Exemple #1
0
def _volume(dimensions, origin, spacing, scalars,
            surface_alpha, resolution, blending, center):
    # Now we can actually construct the visualization
    grid = pyvista.UniformGrid()
    grid.dimensions = dimensions + 1  # inject data on the cells
    grid.origin = origin
    grid.spacing = spacing
    grid.cell_arrays['values'] = scalars

    # Add contour of enclosed volume (use GetOutput instead of
    # GetOutputPort below to avoid updating)
    grid_alg = vtk.vtkCellDataToPointData()
    grid_alg.SetInputDataObject(grid)
    grid_alg.SetPassCellData(False)
    grid_alg.Update()

    if surface_alpha > 0:
        grid_surface = vtk.vtkMarchingContourFilter()
        grid_surface.ComputeNormalsOn()
        grid_surface.ComputeScalarsOff()
        grid_surface.SetInputData(grid_alg.GetOutput())
        grid_surface.SetValue(0, 0.1)
        grid_surface.Update()
        grid_mesh = vtk.vtkPolyDataMapper()
        grid_mesh.SetInputData(grid_surface.GetOutput())
    else:
        grid_mesh = None

    mapper = vtk.vtkSmartVolumeMapper()
    if resolution is None:  # native
        mapper.SetScalarModeToUseCellData()
        mapper.SetInputDataObject(grid)
    else:
        upsampler = vtk.vtkImageReslice()
        upsampler.SetInterpolationModeToLinear()  # default anyway
        upsampler.SetOutputSpacing(*([resolution] * 3))
        upsampler.SetInputConnection(grid_alg.GetOutputPort())
        mapper.SetInputConnection(upsampler.GetOutputPort())
    # Additive, AverageIntensity, and Composite might also be reasonable
    remap = dict(composite='Composite', mip='MaximumIntensity')
    getattr(mapper, f'SetBlendModeTo{remap[blending]}')()
    volume_pos = vtk.vtkVolume()
    volume_pos.SetMapper(mapper)
    dist = grid.length / (np.mean(grid.dimensions) - 1)
    volume_pos.GetProperty().SetScalarOpacityUnitDistance(dist)
    if center is not None and blending == 'mip':
        # We need to create a minimum intensity projection for the neg half
        mapper_neg = vtk.vtkSmartVolumeMapper()
        if resolution is None:  # native
            mapper_neg.SetScalarModeToUseCellData()
            mapper_neg.SetInputDataObject(grid)
        else:
            mapper_neg.SetInputConnection(upsampler.GetOutputPort())
        mapper_neg.SetBlendModeToMinimumIntensity()
        volume_neg = vtk.vtkVolume()
        volume_neg.SetMapper(mapper_neg)
        volume_neg.GetProperty().SetScalarOpacityUnitDistance(dist)
    else:
        volume_neg = None
    return grid, grid_mesh, volume_pos, volume_neg
Exemple #2
0
    def __init__(self, Mgr):
        self.Mgr = Mgr

        self.m_volumeInfo = None
        self.m_selectedIdx = None
        self.m_selectedImage = None

        # self.m_reverseSagittal = False
        # self.m_reverseAxial = False
        self.m_shoulderSide = 'L'
        self.m_orientation = None  ##AXL:1, COR:0, SAG:2

        #Selected Volume CFGS
        self.m_colorFunction = vtk.vtkColorTransferFunction()
        self.m_opacityFunction = vtk.vtkPiecewiseFunction()
        self.m_scalarRange = [0.0, 1.0]
        self.m_volumeProperty = vtk.vtkVolumeProperty()
        self.m_imageProperty = vtk.vtkImageProperty()
        self.m_imageProperty.SetInterpolationTypeToLinear()

        #Volume
        self.volume_data = vtk.vtkImageData()
        self.volume_cropper = vtk.vtkImageData()

        self.m_volumeMapper = vtk.vtkSmartVolumeMapper()
        self.m_volume = vtk.vtkVolume()
        self.m_resliceMapper = [0, 0, 0]
        self.m_resliceActor = [0, 0, 0]

        #Color MAp Volume
        self.m_bShowCAM = False
        self.m_bShowVolume = False
        self.m_colorMapMapper = vtk.vtkSmartVolumeMapper()
        self.m_colorMapVolume = vtk.vtkVolume()
        self.m_colorMapResliceMapper = [None, None, None]
        self.m_colorMapResliceActor = [None, None, None]

        self.resolution = 64

        #Crop View
        self.croppingMapper = vtk.vtkImageSliceMapper()
        self.croppingActor = vtk.vtkImageSlice()

        for i in range(3):
            self.m_resliceMapper[i] = vtk.vtkImageSliceMapper()
            self.m_resliceActor[i] = vtk.vtkImageSlice()
            self.m_colorMapResliceMapper[i] = vtk.vtkImageSliceMapper()
            self.m_colorMapResliceActor[i] = vtk.vtkImageSlice()

        self.m_resliceActor[0].RotateY(90)
        self.m_resliceActor[1].RotateX(-90)
        self.m_colorMapResliceActor[0].RotateY(90)
        self.m_colorMapResliceActor[1].RotateX(-90)

        #Initialize
        self.SetPresetFunctions(
            self.Mgr.mainFrm.volumeWidget.GetCurrentColorIndex())
        self.InitializeVolumeFunctions()
        self.InitializeClassActivationMap()
Exemple #3
0
    def __init__(self):
        # Objects for volume rendering
        self.volume = vtk.vtkVolume()
        self.volumeMapper = vtk.vtkSmartVolumeMapper()
        self.volumeProperty = vtk.vtkVolumeProperty()

        # Objects for slice rendering
        self.sliceActor = vtk.vtkImageActor()
        self.sliceMapper = vtk.vtkImageResliceMapper()
        self.sliceProperty = vtk.vtkImageProperty()

        # Objects for importing and reslicing the data
        self.importer = [vtk.vtkImageImport()]
        self.slice = [vtk.vtkImageResliceToColors()]

        # Objects that point to the output algorithms
        # These must be specified at run time by the implementing class
        self.output = None
        self.sliceOutput = None

        # Some properties of the data
        self.numberOfDataSets = 0
        self.numberOfTimeFrames = 0
        self.currentTimeFrame = 0
        self.dimensions = [0, 0, 0]
Exemple #4
0
 def __init__(self, img, color):
     self.volume = vtk.vtkVolume()
     self.__color = color
     dataImporter = vtk.vtkImageImport()
     simg = np.ascontiguousarray(img, np.uint8)
     dataImporter.CopyImportVoidPointer(simg.data, len(simg.data))
     dataImporter.SetDataScalarTypeToUnsignedChar()
     dataImporter.SetNumberOfScalarComponents(1)
     dataImporter.SetDataExtent(0, simg.shape[2]-1, 0, simg.shape[1]-1, 0, simg.shape[0]-1)
     dataImporter.SetWholeExtent(0, simg.shape[2]-1, 0, simg.shape[1]-1, 0, simg.shape[0]-1)
     self.__smoother = vtk.vtkImageGaussianSmooth()
     self.__smoother.SetStandardDeviation(1, 1, 1)
     self.__smoother.SetInputConnection(dataImporter.GetOutputPort())
     volumeMapper = vtk.vtkSmartVolumeMapper()
     volumeMapper.SetInputConnection(self.__smoother.GetOutputPort())
     self.__volumeProperty = vtk.vtkVolumeProperty()
     self.__colorFunc = vtk.vtkColorTransferFunction()
     self.__alpha = vtk.vtkPiecewiseFunction()
     for i in range(256):
         self.__colorFunc.AddRGBPoint(i, i * color[0], i * color[1], i * color[2])
     self.__alpha.AddPoint(5, .01)
     self.__alpha.AddPoint(10, .03)
     self.__alpha.AddPoint(50, .1)
     self.__alpha.AddPoint(150, .2)
     self.__volumeProperty.SetColor(self.__colorFunc)
     self.__volumeProperty.SetScalarOpacity(self.__alpha)
     self.volume.SetMapper(volumeMapper)
     self.volume.SetProperty(self.__volumeProperty)
Exemple #5
0
    def get_volume(self, color_file=None, volume_opacity=0.25):
        """
        Default Volume Rendering
        Return vtkActor. For volume rendering it is vtkVolume
        """
        if not self.flag_read:
            sys.stderr.write('No Image Loaded.')
            return

        # TEST
        print self.is_blank_image()

        transfer_func = self.get_transfer_functioin(color_file, volume_opacity)
        prop_volume = vtk.vtkVolumeProperty()
        prop_volume.ShadeOff()
        prop_volume.SetColor(transfer_func[0])
        prop_volume.SetScalarOpacity(transfer_func[1])
        prop_volume.SetGradientOpacity(transfer_func[2])
        prop_volume.SetInterpolationTypeToLinear()
        prop_volume.SetAmbient(0.4)
        prop_volume.SetDiffuse(0.6)
        prop_volume.SetSpecular(0.2)

        mapper = vtk.vtkSmartVolumeMapper()
        mapper.SetRequestedRenderMode(0)
        # mapper = vtk.vtkGPUVolumeRayCastMapper()
        mapper.SetInputData(self.reader)

        actor = vtk.vtkVolume()
        actor.SetMapper(mapper)

        actor.SetProperty(prop_volume)

        return actor
Exemple #6
0
  def __init__(self, name, image_data):
    if not isinstance(image_data, vtk.vtkImageData):
      raise TypeError("input has to be vtkImageData")

    self.name = name

    # Create transfer mapping scalar value to opacity.
    opacity_function = vtk.vtkPiecewiseFunction()
    opacity_function.AddPoint(0,   0.0)
    opacity_function.AddPoint(127, 0.0)
    opacity_function.AddPoint(128, 0.2)
    opacity_function.AddPoint(255, 0.2)
    
    # Create transfer mapping scalar value to color.
    color_function = vtk.vtkColorTransferFunction()
    color_function.SetColorSpaceToHSV()
    color_function.AddHSVPoint(0,   0.0, 0.0, 0.0)
    color_function.AddHSVPoint(127, 0.0, 0.0, 0.0)
    color_function.AddHSVPoint(128, 0.0, 0.0, 1.0)
    color_function.AddHSVPoint(255, 0.0, 0.0, 1.0)
    
    volume_property = vtk.vtkVolumeProperty()
    volume_property.SetColor(color_function)
    volume_property.SetScalarOpacity(opacity_function)
    volume_property.ShadeOn()
    volume_property.SetInterpolationTypeToLinear()
    
    volume_mapper = vtk.vtkSmartVolumeMapper()
    volume_mapper.SetInputData(image_data)
    
    self.volume = vtk.vtkVolume()
    self.volume.SetMapper(volume_mapper)
    self.volume.SetProperty(volume_property)
    def get_volume(self, color_file=None, volume_opacity=0.25):
        """
        Default Volume Rendering
        Return vtkActor. For volume rendering it is vtkVolume
        """
        if not self.flag_read:
            sys.stderr.write('No Image Loaded.')
            return

        # TEST
        print self.is_blank_image()

        transfer_func = self.get_transfer_functioin(color_file, volume_opacity)
        prop_volume = vtk.vtkVolumeProperty()
        prop_volume.ShadeOff()
        prop_volume.SetColor(transfer_func[0])
        prop_volume.SetScalarOpacity(transfer_func[1])
        prop_volume.SetGradientOpacity(transfer_func[2])
        prop_volume.SetInterpolationTypeToLinear()
        prop_volume.SetAmbient(0.4)
        prop_volume.SetDiffuse(0.6)
        prop_volume.SetSpecular(0.2)

        mapper = vtk.vtkSmartVolumeMapper()
        mapper.SetRequestedRenderMode(0)
        # mapper = vtk.vtkGPUVolumeRayCastMapper()
        mapper.SetInputData(self.reader)

        actor = vtk.vtkVolume()
        actor.SetMapper(mapper)

        actor.SetProperty(prop_volume)

        return actor
Exemple #8
0
def setup_volume_actor(image, valueRange=None, cmap='jet'):

    volumeMapper = vtk.vtkSmartVolumeMapper()
    if vtk.VTK_MAJOR_VERSION > 5:
        volumeMapper.SetInputData(image)
    else:
        volumeMapper.SetInput(image)

    if not valueRange:
        valueRange = image.GetPointData().GetScalars().GetRange()
    valueSize = valueRange[1] - valueRange[0]
    valueRange = [
        valueRange[0] + valueSize * 0.1, valueRange[0] + valueSize * 0.9
    ]

    volumeProperties = vtk.vtkVolumeProperty()
    volumeProperties.ShadeOff()
    colormap = build_ctf(cmap, valueRange)
    volumeProperties.SetColor(colormap)
    volumeProperties.SetScalarOpacity(build_opacity_function(valueRange))
    scalarOpacityUnitDistance = min(image.GetSpacing()) * 2.0
    volumeProperties.SetScalarOpacityUnitDistance(scalarOpacityUnitDistance)
    volumeProperties.SetGradientOpacity(default_gradient_opacity())
    volumeProperties.SetInterpolationTypeToLinear()

    volumeActor = vtk.vtkVolume()
    volumeActor.SetMapper(volumeMapper)
    volumeActor.SetProperty(volumeProperties)

    return volumeMapper, volumeActor
Exemple #9
0
    def __init__(self, volume_data, genren):
        self.volume_data = volume_data
        self.genren = genren

        self.vtk_renderer = vtk.vtkRenderer()
        self.vtk_renderer.SetBackground(0.310999694819562063,0.3400015259021897,0.4299992370489052)
        self.renWin = vtk.vtkRenderWindow()
        self.renWin.SetSize(256,256)
        self.renWin.AddRenderer(self.vtk_renderer)
        self.renWin.SetWindowName('VTK Renderer')
        self.iren = vtk.vtkRenderWindowInteractor()
        self.iren.SetRenderWindow(self.renWin)

        # compute volume center
        volume_spacing = np.array(self.volume_data.GetSpacing())
        volume_origin = np.array(self.volume_data.GetOrigin())
        volume_dimensions = np.array(self.volume_data.GetDimensions())
        volume_max = volume_origin+volume_spacing*volume_dimensions
        volume_center = 0.5*(volume_origin+volume_max)
        volume_diag = volume_max-volume_origin

        #offset_scale = 2.25
        offset_scale = 2.0

        # camera
        self.camera = self.vtk_renderer.MakeCamera()
        self.camera.SetClippingRange(0.01,offset_scale*2.0*np.linalg.norm(volume_diag))
        self.camera.SetPosition(volume_center[0],volume_center[1],volume_center[2]+offset_scale*np.linalg.norm(volume_diag))
        self.camera.SetFocalPoint(volume_center[0],volume_center[1],volume_center[2])
        self.camera.Elevation(-85)
        self.vtk_renderer.SetActiveCamera(self.camera)

        # color map, opacity map
        self.vtk_color_map = vtk.vtkColorTransferFunction()
        for color_val in self.genren.color_tf:
            self.vtk_color_map.AddRGBPoint(color_val[0],color_val[1],color_val[2],color_val[3])
        vtk_opacity_map = vtk.vtkPiecewiseFunction()
        for op_val in self.genren.opacity_tf:
            vtk_opacity_map.AddPoint(op_val[0],op_val[1])

        # volume properties
        self.prop_volume = vtk.vtkVolumeProperty()
        self.prop_volume.ShadeOff()
        self.prop_volume.SetColor(self.vtk_color_map)
        self.prop_volume.SetScalarOpacity(vtk_opacity_map)
        self.prop_volume.SetInterpolationTypeToLinear()

        # vtk volume render
        self.mapperVolume = vtk.vtkSmartVolumeMapper()
        self.mapperVolume = vtk.vtkGPUVolumeRayCastMapper()
        self.mapperVolume.SetBlendModeToComposite()
        self.mapperVolume.SetInputData(self.volume_data)
        self.actorVolume = vtk.vtkVolume()
        self.actorVolume.SetMapper(self.mapperVolume)
        self.actorVolume.SetProperty(self.prop_volume)
        self.vtk_renderer.AddActor(self.actorVolume)

        self.iren.Initialize()
        def CreateVolumeRayCastMapper(self, volumeSrc):
            volumeMapper = vtk.vtkSmartVolumeMapper()

            volumeMapper.SetInputConnection(volumeSrc.GetOutputPort())
            volumeMapper.SetRequestedRenderModeToRayCast()
            volumeMapper.SetBlendModeToMaximumIntensity()
            volumeMapper.SetInterpolationModeToNearestNeighbor()

            return volumeMapper
Exemple #11
0
 def viz_visualize(self):
     volume = vtk.vtkVolume()
     volumeProperty = vtk.vtkVolumeProperty()
     volumeProperty.SetColor(self.__colorFunc)
     volumeProperty.SetScalarOpacity(self.__alphaChannelFunc)
     volumeProperty.ShadeOn()
     volumeProperty.SetInterpolationTypeToLinear()
     volumeMapper = vtk.vtkSmartVolumeMapper()
     volumeMapper.SetInputConnection(self.__dataImporter.GetOutputPort())
     volume.SetMapper(volumeMapper)
     volume.SetProperty(volumeProperty)
     self.__ren.AddVolume(volume)
Exemple #12
0
    def render_p(self):
        self.ren.RemoveVolume(self.P_volume)
        if not self.config["P"][0]:
            return
        # input: file containing all data for P.vti
        # output: actor for current timestep
        data_path = compose_file_name(self.base_dir, "/P",
                                      self.data_folders["P"], self.time_step)
        reader = vtk.vtkXMLImageDataReader()
        reader.SetFileName(data_path)
        reader.Update()

        spacing = reader.GetOutput().GetSpacing()
        reader.GetOutput().SetSpacing(spacing[0], spacing[1], spacing[2] * 30)
        myrange = reader.GetOutput().GetPointData().GetScalars().GetRange()

        opacityTransferFunction = vtk.vtkPiecewiseFunction()
        opacityTransferFunction.AddPoint(-3781, 0.3)
        opacityTransferFunction.AddPoint(-3097, 0.3)
        opacityTransferFunction.AddPoint(-2488, 0)
        opacityTransferFunction.AddPoint(-1334, 0)
        opacityTransferFunction.AddPoint(-661, 0.001)
        opacityTransferFunction.AddPoint(-354, 0)
        opacityTransferFunction.AddPoint(787, 0.0021)
        opacityTransferFunction.AddPoint(1225, 0.0062)
        opacityTransferFunction.AddPoint(2010, 0.1)
        opacityTransferFunction.AddPoint(2329, 0.1)

        color = vtk.vtkColorTransferFunction()
        # Blue
        color.AddRGBPoint(myrange[0], 0., 1., 0)
        color.AddRGBPoint((myrange[0] + myrange[1]) / 2, 1., 1., 0)
        color.AddRGBPoint(myrange[1], 1., 0., 0.)

        volumeProperty = vtk.vtkVolumeProperty()
        volumeProperty.SetColor(color)
        volumeProperty.SetScalarOpacity(opacityTransferFunction)
        volumeProperty.SetInterpolationTypeToLinear()
        volumeProperty.ShadeOff()

        volumeMapper = vtk.vtkSmartVolumeMapper()
        volumeMapper.SetBlendModeToComposite()
        volumeMapper.SetAutoAdjustSampleDistances(0)
        volumeMapper.SetSampleDistance(0.5)
        volumeMapper.SetInputConnection(reader.GetOutputPort())

        # The volume holds the mapper and the property and
        # can be used to position/orient the volume
        volume = vtk.vtkVolume()
        volume.SetMapper(volumeMapper)
        volume.SetProperty(volumeProperty)
        self.P_volume = volume
        self.ren.AddVolume(volume)
Exemple #13
0
 def RenderImage(self, origImg):
     self.ren[0].RemoveVolume(self.volume)
     self.ren[0].RemoveActor(self.outLine)
     # create volume
     volumeImport = vtk.vtkImageImport()
     data_string = origImg.tostring()
     if origImg.dtype == np.uint16:
         volumeImport.CopyImportVoidPointer(data_string, len(data_string))
         volumeImport.SetDataScalarTypeToUnsignedShort()
     else:
         volumeImport.CopyImportVoidPointer(data_string, len(data_string))
         volumeImport.SetDataScalarTypeToUnsignedChar()
     volumeImport.SetNumberOfScalarComponents(1)
     sz = origImg.shape
     volumeImport.SetDataExtent(0, sz[2] - 1, 0, sz[1] - 1, 0, sz[0] - 1)
     volumeImport.SetWholeExtent(0, sz[2] - 1, 0, sz[1] - 1, 0, sz[0] - 1)
     volumeImport.Update()
     self.importData.DeepCopy(volumeImport.GetOutput())
     self.volumeSize = sz
     #
     alphaChannelFunc = vtk.vtkPiecewiseFunction()
     alphaChannelFunc.AddPoint(0, 0.0)
     alphaChannelFunc.AddPoint(10, 0.9)
     #
     self.colorFunc.AddRGBPoint(1, 0.0, 0.0, 0.0)
     self.colorFunc.AddRGBPoint(255, 1.0, 1.0, 1.0)
     #
     volumeProperty = vtk.vtkVolumeProperty()
     volumeProperty.SetColor(self.colorFunc)
     volumeProperty.SetScalarOpacity(alphaChannelFunc)
     volumeProperty.SetInterpolationType(3)
     #
     volumeMapper = vtk.vtkSmartVolumeMapper()
     volumeMapper.SetBlendModeToMaximumIntensity()
     # volumeMapper.SetVolumeRayCastFunction(compositeFunction)
     volumeMapper.SetInterpolationModeToCubic()
     volumeMapper.SetInputConnection(volumeImport.GetOutputPort())
     self.volume.SetMapper(volumeMapper)
     self.volume.SetProperty(volumeProperty)
     self.volume.SetUserTransform(self.transform)
     #
     outLineSource = vtk.vtkVolumeOutlineSource()
     outLineSource.SetVolumeMapper(volumeMapper)
     outLineMapper = vtk.vtkPolyDataMapper()
     outLineMapper.SetInputConnection(outLineSource.GetOutputPort())
     self.outLine.SetMapper(outLineMapper)
     self.outLine.GetProperty().SetColor(0, 1, 1)
     self.outLine.SetUserTransform(self.transform)
     self.ren[0].AddVolume(self.volume)
     self.ren[0].AddActor(self.outLine)
     self.ren[0].ResetCamera()
Exemple #14
0
def load_atlas(path, intensities, signs):
    '''
    path: path to atlas file
    opacity: opacity of overlayed atlas brain
    '''
    nifti_reader = vtk.vtkNIFTIImageReader()
    nifti_reader.SetFileName(path)
    nifti_reader.Update()

    # intensities = intensities/math.sqrt(np.mean(intensities**2))

    # The following class is used to store transparencyv-values for later
    # retrival. In our case, we want the value 0 to be completly opaque
    alphaChannelFunc = vtk.vtkPiecewiseFunction()
    alphaChannelFunc.AddPoint(0, 0.0)
    for i in range(len(intensities)):
        alphaChannelFunc.AddPoint(i + 1, intensities[i])

    # This class stores color data and can create color tables from a few color
    # points. For this demo, we want the three cubes to be of the colors red
    # green and blue.
    colorFunc = vtk.vtkColorTransferFunction()
    colorFunc.AddRGBPoint(0, 0.0, 0.0, 0.0)
    for i in range(len(signs)):
        if signs[i] < 0: colorFunc.AddRGBPoint(i + 1, 0.0, 0.0, intensities[i])
        elif signs[i] > 0:
            colorFunc.AddRGBPoint(i + 1, intensities[i], 0.0, 0.0)
        else:
            colorFunc.AddRGBPoint(i + 1, 1.0, 1.0, 1.0)

    # The previous two classes stored properties. Because we want to apply
    # these properties to the volume we want to render, we have to store them
    # in a class that stores volume prpoperties.
    volumeProperty = vtk.vtkVolumeProperty()
    volumeProperty.SetColor(colorFunc)
    volumeProperty.SetScalarOpacity(alphaChannelFunc)
    volumeProperty.ShadeOn()

    # We can finally create our volume. We also have to specify the data for
    # it, as well as how the data will be rendered.
    volumeMapper = vtk.vtkSmartVolumeMapper()
    volumeMapper.SetInputDataObject(nifti_reader.GetOutput())

    # The class vtkVolume is used to pair the preaviusly declared volume as
    # well as the properties to be used when rendering that volume.
    volume = vtk.vtkVolume()
    volume.SetMapper(volumeMapper)
    volume.SetProperty(volumeProperty)

    return volume
    def __init__(self, data_dir, opacityL, opacityH):
        # Read the data
        filename = "vol_t00_x5_70_d4pt5_inner.vti"
        vSource = vtk.vtkXMLImageDataReader()
        vSource.SetFileName(filename)
        vSource.Update()

        #blocks = reader1.GetOutput()
        #b0 = blocks.GetBlock(0)

        # Setup VTK environment

        #Create a mapper and actor
        opacityTransferFunction = vtk.vtkPiecewiseFunction()
        opacityTransferFunction.AddPoint(opacityL, 0.0)
        opacityTransferFunction.AddPoint(opacityH, 0.8)

        colorTransferFunction = vtk.vtkColorTransferFunction()
        colorTransferFunction.AddRGBPoint(0.0, 0.0, 0.0, 0.0)
        colorTransferFunction.AddRGBPoint(64.0, 1.0, 0.2, 0.4)
        #colorTransferFunction.AddRGBPoint(128.0, 0.0, 0.0, 1.0)
        #colorTransferFunction.AddRGBPoint(192.0, 0.0, 1.0, 0.0)

        volumeProperty = vtk.vtkVolumeProperty()
        volumeProperty.SetColor(colorTransferFunction)
        #volumeProperty.SetGradientOpacity(gradientTransferFunction)
        volumeProperty.SetScalarOpacity(opacityTransferFunction)
        #volumeProperty.ShadeOn()
        volumeProperty.SetInterpolationTypeToLinear()
        volumeProperty.SetAmbient(1.0)
        volumeProperty.SetDiffuse(0.7)
        volumeProperty.SetSpecular(0.5)
        volumeMapper = vtk.vtkSmartVolumeMapper()
        volumeMapper.SetInputConnection(vSource.GetOutputPort())
        #volumeMapper.CroppingOn()
        volume = vtk.vtkVolume()
        volume.SetMapper(volumeMapper)
        volume.SetProperty(volumeProperty)
        volume.Update()
        #renderer.AddVolume(volume)

        # Mapper
        #glyph_mapper =  vtk.vtkPolyDataMapper()
        #glyph_mapper.SetInputConnection(glyphs.GetOutputPort())
        #glyph_actor = vtk.vtkActor()
        #glyph_actor.SetMapper(glyph_mapper)

        #self.b0 = b0
        self.volume = volume
        self.vSource = vSource
Exemple #16
0
def load_atlas(path, intensities, signs):
    '''
    path: path to atlas file
    opacity: opacity of overlayed atlas brain
    '''
    nifti_reader = vtk.vtkNIFTIImageReader()
    nifti_reader.SetFileName(path)
    nifti_reader.Update()


    # intensities = intensities/math.sqrt(np.mean(intensities**2))

    # The following class is used to store transparencyv-values for later
    # retrival. In our case, we want the value 0 to be completly opaque
    alphaChannelFunc = vtk.vtkPiecewiseFunction()
    alphaChannelFunc.AddPoint(0, 0.0)
    for i in range(len(intensities)):
        alphaChannelFunc.AddPoint(i+1, intensities[i])

    # This class stores color data and can create color tables from a few color
    # points. For this demo, we want the three cubes to be of the colors red
    # green and blue.
    colorFunc = vtk.vtkColorTransferFunction()
    colorFunc.AddRGBPoint(0, 0.0, 0.0, 0.0)
    for i in range(len(signs)):
        if signs[i] < 0: colorFunc.AddRGBPoint(i+1, 0.0, 0.0, intensities[i])
        elif signs[i] > 0: colorFunc.AddRGBPoint(i+1, intensities[i], 0.0, 0.0)
        else: colorFunc.AddRGBPoint(i+1, 1.0, 1.0, 1.0)

    # The previous two classes stored properties. Because we want to apply
    # these properties to the volume we want to render, we have to store them
    # in a class that stores volume prpoperties.
    volumeProperty = vtk.vtkVolumeProperty()
    volumeProperty.SetColor(colorFunc)
    volumeProperty.SetScalarOpacity(alphaChannelFunc)
    volumeProperty.ShadeOn()

    # We can finally create our volume. We also have to specify the data for
    # it, as well as how the data will be rendered.
    volumeMapper = vtk.vtkSmartVolumeMapper()
    volumeMapper.SetInputDataObject(nifti_reader.GetOutput())

    # The class vtkVolume is used to pair the preaviusly declared volume as
    # well as the properties to be used when rendering that volume.
    volume = vtk.vtkVolume()
    volume.SetMapper(volumeMapper)
    volume.SetProperty(volumeProperty)

    return volume
Exemple #17
0
    def __init__(self):
        super().__init__()
        self.vtk_widget = QVTKRenderWindowInteractor(self)
        self.main_layout = QGridLayout()
        self.main_layout.addWidget(self.vtk_widget)
        self.setLayout(self.main_layout)

        self.vtk_renderer = vtk.vtkRenderer()
        self.vtk_render_win = self.vtk_widget.GetRenderWindow()
        self.vtk_render_win.AddRenderer(self.vtk_renderer)
        self.vtk_interactor = self.vtk_render_win.GetInteractor()
        self.vtk_interactor.Initialize()

        self.vtk_volume_mapper = vtk.vtkSmartVolumeMapper()
        pass
 def opImplement(self):
     opacity = vtk.vtkPiecewiseFunction();
     #x is scaler value , y is opacity value
     opacity.AddPoint(IMAGEOUT,0.0);
     opacity.AddPoint(IMAGEIN  ,1.0);
     #x is scaler value , other is rgb value
     color = vtk.vtkColorTransferFunction();
     color.AddRGBPoint(IMAGEIN  ,255.0/255.0,255.0/255.0,255.0/255.0);
     volumeProperty = vtk.vtkVolumeProperty();
     volumeProperty.ShadeOn();
     volumeProperty.SetScalarOpacity(opacity)
     volumeProperty.SetColor(color);
     mapper = vtk.vtkSmartVolumeMapper();
     mapper.SetInputData(self.data);
     volume = vtk.vtkVolume();
     volume.SetMapper(mapper);
     volume.SetProperty(volumeProperty);
     return volume;
Exemple #19
0
    def render_cloud(self):
        self.ren.RemoveVolume(self.cloud_volume)
        if not self.config["CLOUD"][0]:
            return
        data_path = compose_file_name(self.base_dir, "/CLOUD",
                                      self.data_folders["CLOUD"],
                                      self.time_step)
        reader = vtk.vtkXMLImageDataReader()
        reader.SetFileName(data_path)
        reader.Update()

        spacing = reader.GetOutput().GetSpacing()
        reader.GetOutput().SetSpacing(spacing[0], spacing[1], spacing[2] * 30)
        myrange = reader.GetOutput().GetPointData().GetScalars().GetRange()

        opacityTransferFunction = vtk.vtkPiecewiseFunction()
        opacityTransferFunction.AddPoint(myrange[0], 0.0)
        opacityTransferFunction.AddPoint(myrange[1], 0.1)

        color = vtk.vtkColorTransferFunction()
        # Blue
        color.AddRGBPoint(myrange[0], 0.8, 0.8, 0.8)
        color.AddRGBPoint((myrange[0] + myrange[1]) / 2, 1., 1., 1)
        color.AddRGBPoint(myrange[1], 0.8, 0.8, 0.8)

        volumeProperty = vtk.vtkVolumeProperty()
        volumeProperty.SetColor(color)
        volumeProperty.SetScalarOpacity(opacityTransferFunction)
        volumeProperty.SetInterpolationTypeToLinear()
        volumeProperty.ShadeOff()

        volumeMapper = vtk.vtkSmartVolumeMapper()
        volumeMapper.SetBlendModeToComposite()
        volumeMapper.SetAutoAdjustSampleDistances(0)
        volumeMapper.SetSampleDistance(0.5)
        volumeMapper.SetInputConnection(reader.GetOutputPort())

        # The volume holds the mapper and the property and
        # can be used to position/orient the volume
        volume = vtk.vtkVolume()
        volume.SetMapper(volumeMapper)
        volume.SetProperty(volumeProperty)
        self.cloud_volume = volume
        self.ren.AddVolume(volume)
Exemple #20
0
def makeVolumeRenderingPipeline(in_volume):
    dataImporter = vtk.vtkImageImport()

    if in_volume.dtype == numpy.uint8:
        dataImporter.SetDataScalarTypeToUnsignedChar()
    elif in_volume.dtype == numpy.uint16:
        dataImporter.SetDataScalarTypeToUnsignedShort()
    elif in_volume.dtype == numpy.int32:
        dataImporter.SetDataScalarTypeToInt()
    elif in_volume.dtype == numpy.int16:
        dataImporter.SetDataScalarTypeToShort()
    else:
        raise RuntimeError("unknown data type %r of volume" %
                           (in_volume.dtype, ))

    dataImporter.SetImportVoidPointer(in_volume, len(in_volume))
    dataImporter.SetNumberOfScalarComponents(1)
    extent = [
        0, in_volume.shape[2] - 1, 0, in_volume.shape[1] - 1, 0,
        in_volume.shape[0] - 1
    ]
    dataImporter.SetDataExtent(*extent)
    dataImporter.SetWholeExtent(*extent)

    alphaChannelFunc = vtk.vtkPiecewiseFunction()
    alphaChannelFunc.AddPoint(0, 0.0)
    for i in range(1, NOBJECTS):
        alphaChannelFunc.AddPoint(i, 1.0)

    colorFunc = vtk.vtkColorTransferFunction()

    volumeMapper = vtk.vtkSmartVolumeMapper()
    volumeMapper.SetInputConnection(dataImporter.GetOutputPort())

    volumeProperty = vtk.vtkVolumeProperty()
    volumeProperty.SetColor(colorFunc)
    volumeProperty.SetScalarOpacity(alphaChannelFunc)
    volumeProperty.ShadeOn()

    volume = vtk.vtkVolume()
    volume.SetMapper(volumeMapper)
    volume.SetProperty(volumeProperty)

    return dataImporter, colorFunc, volume, volumeMapper
Exemple #21
0
    def showVolume(self, vtkImageData, preserveState):
        '''Shows volume of image.'''
        producer = vtk.vtkTrivialProducer()
        producer.SetOutput(vtkImageData)

        flip = vtk.vtkImageFlip()
        # flip over y axis
        flip.SetFilteredAxis(1)
        flip.SetInputConnection(producer.GetOutputPort())

        mapper = vtk.vtkSmartVolumeMapper()
        mapper.SetInputConnection(flip.GetOutputPort())

        scalarRange = vtkImageData.GetScalarRange()

        opacity = vtk.vtkPiecewiseFunction()
        opacity.AddPoint(scalarRange[0], 0.2)
        opacity.AddPoint(scalarRange[1], 0.9)

        color = vtk.vtkColorTransferFunction()
        color.AddRGBPoint(scalarRange[0], 0, 0, 0)
        color.AddRGBPoint(scalarRange[1], 1, 1, 1)

        prop = vtk.vtkVolumeProperty()
        prop.ShadeOff()
        prop.SetInterpolationType(vtk.VTK_LINEAR_INTERPOLATION)
        prop.SetColor(color)
        prop.SetScalarOpacity(opacity)

        # save tubes and property if preserving state
        if preserveState and self.volume:
            prop = self.volume.GetProperty()
            self.volumeRenderer.RemoveViewProp(self.volume)
        else:
            self.volumeRenderer.RemoveAllViewProps()

        self.volume = vtk.vtkVolume()
        self.volume.SetMapper(mapper)
        self.volume.SetProperty(prop)

        self.volumeRenderer.AddViewProp(self.volume)
        self.volumeRenderer.ResetCamera()
Exemple #22
0
def makeVolumeRenderingPipeline(in_volume):
    dataImporter = vtk.vtkImageImport()

    if in_volume.dtype == numpy.uint8:
        dataImporter.SetDataScalarTypeToUnsignedChar()
    elif in_volume.dtype == numpy.uint16:
        dataImporter.SetDataScalarTypeToUnsignedShort()
    elif in_volume.dtype == numpy.int32:
        dataImporter.SetDataScalarTypeToInt()
    elif in_volume.dtype == numpy.int16:
        dataImporter.SetDataScalarTypeToShort()
    else:
        raise RuntimeError("unknown data type %r of volume" % (in_volume.dtype,))

    dataImporter.SetImportVoidPointer(in_volume, len(in_volume))
    dataImporter.SetNumberOfScalarComponents(1)
    extent = [0, in_volume.shape[2]-1, 0, in_volume.shape[1]-1, 0, in_volume.shape[0]-1]
    dataImporter.SetDataExtent(*extent)
    dataImporter.SetWholeExtent(*extent)

    alphaChannelFunc = vtk.vtkPiecewiseFunction()
    alphaChannelFunc.AddPoint(0, 0.0)
    for i in range(1, NOBJECTS):
        alphaChannelFunc.AddPoint(i, 1.0)

    colorFunc = vtk.vtkColorTransferFunction()

    volumeMapper = vtk.vtkSmartVolumeMapper()
    volumeMapper.SetInputConnection(dataImporter.GetOutputPort())

    volumeProperty = vtk.vtkVolumeProperty()
    volumeProperty.SetColor(colorFunc)
    volumeProperty.SetScalarOpacity(alphaChannelFunc)
    volumeProperty.ShadeOn()

    volume = vtk.vtkVolume()
    volume.SetMapper(volumeMapper)
    volume.SetProperty(volumeProperty)

    return dataImporter, colorFunc, volume, volumeMapper
    def __init__(self, data_dir, opacityL, opacityH):
        # Read the data
        filename = "inclusions_all.vti"
        vSource = vtk.vtkXMLImageDataReader()
        vSource.SetFileName(filename)
        vSource.Update()

        #Create a mapper and actor
        opacityTransferFunction = vtk.vtkPiecewiseFunction()
        opacityTransferFunction.AddPoint(opacityL, 0.0)
        opacityTransferFunction.AddPoint(opacityH, 0.8)

        colorTransferFunction = vtk.vtkColorTransferFunction()
        colorTransferFunction.AddRGBPoint(0.0, 0.0, 0.0, 0.0)
        colorTransferFunction.AddRGBPoint(64.0, 1.0, 0.2, 0.4)
        colorTransferFunction.AddRGBPoint(128.0, 0.0, 0.0, 1.0)
        colorTransferFunction.AddRGBPoint(192.0, 0.0, 1.0, 0.0)

        volumeProperty = vtk.vtkVolumeProperty()
        #volumeProperty.SetColor(colorTransferFunction)
        #volumeProperty.SetGradientOpacity(gradientTransferFunction)
        volumeProperty.SetScalarOpacity(opacityTransferFunction)
        #volumeProperty.ShadeOn()
        volumeProperty.SetInterpolationTypeToLinear()
        volumeProperty.SetAmbient(1.0)
        volumeProperty.SetDiffuse(0.7)
        volumeProperty.SetSpecular(0.5)
        volumeMapper = vtk.vtkSmartVolumeMapper()
        volumeMapper.SetInputConnection(vSource.GetOutputPort())
        #volumeMapper.CroppingOn()
        volume = vtk.vtkVolume()
        volume.SetMapper(volumeMapper)
        volume.SetProperty(volumeProperty)
        volume.Update()
        #renderer.AddVolume(volume)

        #self.b0 = b0
        self.volume = volume
        self.vSource = vSource
 def __init__(self, cmData, reslice=None):
     self.cmData = cmData
     self._min = 0
     self._max = 255
     self.dataImport = vtk.vtkImageImport()
     self.dataImport.SetDataScalarTypeToUnsignedChar()
     self.dataImport.SetNumberOfScalarComponents(1)
     self.alphaFunc = vtk.vtkPiecewiseFunction()
     self.colorFunc = vtk.vtkColorTransferFunction()
     self.setupColorFunc()
     self.prop = vtk.vtkVolumeProperty()
     self.prop.SetColor(self.colorFunc)
     self.prop.SetScalarOpacity(self.alphaFunc)
     self.mapper = vtk.vtkSmartVolumeMapper()
     self.mapper.SetBlendModeToMaximumIntensity()
     if reslice is not None:
         reslice.SetInputConnection(self.dataImport.GetOutputPort())
         self.mapper.SetInputConnection(reslice.GetOutputPort())
     else:
         self.mapper.SetInputConnection(self.dataImport.GetOutputPort())
     self.volume = vtk.vtkVolume()
     self.volume.SetMapper(self.mapper)
     self.volume.SetProperty(self.prop)
Exemple #25
0
def _from_itk_to_vtk(image_type,
                     image_data,
                     color_func=None,
                     opacity_func=None):
    # convert itk to vtk image data
    itk_to_vtk = itk.ImageToVTKImageFilter[image_type].New()
    itk_to_vtk.SetInput(image_data)
    itk_to_vtk.Update()

    vtk_image_data = itk_to_vtk.GetOutput()

    # convert vtk image data to vtk object for slicer rendering
    cast_filter = vtk.vtkImageCast()
    cast_filter.SetInputData(vtk_image_data)
    cast_filter.Update()

    # convert vtk image data to vtk volume for volume rendering
    vol = vtk.vtkVolume()
    mapper = vtk.vtkSmartVolumeMapper()
    mapper.SetInputData(vtk_image_data)
    vol.SetMapper(mapper)

    if color_func is None:
        color_func = vtk.vtkColorTransferFunction()

    if opacity_func is None:
        opacity_func = vtk.vtkPiecewiseFunction()

    volume_property = vtk.vtkVolumeProperty()
    volume_property.SetColor(color_func)
    volume_property.SetScalarOpacity(opacity_func)
    volume_property.SetInterpolationTypeToLinear()

    vol.SetProperty(volume_property)
    vol.SetMapper(mapper)

    return cast_filter, vol
colorFunc = vtk.vtkColorTransferFunction()
colorFunc.AddRGBPoint(0, 0.75, 0.75, 0.75)
colorFunc.AddRGBPoint(128, 0.75, 0.75, 0.75)
colorFunc.AddRGBPoint(255, 0.5, 0.5, 0.5)

volProp = vtk.vtkVolumeProperty()
volProp.SetColor(colorFunc)
volProp.ShadeOn()
volProp.SetAmbient(0.25)
volProp.SetDiffuse(0.75)
volProp.SetSpecular(0)
volProp.SetScalarOpacity(alphaFunc)
volProp.SetInterpolationTypeToLinear()

# volMapper = vtk.vtkFixedPointVolumeRayCastMapper()
volMapper = vtk.vtkSmartVolumeMapper()
volMapper.SetInputConnection(reader.GetOutputPort())

vol = vtk.vtkVolume()
vol.SetMapper(volMapper)
vol.SetProperty(volProp)

renderer = vtk.vtkRenderer()
renderer.AddVolume(vol)
renderer.SetBackground(colors.GetColor3d('White'))
renderer.ResetCamera()
renderer.GetActiveCamera().Azimuth(-90)
renderer.GetActiveCamera().Elevation(-90)
# renderer.GetActiveCamera().Roll(180)
renderer.GetActiveCamera().Zoom(1.5)
    def initialize(self):
        global renderer, renderWindow, renderWindowInteractor, cone, mapper, actor

        # Bring used components
        self.registerVtkWebProtocol(protocols.vtkWebMouseHandler())
        self.registerVtkWebProtocol(protocols.vtkWebViewPort())
        self.registerVtkWebProtocol(
            protocols.vtkWebPublishImageDelivery(decode=False))
        self.registerVtkWebProtocol(protocols.vtkWebViewPortGeometryDelivery())

        # Update authentication key to use
        self.updateSecret(_WebCone.authKey)

        # tell the C++ web app to use no encoding.
        # ParaViewWebPublishImageDelivery must be set to decode=False to match.
        self.getApplication().SetImageEncoding(0)

        # Create default pipeline (Only once for all the session)
        if not _WebCone.view:
            # VTK specific code
            renderer = vtk.vtkRenderer()
            renderWindow = vtk.vtkRenderWindow()
            renderWindow.AddRenderer(renderer)

            renderWindowInteractor = vtk.vtkRenderWindowInteractor()
            renderWindowInteractor.SetRenderWindow(renderWindow)
            renderWindowInteractor.GetInteractorStyle(
            ).SetCurrentStyleToTrackballCamera()

            # cone = vtk.vtkConeSource()
            # mapper = vtk.vtkPolyDataMapper()
            # actor = vtk.vtkActor()

            # mapper.SetInputConnection(cone.GetOutputPort())
            # actor.SetMapper(mapper)

            # renderer.AddActor(actor)

            # load nrrd
            reader = vtk.vtkNrrdReader()
            reader.SetFileName('C:\\Users\\Mat\\Desktop\\tardiva3.0.nrrd')
            reader.Update()

            # The volume will be displayed by ray-cast alpha compositing.
            # A ray-cast mapper is needed to do the ray-casting.
            # volume_mapper = vtk.vtkFixedPointVolumeRayCastMapper()
            volume_mapper = vtk.vtkSmartVolumeMapper()
            volume_mapper.SetInputConnection(reader.GetOutputPort())
            volume_mapper.SetSampleDistance(0.5)

            # The color transfer function maps voxel intensities to colors.
            # It is modality-specific, and often anatomy-specific as well.
            # The goal is to one color for flesh (between 500 and 1000)
            # and another color for bone (1150 and over).
            volume_color = vtk.vtkColorTransferFunction()
            volume_color.AddRGBPoint(0, 0.2, 0.2, 0.7)
            volume_color.AddRGBPoint(500, 240.0 / 255.0, 184.0 / 255.0,
                                     160.0 / 255.0)
            volume_color.AddRGBPoint(1000, 240.0 / 255.0, 184.0 / 255.0,
                                     160.0 / 255.0)
            volume_color.AddRGBPoint(1150, 1.0, 1.0, 240.0 / 255.0)  # Ivory

            # The opacity transfer function is used to control the opacity
            # of different tissue types.
            volume_scalar_opacity = vtk.vtkPiecewiseFunction()
            volume_scalar_opacity.AddPoint(0, 0.00)
            volume_scalar_opacity.AddPoint(500, 0.15)
            volume_scalar_opacity.AddPoint(1000, 0.15)
            volume_scalar_opacity.AddPoint(1150, 0.85)

            # The gradient opacity function is used to decrease the opacity
            # in the 'flat' regions of the volume while maintaining the opacity
            # at the boundaries between tissue types.  The gradient is measured
            # as the amount by which the intensity changes over unit distance.
            # For most medical data, the unit distance is 1mm.
            volume_gradient_opacity = vtk.vtkPiecewiseFunction()
            volume_gradient_opacity.AddPoint(0, 0.0)
            volume_gradient_opacity.AddPoint(90, 0.5)
            volume_gradient_opacity.AddPoint(100, 1.0)

            # The VolumeProperty attaches the color and opacity functions to the
            # volume, and sets other volume properties.  The interpolation should
            # be set to linear to do a high-quality rendering.  The ShadeOn option
            # turns on directional lighting, which will usually enhance the
            # appearance of the volume and make it look more '3D'.  However,
            # the quality of the shading depends on how accurately the gradient
            # of the volume can be calculated, and for noisy data the gradient
            # estimation will be very poor.  The impact of the shading can be
            # decreased by increasing the Ambient coefficient while decreasing
            # the Diffuse and Specular coefficient.  To increase the impact
            # of shading, decrease the Ambient and increase the Diffuse and Specular.
            volume_property = vtk.vtkVolumeProperty()
            volume_property.SetColor(volume_color)
            volume_property.SetScalarOpacity(volume_scalar_opacity)
            volume_property.SetGradientOpacity(volume_gradient_opacity)
            volume_property.SetInterpolationTypeToLinear()
            volume_property.ShadeOn()
            volume_property.SetAmbient(0.4)
            volume_property.SetDiffuse(0.6)
            volume_property.SetSpecular(0.2)

            # The vtkVolume is a vtkProp3D (like a vtkActor) and controls the position
            # and orientation of the volume in world coordinates.
            volumeActor = vtk.vtkVolume()
            volumeActor.SetMapper(volume_mapper)
            volumeActor.SetProperty(volume_property)

            # Finally, add the volume to the renderer
            renderer.AddActor(volumeActor)

            ##########################
            # renderer.AddActor(actor)

            # render
            renderer.ResetCamera()
            renderWindow.Render()

            # VTK Web application specific
            _WebCone.view = renderWindow
            self.getApplication().GetObjectIdMap().SetActiveObject(
                "VIEW", renderWindow)
Exemple #28
0
camera = renderer.MakeCamera()
camera.SetPosition(
    volume_center[0], volume_center[1],
    volume_center[2] + offset_scale * np.linalg.norm(volume_diag))
camera.SetFocalPoint(volume_center[0], volume_center[1], volume_center[2])
#camera.SetParallelScale(135.24329927948372)
camera.Elevation(-85)
renderer.SetActiveCamera(camera)

# volume properties
prop_volume = vtk.vtkVolumeProperty()
prop_volume.ShadeOff()
prop_volume.SetInterpolationTypeToLinear()

# vtk volume renderer
mapperVolume = vtk.vtkSmartVolumeMapper()
mapperVolume.SetRequestedRenderModeToGPU()
#mapperVolume.SetRequestedRenderModeToRayCast()
mapperVolume.SetBlendModeToComposite()
mapperVolume.SetInputData(volume_data)
actorVolume = vtk.vtkVolume()
actorVolume.SetMapper(mapperVolume)
actorVolume.SetProperty(prop_volume)
renderer.AddActor(actorVolume)

if not os.path.exists(base_dir + 'imgs'):
    os.makedirs(base_dir + 'imgs')
if not os.path.exists(base_dir + 'inputs'):
    os.makedirs(base_dir + 'inputs')

output_img_dir = base_dir + 'imgs/'
def main(argv):
	if len(argv) < 3:
		sys.stderr.write("Usage: %s <volume.mhd> <trace.vtk>\n" % argv[0])
		return 1

	segmented_volume_filename, trace_filename = argv[1:3]

	for filename in [ segmented_volume_filename, trace_filename ]:
		if not os.path.exists(filename):
			sys.stderr.write("file '%s' not found\n" % filename)
			return 1

	ren = vtk.vtkRenderer()
	renWin = vtk.vtkRenderWindow()
	renWin.AddRenderer(ren)
	renWin.SetSize(WIDTH, HEIGHT)

	# create a renderwindowinteractor
	iren = vtk.vtkRenderWindowInteractor()
	iren.SetRenderWindow(renWin)

	antique_white = [ 0.9804, 0.9216, 0.8431 ]
	line_width = 5

	centerline = vtk.vtkPolyDataReader()
	for centerline in [centerline]:
		for r in [centerline]:
			r.SetFileName( trace_filename )
			r.ReadAllVectorsOn()
			r.ReadAllScalarsOn()
			r.Update()
			centerline_mapper = vtk.vtkPolyDataMapper()
			for m in [centerline_mapper]:
				m.SetInput( centerline.GetOutput() )
			centreline_actor = vtk.vtkActor()
			for a in [centreline_actor]:
				a.SetMapper( centerline_mapper )
				a.GetProperty().SetColor( *antique_white )
				a.GetProperty().SetLineWidth( line_width );

	# Create transfer mapping scalar value to opacity
	opacity_transfer_function = vtk.vtkPiecewiseFunction()
	for tf in [opacity_transfer_function]:
		tf.AddPoint( 20 , 0.0)
		tf.AddPoint( 255 , 0.2)
	# Create transfer mapping scalar value to color
	color_transfer_function = vtk.vtkColorTransferFunction()
	for tf in [color_transfer_function]:
		tf.AddRGBPoint(0.0, 0.0, 0.0, 0.0)
		tf.AddRGBPoint(64.0, 0.2, 0.0, 0.0)
		tf.AddRGBPoint(128.0, 0.0, 0.0, 1.0)
		tf.AddRGBPoint( 192.0, 0.0, 1.0, 0.0)
		tf.AddRGBPoint( 255.0, 0.0, 0.2, 0.0)
		tf.SetColorSpaceToDiverging()
	# The property describes how the data will look
	volume_property = vtk.vtkVolumeProperty()
	for vp in [volume_property]:
		vp.SetColor(color_transfer_function)
		vp.SetScalarOpacity(opacity_transfer_function)

	segmentation = vtk.vtkMetaImageReader()
	for segmentation in [segmentation]:
		for r in [segmentation]:
			r.SetFileName( segmented_volume_filename )
			r.Update()

		segmentation_outline_filter = vtk.vtkOutlineFilter()
		for f in [segmentation_outline_filter]:
			f.SetInput( segmentation.GetOutput() )
		segmentation_outline_mapper = vtk.vtkPolyDataMapper()
		for m in [segmentation_outline_mapper]:
			m.SetInputConnection( segmentation_outline_filter.GetOutputPort() )
		segmentation_outline_actor = vtk.vtkActor()
		for a in [segmentation_outline_actor]:
			a.SetMapper( segmentation_outline_mapper )

		segmentation_mapper = vtk.vtkSmartVolumeMapper()
		for m in [segmentation_mapper]:
			m.SetInput( segmentation.GetOutput() )
		segmentation_actor = vtk.vtkVolume()
		for a in [segmentation_actor]:
			a.SetMapper( segmentation_mapper )
			a.SetProperty( volume_property )




		for actor in [ centreline_actor, segmentation_actor, segmentation_outline_actor]:
			ren.AddActor( actor )

	iren.Initialize()
	renWin.Render()

	iren.Start()
Exemple #30
0
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)

#---------------------------------------------------------
# read the volume
reader = vtk.vtkImageReader2()
reader.SetDataExtent(0,63,0,63,0,92)
reader.SetFileNameSliceOffset(1)
reader.SetDataScalarTypeToUnsignedShort()
reader.SetDataByteOrderToLittleEndian()
reader.SetFilePrefix(str(VTK_DATA_ROOT) + "/Data/headsq/quarter")
reader.SetDataSpacing(3.2,3.2,1.5)

#---------------------------------------------------------
# set up the volume rendering
volumeMapper = vtk.vtkSmartVolumeMapper()#vtk.vtkVolumeTextureMapper3D()
volumeMapper.SetInputConnection(reader.GetOutputPort())
volumeMapper.CroppingOn()
volumeMapper.SetCroppingRegionPlanes((0.0, 141.6, 0.0, 201.6, 0.0, 138.0))

volumeColor = vtk.vtkColorTransferFunction()
volumeColor.AddRGBPoint(0,0.0,0.0,0.0)
volumeColor.AddRGBPoint(180,0.3,0.1,0.2)
volumeColor.AddRGBPoint(1000,1.0,0.7,0.6)
volumeColor.AddRGBPoint(2000,1.0,1.0,0.9)

volumeScalarOpacity = vtk.vtkPiecewiseFunction()
volumeScalarOpacity.AddPoint(0,0.0)
volumeScalarOpacity.AddPoint(180,0.0)
volumeScalarOpacity.AddPoint(1000,0.2)
volumeScalarOpacity.AddPoint(2000,0.8)
Exemple #31
0
    def BuildView(self):

        # ensure python 2-3 compatibility for checking string type (difference with unicode str handeling)
        PY3 = sys.version_info[0] == 3

        if not self.vmtkRenderer:
            self.vmtkRenderer = vmtkrenderer.vmtkRenderer()
            self.vmtkRenderer.Initialize()
            self.OwnRenderer = 1

        self.vmtkRenderer.RegisterScript(self)

        if (self.ArrayName != ''):
            self.Image.GetPointData().SetActiveScalars(self.ArrayName)

        if PY3:
            string_types = str,
        else:
            string_types = basestring,
        if not isinstance(self.VolumeRenderingMethod, string_types):
            self.PrintError(
                'Specified Rendering Method is not of required "string" type')

        # create volume mapper and apply requested volume rendering method
        volumeMapper = vtk.vtkSmartVolumeMapper()
        if self.VolumeRenderingMethod.lower() == 'default':
            volumeMapper.SetRequestedRenderModeToDefault()
        elif self.VolumeRenderingMethod.lower() == 'gpu':
            volumeMapper.SetRequestedRenderModeToGPU()
        elif self.VolumeRenderingMethod.lower() == 'ospray':
            volumeMapper.SetRequestedRenderModeToOSPRay()
        elif self.VolumeRenderingMethod.lower() == 'raycast':
            volumeMapper.SetRequestedRenderModeToRayCast()
        else:
            self.PrintError(
                'Specified Rendering Method: ' + self.VolumeRenderingMethod +
                ' not supported. Please choose from ["default", "gpu", "ospray", "raycast"]'
            )
        volumeMapper.SetInputData(self.Image)
        volumeMapper.SetBlendModeToComposite()

        # parse the xml file which is loaded in the same path as the vmtkimagevolumeviewer.py file at runtime
        presetElementTree = ET.parse(
            os.path.join(os.path.dirname(__file__), 'share',
                         'vmtkimagevolumeviewerpresets.xml'))
        presetRoot = presetElementTree.getroot()
        volProperties = presetRoot.findall(
            'VolumeProperty[@name="' + self.Preset +
            '"]')  # should return a list with only one element
        volPropertiesDict = volProperties[0].attrib

        def chunks(l, n):
            """Yield successive n-sized chunks from l."""
            if PY3:
                range_func = range
            else:
                range_func = xrange
            for i in range_func(0, len(l), n):
                yield l[i:i + n]

        # need to convert the space seperated string displaying values into a list of floats
        colorList = [
            float(i) for i in volPropertiesDict['colorTransfer'].split()
        ]
        gradientOpacityList = [
            float(i) for i in volPropertiesDict['gradientOpacity'].split()
        ]
        opacityList = [
            float(i) for i in volPropertiesDict['scalarOpacity'].split()
        ]

        # create an array of arrays with each list split into subarrays of desired size
        colorMapList = chunks(colorList, 4)
        gradientOpacityMapList = chunks(gradientOpacityList, 2)
        opacityMapList = chunks(opacityList, 2)

        # create vtk objects from the mapped lists (now arrays of arrays)
        self.ColorTransferFunction = self.BuildVTKColorTransferFunction(
            colorMapList)
        self.GradientOpacityTransferFunction = self.BuildVTKPiecewiseFunction(
            gradientOpacityMapList)
        self.OpacityTransferFunction = self.BuildVTKPiecewiseFunction(
            opacityMapList)

        # assign other properties from the element tree to variables with the appropriate type
        self.InterpolationType = int(volPropertiesDict['interpolation'])
        self.Shade = int(volPropertiesDict['shade'])
        self.SpecularPower = float(volPropertiesDict['specularPower'])
        self.Specular = float(volPropertiesDict['specular'])
        self.Diffuse = float(volPropertiesDict['diffuse'])
        self.Ambient = float(volPropertiesDict['ambient'])

        # set transfer function and lighting properties of the vtk volume object
        volumeProperty = vtk.vtkVolumeProperty()
        volumeProperty.SetScalarOpacity(self.OpacityTransferFunction)
        volumeProperty.SetGradientOpacity(self.GradientOpacityTransferFunction)
        volumeProperty.SetColor(self.ColorTransferFunction)
        volumeProperty.SetInterpolationType(self.InterpolationType)
        volumeProperty.SetShade(self.Shade)
        volumeProperty.SetSpecularPower(self.SpecularPower)
        volumeProperty.SetSpecular(self.Specular)
        volumeProperty.SetDiffuse(self.Diffuse)
        volumeProperty.SetAmbient(self.Ambient)

        # create the volume from the mapper (defining image data and render mode) with the defined properties
        # this is the last pipeline step applied. self.Volume just needs to now be added to the Renderer
        self.Volume = vtk.vtkVolume()
        self.Volume.SetMapper(volumeMapper)
        self.Volume.SetProperty(volumeProperty)

        # add the actors to the renderer
        self.vmtkRenderer.Renderer.AddVolume(self.Volume)

        # This next section is responsible for creating the box outline around the volume's data extent.
        if self.BoxOutline:
            outline = vtk.vtkOutlineFilter()
            outline.SetInputData(self.Image)
            outlineMapper = vtk.vtkPolyDataMapper()
            outlineMapper.SetInputConnection(outline.GetOutputPort())
            outlineActor = vtk.vtkActor()
            outlineActor.SetMapper(outlineMapper)

            # The SetInteractor method is how 3D widgets are associated with the
            # render window interactor. Internally, SetInteractor sets up a bunch
            # of callbacks using the Command/Observer mechanism (AddObserver()).
            boxWidget = vtk.vtkBoxWidget()
            boxWidget.SetInteractor(self.vmtkRenderer.RenderWindowInteractor)
            boxWidget.SetPlaceFactor(1.0)

            # Place the interactor initially. The output of the reader is used to
            # place the box widget.
            boxWidget.SetInputData(self.Image)
            boxWidget.PlaceWidget()
            boxWidget.InsideOutOn()

            # Add the actors to the renderer
            self.vmtkRenderer.Renderer.AddActor(outlineActor)

        if (self.Display == 1):
            self.vmtkRenderer.Render()

        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
def actor_volume(volume,
                 what,
                 origin=(0, 0, 0),
                 c=(1, 1, 1),
                 tb_colors=None,
                 tb_opacity=.05):

    imagedata = volume_to_imagedata(volume, origin=origin)

    volumeMapper = vtk.vtkSmartVolumeMapper()
    # volumeMapper.SetBlendModeToComposite()
    volumeMapper.SetInputData(imagedata)

    volumeProperty = vtk.vtkVolumeProperty()
    #     volumeProperty.ShadeOff()
    # volumeProperty.SetInterpolationType(vtk.VTK_LINEAR_INTERPOLATION)

    if what == 'tb':

        compositeOpacity = vtk.vtkPiecewiseFunction()
        compositeOpacity.AddPoint(0.0, 0.)

        if tb_colors is not None:
            for v, c in sorted(tb_colors.items()):
                vl = v - .5
                vr = v + .5
                cp1 = vl - .25
                cp2 = vr - .25
                compositeOpacity.AddPoint(cp1, .5 * cp1 / 200., .5, 1.)
                compositeOpacity.AddPoint(v, 1., .5, 1.)
                compositeOpacity.AddPoint(cp2, .5 * cp2 / 200., .5, 1.)
            compositeOpacity.AddPoint(vr, .5 * vr / 200.)
        compositeOpacity.AddPoint(240., tb_opacity)
        compositeOpacity.AddPoint(255.0, tb_opacity)
        # compositeOpacity.AddPoint(240., .5)
        # compositeOpacity.AddPoint(255.0, .5)

        color = vtk.vtkColorTransferFunction()
        color.AddRGBPoint(0.0, 0, 0, 0)

        if tb_colors is not None:
            for v, c in sorted(tb_colors.items()):
                vl = v - .5
                vr = v + .5
                cp1 = vl - .25
                cp2 = vr - .25
                color.AddRGBPoint(cp1, .5 * cp1 / 200., .5 * cp1 / 200.,
                                  .5 * cp1 / 200., .5, 1.)
                color.AddRGBPoint(v, c[0], c[1], c[2], .5, 1.)
                color.AddRGBPoint(cp2, .5 * cp2 / 200., .5 * cp2 / 200.,
                                  .5 * cp2 / 200., .5, 1.)
            color.AddRGBPoint(vr, .5 * vr / 200., .5 * vr / 200.,
                              .5 * vr / 200.)
        color.AddRGBPoint(200.0, .5, .5, .5)
        color.AddRGBPoint(255.0, 1, 1, 1)

    # volumeGradientOpacity = vtk.vtkPiecewiseFunction()
    # volumeGradientOpacity.AddPoint(0,   0.0)
    # volumeGradientOpacity.AddPoint(1,  0.5)
    # volumeGradientOpacity.AddPoint(2, 1.0)

    elif what == 'score':

        compositeOpacity = vtk.vtkPiecewiseFunction()
        compositeOpacity.AddPoint(0.0, 0.0)
        # compositeOpacity.AddPoint(0.95, .0)
        # compositeOpacity.AddPoint(0.96, .2)
        compositeOpacity.AddPoint(0.9999, .0)
        compositeOpacity.AddPoint(1.0, .2)
        volumeProperty.SetScalarOpacity(compositeOpacity)

        color = vtk.vtkColorTransferFunction()
        color.AddRGBPoint(0.0, 1, 1, 1)
        color.AddRGBPoint(0.95, 1, 1, 1)
        color.AddRGBPoint(1.0, 1, 1, 1)

    elif what == 'probability':
        compositeOpacity = vtk.vtkPiecewiseFunction()
        compositeOpacity.AddPoint(0.0, 0.)
        compositeOpacity.AddPoint(.9, 0.05)
        compositeOpacity.AddPoint(1., 0.05)

        r, g, b = c

        color = vtk.vtkColorTransferFunction()
        color.AddRGBPoint(0.0, r, g, b)
        # color.AddRGBPoint(.95, .5,.5,.5)
        color.AddRGBPoint(1., r, g, b)

        # lookupTable = vtkLookupTable()
        # lookupTable.SetNumberOfTableValues(2);
        # lookupTable.SetRange(0.0,1.0);
        # lookupTable.SetTableValue( 0, 0.0, 0.0, 0.0, 0.0 ); #label 0 is transparent
        # lookupTable.SetTableValue( 1, 0.0, 1.0, 0.0, 1.0 ); #label 1 is opaque and green
        # lookupTable.Build()
        #
        # mapTransparency = vtkImageMapToColors()
        # mapTransparency.SetLookupTable(lookupTable)
        # mapTransparency.PassAlphaToOutputOn()
        # mapTransparency.SetInputData(maskImage)
        #
        # maskActor = vtkImageActor()
        # maskActor.GetMapper().SetInputConnection(mapTransparency.GetOutputPort())
        #
        #
        # volumeProperty.SetScalarOpacity(compositeOpacity)
        # volumeProperty.SetColor(color)
        #
        # volume = vtk.vtkVolume()
        # volume.SetMapper(volumeMapper)
        # volume.SetProperty(volumeProperty)
        #
        # return volume

    else:
        sys.stderr.write('Color/opacity profile not recognized.\n')

    volumeProperty.SetScalarOpacity(compositeOpacity)
    volumeProperty.SetColor(color)
    # volumeProperty.SetGradientOpacity(volumeGradientOpacity)

    volume = vtk.vtkVolume()
    volume.SetMapper(volumeMapper)
    volume.SetProperty(volumeProperty)

    return volume
Exemple #33
0
    def show_3D_array(self, in_array):
        """
        displays a numpy.ndarray as a 3D-Volume that can be interactively inspected
        :param in_array: the input 3D-array to be displayed
        """
        data_type = in_array.dtype
        dims = in_array.shape
        data_min, data_max = (np.min(in_array), np.max(in_array))
        renderer = vtk.vtkRenderer()
        window = vtk.vtkRenderWindow()
        window.AddRenderer(renderer)
        interactor = vtk.vtkRenderWindowInteractor()
        style = vtk.vtkInteractorStyleTrackballCamera()
        interactor.SetInteractorStyle(style)
        interactor.SetRenderWindow(window)
        renderer.SetBackground(0, 0, 0)
        window.SetSize(800, 600)

        importer = vtk.vtkImageImport()
        if data_type == 'uint8':
            importer.SetDataScalarTypeToUnsignedChar()
        elif data_type == 'uint16':
            importer.SetDataScalarTypeToShort()
        else:
            self.logger.log_error(
                f"unsupported data type ({data_type}) for image display, exiting!"
            )

        importer.SetNumberOfScalarComponents(1)
        importer.SetDataExtent(0, dims[2] - 1, 0, dims[1] - 1, 0, dims[0] - 1)
        importer.SetWholeExtent(0, dims[2] - 1, 0, dims[1] - 1, 0, dims[0] - 1)
        importer.CopyImportVoidPointer(in_array, in_array.nbytes)

        acf = vtk.vtkPiecewiseFunction()
        acf.AddPoint(data_min, 0.0)
        acf.AddPoint(data_max, 1.0)

        color_func = vtk.vtkColorTransferFunction()
        color_func.AddRGBPoint(data_min, 0.0, 0.0, 0.0)
        color_func.AddRGBPoint(data_max, 1.0, 1.0, 1.0)

        volume_property = vtk.vtkVolumeProperty()
        volume_property.SetColor(color_func)
        volume_property.SetScalarOpacity(acf)
        volume_property.ShadeOn()
        volume_property.SetInterpolationTypeToLinear()

        volume_mapper = vtk.vtkSmartVolumeMapper()
        volume_mapper.SetInputConnection(importer.GetOutputPort())

        volume = vtk.vtkVolume()
        volume.SetMapper(volume_mapper)
        volume.SetProperty(volume_property)

        renderer.AddVolume(volume)
        renderer.SetBackground(
            255, 255, 255)  # (25.0 / 255.0, 51.0 / 255.0, 102.0 / 255.0)

        axes = vtk.vtkAxesActor()

        # swap X and Z-Axes due to VTKs inverted indexing
        axes.SetXAxisLabelText('Z')
        axes.SetZAxisLabelText('X')

        widget = vtk.vtkOrientationMarkerWidget()
        widget.SetOutlineColor(0.9300, 0.5700, 0.1300)
        widget.SetOrientationMarker(axes)
        widget.SetInteractor(interactor)
        # widget.SetViewport(0.0, 0.0, 0.4, 0.4)
        widget.SetEnabled(1)
        widget.InteractiveOn()

        window.Render()

        interactor.Initialize()
        interactor.Start()
Exemple #34
0
    def renderFig(self, direction):
        print "cool, it is done"
        fr=gzip.open(self.fname[:-3]+"voxr","rb")
        dataRed=pickle.load(fr)
        self.data_matrix_red=numpy.uint8(dataRed) 
        self.dataImporterR = vtk.vtkImageImport()
        data_string = self.data_matrix_red.tostring()
        self.dataImporterR.CopyImportVoidPointer(data_string, len(data_string))
        self.dataImporterR.SetDataScalarTypeToUnsignedChar()
        self.dataImporterR.SetNumberOfScalarComponents(1)
        xdim,ydim,zdim=self.data_matrix_red.shape
        #self.dataImporter.SetDataExtent(0, zdim-1, 0, vtkPiecewiseFunctionb-1, 0, xdim-1)
        self.dataImporterR.SetDataExtent(0, zdim-1, 0, ydim-1, 0, xdim-1)
        #self.dataImporter.SetWholeExtent(0, zdim-1, 0, ydim-1, 0, xdim-1)
        self.dataImporterR.SetWholeExtent(0, zdim-1, 0, ydim-1, 0, xdim-1)
        
        fg=gzip.open(self.fname[:-3]+"voxg","rb")
        dataGreen=pickle.load(fg)
        self.data_matrix_green=numpy.uint8(dataGreen) 
        self.dataImporterG = vtk.vtkImageImport()
        data_string = self.data_matrix_green.tostring()
        self.dataImporterG.CopyImportVoidPointer(data_string, len(data_string))
        self.dataImporterG.SetDataScalarTypeToUnsignedChar()
        self.dataImporterG.SetNumberOfScalarComponents(1)
        xdim,ydim,zdim=self.data_matrix_green.shape
        #self.dataImporter.SetDataExtent(0, zdim-1, 0, vtkPiecewiseFunctionb-1, 0, xdim-1)
        self.dataImporterG.SetDataExtent(0, zdim-1, 0, ydim-1, 0, xdim-1)
        #self.dataImporter.SetWholeExtent(0, zdim-1, 0, ydim-1, 0, xdim-1)
        self.dataImporterG.SetWholeExtent(0, zdim-1, 0, ydim-1, 0, xdim-1)
        
        fb=gzip.open(self.fname[:-3]+"voxb","rb")
        dataBlue=pickle.load(fb)
        self.data_matrix_blue=numpy.uint8(dataBlue) 
        self.dataImporterB = vtk.vtkImageImport()
        data_string = self.data_matrix_blue.tostring()
        self.dataImporterB.CopyImportVoidPointer(data_string, len(data_string))
        self.dataImporterB.SetDataScalarTypeToUnsignedChar()
        self.dataImporterB.SetNumberOfScalarComponents(1)
        xdim,ydim,zdim=self.data_matrix_blue.shape
        #self.dataImporter.SetDataExtent(0, zdim-1, 0, vtkPiecewiseFunctionb-1, 0, xdim-1)
        self.dataImporterB.SetDataExtent(0, zdim-1, 0, ydim-1, 0, xdim-1)
        #self.dataImporter.SetWholeExtent(0, zdim-1, 0, ydim-1, 0, xdim-1)
        self.dataImporterB.SetWholeExtent(0, zdim-1, 0, ydim-1, 0, xdim-1)

        """Append the output to VTK"""
        self.append = vtk.vtkImageAppendComponents() 
        self.append.SetInputConnection(self.dataImporterR.GetOutputPort()) 
        self.append.AddInputConnection(self.dataImporterG.GetOutputPort()) 
        self.append.AddInputConnection(self.dataImporterB.GetOutputPort()) 
        self.append.Update() 
        
        """Set the mapper in VTK"""
        # This class describes how the volume is rendered (through ray tracing).
        #compositeFunction = vtk.vtkVolumeRayCastCompositeFunction()
        # We can finally create our volume. We also have to specify the data for it, as well as how the data will be rendered.
        #volumeMapper = vtk.vtkVolumeRayCastMapper()
        volumeMapper = vtk.vtkSmartVolumeMapper()
        #volumeMapper.SetVolumeRayCastFunction(compositeFunction)
        #volumeMapper.SetBlendModeToComposite()
        #volumeMapper = vtk.vtkFixedPointVolumeRayCastMapper()   
        volumeMapper.SetInputConnection(self.append.GetOutputPort())
        
        """Set the property of the volume"""            
        volumeProperty = vtk.vtkVolumeProperty() 
        volumeProperty.ShadeOff()
        volumeProperty.SetInterpolationTypeToLinear()
        #volumeProperty.SetIndependentComponents(3)
        volumeProperty.IndependentComponentsOn()
        
        """Set the color and opacity of each output"""
        opacityTF1 = vtk.vtkPiecewiseFunction() 
        opacityTF1.AddPoint(   0.0,  0.0 ) 
        opacityTF1.AddPoint(   1.0,  0.33)
        opacityTF1.AddPoint(   128.0, 0.33) 
        opacityTF1.AddPoint(   255.0,  0.33 ) 
        volumeProperty.SetScalarOpacity(0,opacityTF1) 
        
        colourTF1 = vtk.vtkColorTransferFunction() 
        colourTF1.AddRGBPoint(   0.0,  0.0, 0.0, 0.0 ) 
        colourTF1.AddRGBPoint(   1.0,  0.0, 0.0, 0.1 )
        colourTF1.AddRGBPoint(   128.0, 0.0, 0.0, 0.5 ) 
        colourTF1.AddRGBPoint(   255.0, 0.0, 0.0, 1.0 ) 
        volumeProperty.SetColor(0,colourTF1)
        
        opacityTF2 = vtk.vtkPiecewiseFunction() 
        opacityTF2.AddPoint(   0.0,  0.0 ) 
        opacityTF2.AddPoint(   1.0,  0.33 ) 
        opacityTF2.AddPoint(   128.0, 0.33)
        opacityTF2.AddPoint(   255.0,  0.33 ) 
        volumeProperty.SetScalarOpacity(1,opacityTF2) 
        
        colourTF2 = vtk.vtkColorTransferFunction() 
        colourTF2.AddRGBPoint(   0.0,  0.0, 0.0, 0.0 ) 
        colourTF2.AddRGBPoint(   1.0,  0.0, 0.1, 0.0 )
        colourTF2.AddRGBPoint(   128.0, 0.0, 0.5, 0.0 ) 
        colourTF2.AddRGBPoint(   255.0, 0.0, 1.0, 0.0 ) 
        volumeProperty.SetColor(1,colourTF2)
        
        opacityTF3 = vtk.vtkPiecewiseFunction() 
        opacityTF3.AddPoint(   0.0,  0.0 ) 
        opacityTF3.AddPoint(   1.0,  0.33 ) 
        opacityTF3.AddPoint(   128.0, 0.33)
        opacityTF3.AddPoint(   255.0,  0.33 ) 
        volumeProperty.SetScalarOpacity(2,opacityTF3) 
        
        colourTF3 = vtk.vtkColorTransferFunction() 
        colourTF3.AddRGBPoint(   0.0,  0.0, 0.0, 0.0 ) 
        colourTF3.AddRGBPoint(   1.0,  0.1, 0.0, 0.0 )
        colourTF3.AddRGBPoint(   128.0, 0.5, 0.0, 0.0 ) 
        colourTF3.AddRGBPoint(   255.0, 1.0, 0.0, 0.0 ) 
        volumeProperty.SetColor(2,colourTF3)

        #volumeProperty.SetIndependentComponents(4)    
        
        
        #volumeProperty = vtk.vtkVolumeProperty()
        #volprop.SetColor(colourTF)
        #volprop.SetScalarOpacity(alphaChannelFunc)
   
        self.volume.SetMapper(volumeMapper)
        self.volume.SetProperty(volumeProperty)
                    
        self.ren.RemoveActor(self.actor)
                    
        self.ren.AddVolume(self.volume)
        self.ren.SetBackground(1, 1, 1)
            
        self.addPicker()
        # A simple function to be called when the user decides to quit the application.
        def exitCheck(obj, event):
            if obj.GetEventPending() != 0:
                obj.SetAbortRender(1)
                                     
            # Tell the application to use the function as an exit check.
        renderWin = self.vtkWidget.GetRenderWindow()
        renderWin.AddObserver("AbortCheckEvent", exitCheck)
                    
        self.iren.Initialize()
        # Initially pick the cell at this location.
        self.picker.Pick(85, 126, 0, self.ren)
        self.iren.Start()
Exemple #35
0
    def Add_MomActors(self,ren,renWin,iren,ASDdata,window):
        """Main wrapper to add the needed actors for visualization of the moments.
        Class that contains the data structures for creation of the glyphs or the 
        visualization of the magnetic moments. It also has the capacity to create 
        tessellations for the visualization of volume vendering.

        Args:
            ren: current renderer.
            renWin: current rendering window.
            iren: current interactor for the renderer.
            ASDdata: class where the data read from the ASD simulations is stored.
            window: QMainWindow object where the visualization is performed.

        Author
        ----------
        Jonathan Chico
        """

        import vtk
        import numpy as np

        ASDMomActors.timer_count=0
        ASDMomActors.camera_pos=np.zeros(3,dtype=np.float32)
        ASDMomActors.camera_focal=np.zeros(3,dtype=np.float32)
        ASDMomActors.camera_yaw=0.0
        ASDMomActors.camera_roll=0.0
        ASDMomActors.camera_pitch=0.0
        ASDMomActors.camera_azimuth=0.0
        ASDMomActors.camera_elevation=0.0
        ASDMomActors.kmc_disp=ASDdata.kmc_flag
        ASDMomActors.cluster_disp=ASDdata.cluster_flag
        ASDMomActors.glob_color=ASDdata.colors
        #-----------------------------------------------------------------------
        # Look up tables for colors
        #-----------------------------------------------------------------------
        # This is a diverging RWB color mapping based on the work of Kenneth
        # Moreland and with the vtk examples provided by Andrew Maclean
        if ASDdata.flag2D:
            ASDMomActors.lut = vtk.vtkLookupTable()
            num_colors = 256
            ASDMomActors.lut.SetNumberOfTableValues(num_colors)
            ASDMomActors.transfer_func = vtk.vtkColorTransferFunction()
            ASDMomActors.transfer_func.SetColorSpaceToDiverging()
            ASDMomActors.transfer_func.AddRGBPoint(0, 0.230, 0.299, 0.754)
            ASDMomActors.transfer_func.AddRGBPoint(1, 0.706, 0.016, 0.150)
            for ii,ss in enumerate([float(xx)/float(num_colors) for xx in range(num_colors)]):
                cc = ASDMomActors.transfer_func.GetColor(ss)
                ASDMomActors.lut.SetTableValue(ii, cc[0], cc[1], cc[2], 1.0)
            ASDMomActors.lut.Build()
        else:
            ASDMomActors.lut = vtk.vtkLookupTable()
            num_colors = 256
            ASDMomActors.lut.SetNumberOfTableValues(num_colors)
            ASDMomActors.transfer_func = vtk.vtkColorTransferFunction()
            ASDMomActors.transfer_func.SetColorSpaceToDiverging()
            ASDMomActors.transfer_func.AddRGBPoint(-0, 0.230, 0.299, 0.754)
            ASDMomActors.transfer_func.AddRGBPoint( 1, 0.706, 0.016, 0.150)
            for ii,ss in enumerate([float(xx)/float(num_colors) for xx in range(num_colors)]):
                cc = ASDMomActors.transfer_func.GetColor(ss)
                ASDMomActors.lut.SetTableValue(ii, cc[0], cc[1], cc[2], 1.0)
            ASDMomActors.lut.Build()
        #-----------------------------------------------------------------------
        # Data structures for the generation of the smooth grid
        #-----------------------------------------------------------------------
        # Passing the data from the full system to the PolyData
        ASDMomActors.src=vtk.vtkPolyData()
        ASDMomActors.src.SetPoints(ASDdata.coord)
        ASDMomActors.src.GetPointData().SetScalars(ASDdata.colors[2])
        ASDMomActors.src.GetPointData().SetVectors(ASDdata.moments)
        scalar_range = ASDMomActors.src.GetScalarRange()
        #-----------------------------------------------------------------------
        # Finding useful geometrical information of the sample
        #-----------------------------------------------------------------------
        # Finding the middle of the sample
        # Also making sure that if the sample is 2D one has no problem with bounds
        # this is mostly useful if splatters are used
        (ASDMomActors.xmin,ASDMomActors.xmax,ASDMomActors.ymin,ASDMomActors.ymax,\
        ASDMomActors.zmin,ASDMomActors.zmax)= ASDMomActors.src.GetBounds()
        if ASDMomActors.xmin==ASDMomActors.xmax:
            ASDMomActors.xmin=0.0
            ASDMomActors.xmax=1.0
        if ASDMomActors.ymin==ASDMomActors.ymax:
            ASDMomActors.ymin=0.0
            ASDMomActors.ymax=1.0
        if ASDMomActors.zmin==ASDMomActors.zmax:
            ASDMomActors.zmin=0.0
            ASDMomActors.zmax=1.0
        ASDMomActors.xmid = (ASDMomActors.xmin+ASDMomActors.xmax)*0.5
        ASDMomActors.ymid = (ASDMomActors.ymin+ASDMomActors.ymax)*0.5
        ASDMomActors.zmid = (ASDMomActors.zmin+ASDMomActors.zmax)*0.5
        ASDMomActors.height=max(ASDMomActors.xmax,ASDMomActors.ymax,ASDMomActors.zmax)*1.75
        self.dist_x=np.absolute(ASDMomActors.xmax-ASDMomActors.xmin)
        self.dist_y=np.absolute(ASDMomActors.ymax-ASDMomActors.ymin)
        self.dist_z=np.absolute(ASDMomActors.zmax-ASDMomActors.zmin)
        ASDMomActors.camera_pos[0]=ASDMomActors.xmid
        ASDMomActors.camera_pos[1]=ASDMomActors.ymid
        ASDMomActors.camera_pos[2]=ASDMomActors.height
        ASDMomActors.camera_focal[0]=ASDMomActors.xmid
        ASDMomActors.camera_focal[1]=ASDMomActors.ymid
        ASDMomActors.camera_focal[2]=ASDMomActors.zmid
        # The delaunay tessellation seems to be the best way to transform the point cloud
        # to a surface for volume rendering, the problem is that it is too slow for large
        # data sets, meaning that the best option is first to prune out the data to ensure
        # that one has a manageable number of data points over which to do the construction
        # surface reconstruction and splatter techniques also can be used to generate something
        # akin to the kind of surfaces we want. The issue is that they transform the data to a
        # regular mesh by default. And thus it is a problem for most kind of systems
        if ASDdata.flag2D:
            # Passing the data to generate a triangulation of the data
            ASDMomActors.MagDensMethod = vtk.vtkDelaunay2D()
            ASDMomActors.MagDensMethod.SetInputData(ASDMomActors.src)
            ASDMomActors.MagDensMethod.BoundingTriangulationOff()
            ASDMomActors.MagDensMethod.SetTolerance(0.005)
            # Time the execution of the delaunay tessellation
            SM_timer = vtk.vtkExecutionTimer()
            SM_timer.SetFilter(ASDMomActors.MagDensMethod)
            ASDMomActors.MagDensMethod.Update()
            SM = SM_timer.GetElapsedWallClockTime()
            print ("2D Delaunay:", SM)
            # Creating the mapper for the smooth surfaces
            ASDMomActors.MagDensMap = vtk.vtkDataSetMapper()
            ASDMomActors.MagDensMap.SetScalarRange(scalar_range)
            ASDMomActors.MagDensMap.SetInputConnection(ASDMomActors.MagDensMethod.GetOutputPort())
            ASDMomActors.MagDensMap.SetLookupTable(ASDMomActors.lut)
            ASDMomActors.MagDensMap.SetColorModeToMapScalars()
            ASDMomActors.MagDensMap.Update()
            # Creating the actor for the smooth surfaces
            ASDMomActors.MagDensActor = vtk.vtkLODActor()
            ASDMomActors.MagDensActor.SetMapper(ASDMomActors.MagDensMap)
            ASDMomActors.MagDensActor.GetProperty().SetOpacity(0.75)
            ASDMomActors.MagDensActor.GetProperty().EdgeVisibilityOff()
            if window.DensBox.isChecked():
                ASDMomActors.MagDensActor.VisibilityOn()
            else:
                ASDMomActors.MagDensActor.VisibilityOff()
        else:
            #-------------------------------------------------------------------
            # Setting the parameters for the visualization of 3D structures with
            # splatters
            #-------------------------------------------------------------------
            ASDMomActors.MagDensMethod = vtk.vtkGaussianSplatter()
            ASDMomActors.MagDensMethod.SetInputData(ASDMomActors.src)
            #-------------------------------------------------------------------
            # Options for the Gaussian splatter. These determine the quality of the
            # rendering, increasing the radius smoothens out the volume but performance
            # decreases rapidly
            #-------------------------------------------------------------------
            dist=(np.asarray(ASDMomActors.src.GetPoint(0))-np.asarray(ASDMomActors.src.GetPoint(1)))
            norm=np.sqrt(dist.dot(dist))
            if norm<1:
                rad_fac=0.040
            else:
                rad_fac=0.40
            ASDMomActors.MagDensMethod.SetRadius(rad_fac)
            ASDMomActors.MagDensMethod.ScalarWarpingOn()
            #-------------------------------------------------------------------
            # The exponent factor determines how fast the gaussian splatter decay
            # they again can be used to improve quality at the sake of rendering time
            #-------------------------------------------------------------------
            ASDMomActors.MagDensMethod.SetExponentFactor(-10)
            ASDMomActors.MagDensMethod.NormalWarpingOn()
            ASDMomActors.MagDensMethod.SetEccentricity(10)
            #-------------------------------------------------------------------
            # The Null value can be used to try to eliminate contributions not belonging
            # to the actual sample
            #-------------------------------------------------------------------
            ASDMomActors.MagDensMethod.SetNullValue(-10)
            #-------------------------------------------------------------------
            # Set the actual size of the rendering model
            #-------------------------------------------------------------------
            ASDMomActors.MagDensMethod.SetModelBounds(ASDMomActors.xmin,ASDMomActors.xmax,\
            ASDMomActors.ymin,ASDMomActors.ymax,ASDMomActors.zmin,ASDMomActors.zmax)
            # This should get rid of the problems when trying to map very thin structures in 2D
            if self.dist_x==min(self.dist_x,self.dist_y,self.dist_z) and self.dist_x<3:
                ASDMomActors.MagDensMethod.SetSampleDimensions(3,int(ASDMomActors.ymax),int(ASDMomActors.zmax))
            elif self.dist_y==min(self.dist_x,self.dist_y,self.dist_z) and self.dist_y<3:
                ASDMomActors.MagDensMethod.SetSampleDimensions(int(ASDMomActors.xmax),3,int(ASDMomActors.zmax))
            elif self.dist_z==min(self.dist_x,self.dist_y,self.dist_z) and self.dist_z<3:
                ASDMomActors.MagDensMethod.SetSampleDimensions(int(ASDMomActors.xmax),int(ASDMomActors.ymax),3)
            # Timming for the execution of the volume creation
            SP_timer = vtk.vtkExecutionTimer()
            SP_timer.SetFilter(ASDMomActors.MagDensMethod)
            ASDMomActors.MagDensMethod.Update()
            SP = SP_timer.GetElapsedWallClockTime()
            print ("3D vtkGaussianSplatter Method:", SP)
            # Scalar opacities
            funcOpacityScalar = vtk.vtkPiecewiseFunction()
            funcOpacityScalar.AddPoint(-1.00,0.00)
            funcOpacityScalar.AddPoint( 0.00,0.05)
            funcOpacityScalar.AddPoint( 0.50,0.50)
            funcOpacityScalar.AddPoint( 0.75,1.00)
            # Gradient opacities
            volumeGradientOpacity = vtk.vtkPiecewiseFunction()
            volumeGradientOpacity.AddPoint(0.000,0.0)
            volumeGradientOpacity.AddPoint(0.001,1.0)
            volumeGradientOpacity.AddPoint(1.000,1.0)
            # Volume properties
            ASDMomActors.volumeProperty = vtk.vtkVolumeProperty()
            ASDMomActors.volumeProperty.SetColor(ASDMomActors.transfer_func)
            ASDMomActors.volumeProperty.SetInterpolationTypeToLinear()
            ASDMomActors.volumeProperty.SetAmbient(0.6)
            ASDMomActors.volumeProperty.SetDiffuse(0.6)
            ASDMomActors.volumeProperty.SetSpecular(0.1)
            ASDMomActors.volumeProperty.SetGradientOpacity(volumeGradientOpacity)
            ASDMomActors.volumeProperty.SetScalarOpacity(funcOpacityScalar)
            # Volume Mapper
            ASDMomActors.MagDensMap = vtk.vtkSmartVolumeMapper()
            ASDMomActors.MagDensMap.SetInputConnection(ASDMomActors.MagDensMethod.GetOutputPort())
            # Volume Actor
            ASDMomActors.MagDensActor = vtk.vtkVolume()
            ASDMomActors.MagDensActor.SetMapper(ASDMomActors.MagDensMap)
            ASDMomActors.MagDensActor.SetProperty(self.volumeProperty)
            if window.DensBox.isChecked():
                ASDMomActors.MagDensActor.VisibilityOn()
            else:
                ASDMomActors.MagDensActor.VisibilityOff()
        #-----------------------------------------------------------------------
        # Data structures for the spins
        #-----------------------------------------------------------------------
        # Passing the data from the full system to the PolyData
        ASDMomActors.src_spins=vtk.vtkPolyData()
        ASDMomActors.src_spins.SetPoints(ASDdata.coord)
        ASDMomActors.src_spins.GetPointData().SetScalars(ASDdata.colors[2])
        ASDMomActors.src_spins.GetPointData().SetVectors(ASDdata.moments)
        scalar_range_spins = ASDMomActors.src_spins.GetScalarRange()
        #-----------------------------------------------------------------------
        # Data structures for the contours
        #-----------------------------------------------------------------------
        # Define the contour filters
        contours = vtk.vtkContourFilter()
        contours.SetInputConnection(ASDMomActors.MagDensMethod.GetOutputPort())
        # This generates the contours, it will do 5 between the -1 and 0.5 range
        cont_num=5
        range_cont=(-1,0.5)
        contours.GenerateValues(cont_num,range_cont)
        # Map the contours to graphical primitives
        contMapper = vtk.vtkPolyDataMapper()
        contMapper.SetInputConnection(contours.GetOutputPort())
        contMapper.SetScalarVisibility(False) # colored contours
        contMapper.SetScalarRange(scalar_range)
        # Create an actor for the contours
        ASDMomActors.contActor = vtk.vtkLODActor()
        ASDMomActors.contActor.SetMapper(contMapper)
        ASDMomActors.contActor.GetProperty().SetColor(0, 0, 0)
        ASDMomActors.contActor.GetProperty().SetLineWidth(1.0)
        ASDMomActors.contActor.VisibilityOff()
        #-----------------------------------------------------------------------
        # Setting information of the directions
        #-----------------------------------------------------------------------
        # Create vectors
        arrow = vtk.vtkArrowSource()
        arrow.SetTipRadius(0.20)
        arrow.SetShaftRadius(0.10)
        arrow.SetTipResolution(20)
        arrow.SetShaftResolution(20)
        # Create the mapper for the spins
        arrowMapper = vtk.vtkGlyph3DMapper()
        arrowMapper.SetSourceConnection(arrow.GetOutputPort())
        arrowMapper.SetInputData(ASDMomActors.src)
        arrowMapper.SetScaleFactor(0.50)
        arrowMapper.SetScalarVisibility(False)
        arrowMapper.SetScaleModeToNoDataScaling()
        arrowMapper.Update()
        # Define the vector actor for the spins
        ASDMomActors.vector = vtk.vtkLODActor()
        ASDMomActors.vector.SetMapper(arrowMapper)
        ASDMomActors.vector.GetProperty().SetSpecular(0.3)
        ASDMomActors.vector.GetProperty().SetSpecularPower(60)
        ASDMomActors.vector.GetProperty().SetAmbient(0.2)
        ASDMomActors.vector.GetProperty().SetDiffuse(0.8)
        ASDMomActors.vector.GetProperty().SetColor(0, 0, 0)
        ASDMomActors.vector.VisibilityOff()
        #-----------------------------------------------------------------------
        # Setting information of the spins
        #-----------------------------------------------------------------------
        # Create vectors
        ASDMomActors.spinarrow = vtk.vtkArrowSource()
        ASDMomActors.spinarrow.SetTipRadius(0.20)
        ASDMomActors.spinarrow.SetShaftRadius(0.10)
        ASDMomActors.spinarrow.SetTipResolution(20)
        ASDMomActors.spinarrow.SetShaftResolution(20)
        # Create the mapper for the spins
        ASDMomActors.SpinMapper = vtk.vtkGlyph3DMapper()
        ASDMomActors.SpinMapper.SetSourceConnection(ASDMomActors.spinarrow.GetOutputPort())
        ASDMomActors.SpinMapper.SetInputData(ASDMomActors.src_spins)
        ASDMomActors.SpinMapper.SetScalarRange(scalar_range_spins)
        ASDMomActors.SpinMapper.SetScaleFactor(0.50)
        ASDMomActors.SpinMapper.SetScaleModeToNoDataScaling()
        ASDMomActors.SpinMapper.SetLookupTable(self.lut)
        ASDMomActors.SpinMapper.SetColorModeToMapScalars()
        ASDMomActors.SpinMapper.Update()
        # Define the vector actor for the spins
        ASDMomActors.Spins = vtk.vtkLODActor()
        ASDMomActors.Spins.SetMapper(ASDMomActors.SpinMapper)
        ASDMomActors.Spins.GetProperty().SetSpecular(0.3)
        ASDMomActors.Spins.GetProperty().SetSpecularPower(60)
        ASDMomActors.Spins.GetProperty().SetAmbient(0.2)
        ASDMomActors.Spins.GetProperty().SetDiffuse(0.8)
        if window.SpinsBox.isChecked():
            ASDMomActors.Spins.VisibilityOn()
        else:
            ASDMomActors.Spins.VisibilityOff()
        if (ASDdata.kmc_flag):
            #-------------------------------------------------------------------
            # Setting data structures for the KMC particle visualization
            #-------------------------------------------------------------------
            ASDMomActors.KMC_src=vtk.vtkPolyData()
            ASDMomActors.KMC_src.SetPoints(ASDdata.coord_KMC)
            # Atom sphere
            KMC_part = vtk.vtkSphereSource()
            KMC_part.SetRadius(1.75)
            KMC_part.SetThetaResolution(40)
            KMC_part.SetPhiResolution(40)
            # Atom glyph
            KMC_part_mapper = vtk.vtkGlyph3DMapper()
            KMC_part_mapper.SetInputData(ASDMomActors.KMC_src)
            KMC_part_mapper.SetSourceConnection(KMC_part.GetOutputPort())
            KMC_part_mapper.SetScaleFactor(0.5)
            KMC_part_mapper.ClampingOn()
            KMC_part_mapper.SetScaleModeToNoDataScaling()
            KMC_part_mapper.SetColorModeToMapScalars()
            KMC_part_mapper.Update()
            # Atoms actors
            ASDMomActors.KMC_part_actor = vtk.vtkLODActor()
            ASDMomActors.KMC_part_actor.SetMapper(KMC_part_mapper)
            ASDMomActors.KMC_part_actor.GetProperty().SetOpacity(0.9)
            ASDMomActors.KMC_part_actor.GetProperty().SetColor(0.0, 0.0, 1.0)
            ASDMomActors.KMC_part_actor.GetProperty().EdgeVisibilityOn()
            ASDMomActors.KMC_part_actor.GetProperty().SetEdgeColor(0,0,0)
        #-----------------------------------------------------------------------
        # Setting information of the renderer
        #-----------------------------------------------------------------------
        # Define the renderer
        # Add the actors to the scene
        if ASDdata.flag2D:
            ren.AddActor(ASDMomActors.MagDensActor)
        else:
            ren.AddViewProp(ASDMomActors.MagDensActor)
        ren.AddActor(ASDMomActors.Spins)
        ren.AddActor(ASDMomActors.vector)
        ren.AddActor(ASDMomActors.contActor)
        #If the KMC particles are present add them to the renderer
        if ASDdata.kmc_flag:
            ren.AddActor(ASDMomActors.KMC_part_actor)
        # Defining the camera directions
        ren.GetActiveCamera().Azimuth(ASDMomActors.camera_azimuth)
        ren.GetActiveCamera().Elevation(ASDMomActors.camera_elevation)
        ren.GetActiveCamera().Yaw(ASDMomActors.camera_yaw)
        ren.GetActiveCamera().Roll(ASDMomActors.camera_roll)
        ren.GetActiveCamera().Pitch(ASDMomActors.camera_pitch)
        ren.GetActiveCamera().SetFocalPoint(ASDMomActors.camera_focal)
        ren.GetActiveCamera().SetPosition(ASDMomActors.camera_pos)
        ren.GetActiveCamera().SetViewUp(0,1,0)
        #-----------------------------------------------------------------------
        # Start the renderer
        #-----------------------------------------------------------------------
        iren.Start()
        renWin.Render()
        return;
    def showLayer(self):
        if self.volume != Null:
            self.ren.RemoveVolume(self.volume)
        
        sliceNumber = self.sliceNumber.text()
        sliceIntArray = sliceNumber.toUInt()
        sliceInt = sliceIntArray[0]
        
        print "cool, it is done"
        fr=gzip.open(self.fname[:-3]+"voxr","rb")
        dataRed=pickle.load(fr)
        self.data_matrix_red=numpy.uint8(dataRed)
        self.data_matrix_red=self.data_matrix_red[sliceInt-1:sliceInt+1,:,:]
        with file('layerView.txt', 'w') as outfile:
            for data_slice in self.data_matrix_red:

        # The formatting string indicates that I'm writing out
        # the values in left-justified columns 7 characters in width
        # with 2 decimal places.  
                numpy.savetxt(outfile, data_slice,fmt='%-7.1f')

        # Writing out a break to indicate different slices...
                outfile.write('# New slice\n')
        
        
        self.dataImporterR = vtk.vtkImageImport()
        data_string = self.data_matrix_red.tostring()
        self.dataImporterR.CopyImportVoidPointer(data_string, len(data_string))
        self.dataImporterR.SetDataScalarTypeToUnsignedChar()
        self.dataImporterR.SetNumberOfScalarComponents(1)
        xdim,ydim,zdim=self.data_matrix_red.shape
        #self.dataImporter.SetDataExtent(0, zdim-1, 0, vtkPiecewiseFunctionb-1, 0, xdim-1)
        self.dataImporterR.SetDataExtent(0, zdim-1, 0, ydim-1, 0, xdim-1)
        #self.dataImporter.SetWholeExtent(0, zdim-1, 0, ydim-1, 0, xdim-1)
        self.dataImporterR.SetWholeExtent(0, zdim-1, 0, ydim-1, 0, xdim-1)
        
        fg=gzip.open(self.fname[:-3]+"voxg","rb")
        dataGreen=pickle.load(fg)
        self.data_matrix_green=numpy.uint8(dataGreen)
        self.data_matrix_green = self.data_matrix_green[sliceInt-1:sliceInt+1,:,:] 
        self.dataImporterG = vtk.vtkImageImport()
        data_string = self.data_matrix_green.tostring()
        self.dataImporterG.CopyImportVoidPointer(data_string, len(data_string))
        self.dataImporterG.SetDataScalarTypeToUnsignedChar()
        self.dataImporterG.SetNumberOfScalarComponents(1)
        xdim,ydim,zdim=self.data_matrix_green.shape
        #self.dataImporter.SetDataExtent(0, zdim-1, 0, vtkPiecewiseFunctionb-1, 0, xdim-1)
        self.dataImporterG.SetDataExtent(0, zdim-1, 0, ydim-1, 0, xdim-1)
        #self.dataImporter.SetWholeExtent(0, zdim-1, 0, ydim-1, 0, xdim-1)
        self.dataImporterG.SetWholeExtent(0, zdim-1, 0, ydim-1, 0, xdim-1)
        
        
        fb=gzip.open(self.fname[:-3]+"voxb","rb")
        dataBlue=pickle.load(fb)
        self.data_matrix_blue=numpy.uint8(dataBlue)
        self.data_matrix_blue = self.data_matrix_blue[sliceInt-1:sliceInt+1,:,:] 
        self.dataImporterB = vtk.vtkImageImport()
        data_string = self.data_matrix_blue.tostring()
        self.dataImporterB.CopyImportVoidPointer(data_string, len(data_string))
        self.dataImporterB.SetDataScalarTypeToUnsignedChar()
        self.dataImporterB.SetNumberOfScalarComponents(1)
        xdim,ydim,zdim=self.data_matrix_blue.shape
        #self.dataImporter.SetDataExtent(0, zdim-1, 0, vtkPiecewiseFunctionb-1, 0, xdim-1)
        self.dataImporterB.SetDataExtent(0, zdim-1, 0, ydim-1, 0, xdim-1)
        #self.dataImporter.SetWholeExtent(0, zdim-1, 0, ydim-1, 0, xdim-1)
        self.dataImporterB.SetWholeExtent(0, zdim-1, 0, ydim-1, 0, xdim-1)

        
        self.append = vtk.vtkImageAppendComponents() 
        self.append.SetInputConnection(self.dataImporterR.GetOutputPort()) 
        self.append.AddInputConnection(self.dataImporterG.GetOutputPort()) 
        self.append.AddInputConnection(self.dataImporterB.GetOutputPort()) 
        self.append.Update() 
        
        volumeMapper = vtk.vtkSmartVolumeMapper()
        volumeMapper.SetInputConnection(self.append.GetOutputPort())
        
        volumeProperty = vtk.vtkVolumeProperty() 
        volumeProperty.ShadeOff()
        volumeProperty.SetInterpolationTypeToLinear()
        volumeProperty.IndependentComponentsOn()
        
        opacityTF1 = vtk.vtkPiecewiseFunction() 
        opacityTF1.AddPoint(   0.0,  0.0 ) 
        opacityTF1.AddPoint(   1.0,  0.33)
        opacityTF1.AddPoint(   128.0, 0.33) 
        opacityTF1.AddPoint(   255.0,  0.33 ) 
        volumeProperty.SetScalarOpacity(0,opacityTF1) 
        
        colourTF1 = vtk.vtkColorTransferFunction() 
        colourTF1.AddRGBPoint(   0.0,  0.0, 0.0, 0.0 ) 
        colourTF1.AddRGBPoint(   1.0,  0.0, 0.0, 0.1 )
        colourTF1.AddRGBPoint(   128.0, 0.0, 0.0, 0.5 ) 
        colourTF1.AddRGBPoint(   255.0, 0.0, 0.0, 1.0 ) 
        volumeProperty.SetColor(0,colourTF1)
        
        opacityTF2 = vtk.vtkPiecewiseFunction() 
        opacityTF2.AddPoint(   0.0,  0.0 ) 
        opacityTF2.AddPoint(   1.0,  0.33 ) 
        opacityTF2.AddPoint(   128.0, 0.33)
        opacityTF2.AddPoint(   255.0,  0.33 ) 
        volumeProperty.SetScalarOpacity(1,opacityTF2) 
        
        colourTF2 = vtk.vtkColorTransferFunction() 
        colourTF2.AddRGBPoint(   0.0,  0.0, 0.0, 0.0 ) 
        colourTF2.AddRGBPoint(   1.0,  0.0, 0.1, 0.0 )
        colourTF2.AddRGBPoint(   128.0, 0.0, 0.5, 0.0 ) 
        colourTF2.AddRGBPoint(   255.0, 0.0, 1.0, 0.0 ) 
        volumeProperty.SetColor(1,colourTF2)
        
        opacityTF3 = vtk.vtkPiecewiseFunction() 
        opacityTF3.AddPoint(   0.0,  0.0 ) 
        opacityTF3.AddPoint(   1.0,  0.33 ) 
        opacityTF3.AddPoint(   128.0, 0.33)
        opacityTF3.AddPoint(   255.0,  0.33 ) 
        volumeProperty.SetScalarOpacity(2,opacityTF3) 
        
        colourTF3 = vtk.vtkColorTransferFunction() 
        colourTF3.AddRGBPoint(   0.0,  0.0, 0.0, 0.0 ) 
        colourTF3.AddRGBPoint(   1.0,  0.1, 0.0, 0.0 )
        colourTF3.AddRGBPoint(   128.0, 0.5, 0.0, 0.0 ) 
        colourTF3.AddRGBPoint(   255.0, 1.0, 0.0, 0.0 ) 
        volumeProperty.SetColor(2,colourTF3)
   
        self.volume.SetMapper(volumeMapper)
        self.volume.SetProperty(volumeProperty)
                    
        #self.ren.RemoveActor(self.actor)
                    
        self.ren.AddVolume(self.volume)
        self.ren.SetBackground(0, 0, 0)
        # A simple function to be called when the user decides to quit the application.
        def exitCheck(obj, event):
            if obj.GetEventPending() != 0:
                obj.SetAbortRender(1)
                                     
            # Tell the application to use the function as an exit check.
        light = vtk.vtkLight()
        #light.SetColor(1, 1, 1)
        light.SwitchOff()
        self.ren.AddLight(light)
        
        renderWin = self.vtkWidget.GetRenderWindow()
        renderWin.AddObserver("AbortCheckEvent", exitCheck)
                    
        self.iren.Initialize()
        self.iren.Start()
Exemple #37
0
    def assignVolumeProperties(self, recomp=False):
        ''' Configures Transfer Functions for Volume Render. '''
        
        self.chart = vtk.vtkChartXY()
        
        # remove previous volume / scalarbar if there was one
        if self.actorVolume != None:
            self.renderer.RemoveActor(self.actorVolume)
            self.renderer.RemoveActor(self.scalarBar)
            
        if recomp:
            self.colorfunctions.clear()
            
        if self.curr_statistic not in self.colorfunctions.keys():
            self.colorfunctions[self.curr_statistic] = vtk.vtkColorTransferFunction()
            self.opacityfunctions[self.curr_statistic] = vtk.vtkPiecewiseFunction()
            cfn = self.colorfunctions[self.curr_statistic]
            ofn = self.opacityfunctions[self.curr_statistic]
            self.setColorOpacityDataPoints(cfn, ofn)
            self.opacityfunctions[self.curr_statistic].ClampingOn()
                    
        cfn = self.colorfunctions[self.curr_statistic]
        ofn = self.opacityfunctions[self.curr_statistic]
        
        self.__buildTransFuncChart(cfn, ofn)
        self.__buildScalarBar(self.curr_statistic)
        
        self.mapperVolume2 = vtk.vtkSmartVolumeMapper()
        img = self.images[self.curr_statistic]
        self.mapperVolume2.SetInputData( img )
        self.mapperVolume2.CroppingOff()
        self.addClippingPlanes(self.mapperVolume2, recomp)
        self.mapperVolume2.SetBlendModeToComposite()
        '''
        virtual void     SetBlendMode (int)
        void     SetBlendModeToComposite ()
        void     SetBlendModeToMaximumIntensity ()
        void     SetBlendModeToMinimumIntensity ()
        void     SetBlendModeToAdditive ()
        virtual int     GetBlendMode ()
        '''

        self.propVolume = vtk.vtkVolumeProperty()
        self.propVolume.ShadeOff()
        self.propVolume.SetColor(cfn)
        self.propVolume.SetScalarOpacity(ofn)
        #self.propVolume.SetInterpolationTypeToLinear()
        
        self.actorVolume = vtk.vtkVolume()
        self.actorVolume.SetMapper(self.mapperVolume2)
        self.actorVolume.SetProperty(self.propVolume)
        
        self.renderer.AddActor(self.actorVolume)
        self.renderer.AddActor(self.scalarBar)
        
        # set TF chart labels
        stat = self.curr_statistic
        if stat == 'Mean' or stat =='Var' or stat =='Min' or \
            stat =='Max' or stat =='NumSamples':
            self.setTFAxisLabels(self.curr_statistic, \
                                 self.curr_statistic, \
                                 self.curr_statistic)
        elif self.curr_statistic == 'Mean-Var':
            self.setTFAxisLabels(self.curr_statistic, \
                                 xlabel = 'Mean', \
                                 ylabel = '1.0 - Normalized Mean-Var')
        elif self.curr_statistic == 'Min-Var':
            self.setTFAxisLabels(self.curr_statistic, \
                                 xlabel = 'Min', \
                                 ylabel = '1.0 - Normalized Min-Var')
        elif self.curr_statistic == 'Max-Var':
            self.setTFAxisLabels(self.curr_statistic, \
                                 xlabel = 'Max', \
                                 ylabel = '1.0 - Normalized Max-Var')
Exemple #38
0
    def buildPipeline(self):
        """ execute() -> None
        Dispatch the vtkRenderer to the actual rendering widget
        """  
        extent = self.input().GetExtent() 
        rangeBounds = self.getRangeBounds() 
        self.sliceCenter = [ (extent[2*i+1]-extent[2*i])/2 for i in range(3) ]       
        spacing = self.input().GetSpacing()
        sx, sy, sz = spacing       
        origin = self.input().GetOrigin()
        ox, oy, oz = origin
        self._range = [ rangeBounds[0], rangeBounds[1], rangeBounds[0], 0 ]
        dataType = self.input().GetScalarTypeAsString()
        self.setMaxScalarValue( self.input().GetScalarType() )
        self.pos = [ spacing[i]*extent[2*i] for i in range(3) ]
#        if ( (origin[0] + self.pos[0]) < 0.0): self.pos[0] = self.pos[0] + 360.0
        bounds = [0]*6
        for i in range(6):
            io2 = int(i/2)
            bounds[i] = origin[io2] + spacing[io2]*extent[i] 
            
        print " --VolumeRenderer--   Data Type = %s, range = (%f,%f), max_scalar = %s" % ( dataType, rangeBounds[0], rangeBounds[1], self._max_scalar_value )
        print "Extent: %s " % str( self.input().GetWholeExtent() )
        print "Spacing: %s " % str( spacing )
        print "Origin: %s " % str( origin )
        print "Dimensions: %s " % str( self.input().GetDimensions() )
        print "Bounds: %s " % str( bounds )
        print "Input Bounds: %s " % str( self.input().GetBounds() )
        print "VolumePosition: %s " % str( self.pos )
        
#        self.inputInfo = self.inputPort.GetInformation() 
#        translation = inputInfo.Get( ResampleTranslationKey  )                                     
        
        # Create transfer mapping scalar value to color
        self.colorTransferFunction = vtk.vtkColorTransferFunction()
                
        # Create transfer mapping scalar value to opacity
        self.opacityTransferFunction = vtk.vtkPiecewiseFunction()        
                
        # The property describes how the data will look
        self.volumeProperty = vtk.vtkVolumeProperty()
        self.volumeProperty.SetInterpolationType( vtk.VTK_LINEAR_INTERPOLATION )
        self.volumeProperty.SetColor(self.colorTransferFunction)
        self.volumeProperty.SetScalarOpacity(self.opacityTransferFunction)
#        self.volumeProperty.SetGradientOpacity(self.opacityTransferFunction)
     
        # The mapper knows how to render the data

#        self.volumeMapperTexture2D = vtk.vtkVolumeTextureMapper2D()
        self.volumeMapper = vtk.vtkSmartVolumeMapper() 
        self.volumeMapper.SetBlendModeToComposite() 
        self.volumeMapper.CroppingOff()
       
        self.clipper = vtk.vtkBoxWidget()
        self.clipper.RotationEnabledOff()
        self.clipper.SetPlaceFactor( 1.0 )    
        self.clipper.AddObserver( 'StartInteractionEvent', self.startClip )
        self.clipper.AddObserver( 'EndInteractionEvent', self.endClip )
        self.clipper.AddObserver( 'InteractionEvent', self.executeClip )
#        self.clipper.AddObserver( 'AnyEvent', self.clipObserver )
        
#        self.volumeMapper.SetScalarModeToUsePointFieldData()

#         if vtk.VTK_MAJOR_VERSION <= 5:  self.volumeMapper.SetInput(self.input())
#         else:                           self.volumeMapper.SetInputData(self.input())        
           
        # The volume holds the mapper and the property and can be used to
        # position/orient the volume
        self.volume = vtk.vtkVolume()
        self.volume.SetScale( 1.0, 1.0, 1.0 )
        self.volume.SetMapper( self.volumeMapper )     
#        self.volume.SetScale( spacing[0], spacing[1], spacing[2] )   
        self.setVolRenderCfg( None, False )

        self.volume.SetProperty(self.volumeProperty)
#        self.clipper.AddObserver( 'AnyEvent', self.EventWatcher )
               
#        self.input().AddObserver( 'AnyEvent', self.EventWatcher )
        
        self.volume.SetPosition( self.pos )

        self.renderer.AddVolume( self.volume )
        self.renderer.SetBackground( VTK_BACKGROUND_COLOR[0], VTK_BACKGROUND_COLOR[1], VTK_BACKGROUND_COLOR[2] )
        self.setColormap( [ 'jet', 1, 0, 0 ] )
Exemple #39
0
def vis_volRepos(ren, objName):
    if Repository.Exists(objName)==0:
        raise ValueError("ERROR:  Object does not exist.")
        return
    if Repository.Type(objName) != "StructuredPts":
        raise TypeError("Incorrect object type.")
        return
    caster = [None]*2
    opacityTransferFunction = [None]*2
    colorTransferFunction = [None]*2
    gradientTransferFunction = [None]*2
    volumeProperty = [None]*2
    volumeMapper = [None]*2
    compositeFunction = [None]*2
    outline = [None]*2
    outlineMapper = [None]*2
    outlineProperty = [None]*2
    lod = [None]*2
    
    caster[0] = "vis_vol_caster_"+objName
    opacityTransferFunction[0] = "vis_vol_opacityTransferFunction_"+objName
    colorTransferFunction[0] = "vis_vol_colorTransferFunction_"+objName
    gradientTransferFunction[0] = "vis_vol_gradientTransferFunction_"+objName
    volumeProperty[0] = "vis_vol_volumeProperty_"+objName
    volumeMapper[0] = "vis_vol_volumeMapper_"+objName
    compositeFunction[0] = "vis_vol_compositeFunction_"+objName
    outline[0] = "vis_vol_outline_"+objName
    outlineMapper[0] = "vis_vol_outlineMapper_"+objName
    outlineProperty[0] = "vis_vol_outlineProperty_"+objName
    lod[0] = "vis_vol_lod_" + objName
    
    caster[1] = vtk.vtkImageCast()
    caster[1].SetOutputScalarTypeToUnsignedShort()
    caster[1].SetInputDataObject(Repository.ExportToVtk(objName))
    caster[1].Update()
    
    # Create transfer functions for opacity and color
    opacityTransferFunction[1] = vtk.vtkPiecewiseFunction()
    opacityTransferFunction[1].AddPoint(0,0.)
    opacityTransferFunction[1].AddPoint(80,0.)
    opacityTransferFunction[1].AddPoint(128,0.5)
    opacityTransferFunction[1].AddPoint(150,0.9)
    opacityTransferFunction[1].AddPoint(350,1.0)
    
    colorTransferFunction[1] = vtk.vtkColorTransferFunction()
    colorTransferFunction[1].AddRGBPoint(0,0,0,0)
    colorTransferFunction[1].AddRGBPoint(350,1,1,1)
    
    gradientTransferFunction[1] = vtk.vtkPiecewiseFunction()
    gradientTransferFunction[1].AddPoint(0,1.0)
    gradientTransferFunction[1].AddPoint(1,1.0)
    gradientTransferFunction[1].AddPoint(255,1.0)
    gradientTransferFunction[1].AddPoint(512,1.0)
    
    # Create properties, mappers, volume actors, and ray cast function
    volumeProperty[1] = vtk.vtkVolumeProperty()
    volumeProperty[1].SetColor(colorTransferFunction[1])
    volumeProperty[1].SetScalarOpacity(opacityTransferFunction[1])
    volumeProperty[1].SetGradientOpacity(gradientTransferFunction[1])
    volumeProperty[1].SetInterpolationTypeToLinear()
    
    volumeMapper[1] = vtk.vtkSmartVolumeMapper()
    volumeMapper[1].SetInputDataObject(caster[1].GetOutput())
    
    lod[1] = vtk.vtkVolume()
    lod[1].SetProperty(volumeProperty[1])
    lod[1].SetMapper(volumeMapper[1])
    
    ren[1].AddViewProp(lod[1])
    
    setattr(vis, caster[0], caster)
    setattr(vis, opacityTransferFunction[0], opacityTransferFunction)
    setattr(vis, colorTransferFunction[0], colorTransferFunction)
    setattr(vis, gradientTransferFunction[0], gradientTransferFunction)
    setattr(vis, volumeProperty[0], volumeProperty)
    setattr(vis, volumeMapper[0], volumeMapper)
    setattr(vis, compositeFunction[0], compositeFunction)
    setattr(vis, outline[0], outline)
    setattr(vis, outlineMapper[0], outlineMapper)
    setattr(vis, outlineProperty[0], outlineProperty)
    setattr(vis, lod[0], lod)
    vis.render(ren)
    return lod
Exemple #40
0
def render3d(directory, mouse_queue, mouse_move_event):
    # Create the renderer, the render window, and the interactor. The renderer
    # draws into the render window, the interactor enables mouse- and
    # keyboard-based interaction with the scene.
    renderer = vtk.vtkRenderer()
    render_window = vtk.vtkRenderWindow()
    render_window.SetWindowName("Test")
    render_window.AddRenderer(renderer)
    interactor = vtk.vtkRenderWindowInteractor()
    interactor.SetRenderWindow(render_window)

    # The following reader is used to read a series of 2D slices (images)
    # that compose the volume. The slice dimensions are set, and the
    # pixel spacing. The data Endianness must also be specified. The reader
    # usese the FilePrefix in combination with the slice number to construct
    # filenames using the format FilePrefix.%d. (In this case the FilePrefix
    # is the root name of the file: quarter.)
    reader = vtk.vtkVolume16Reader()
    reader.SetDataDimensions(256, 256)
    reader.SetImageRange(1, 99)
    reader.SetDataByteOrderToLittleEndian()
    reader.SetFilePrefix(os.path.join(directory, 'image'))
    data_spacing = (1, 1, 2)
    reader.SetDataSpacing(data_spacing[0], data_spacing[1], data_spacing[2])

    volume_mapper = vtk.vtkSmartVolumeMapper()
    volume_mapper.SetInputConnection(reader.GetOutputPort())
    volume_mapper.SetBlendModeToComposite()

    # Cutting plane
    plane = vtk.vtkPlane()
    plane.SetOrigin(0, 0, 2)
    plane.SetNormal(0, 0, 1)

    # create cutter
    cutter = vtk.vtkCutter()
    cutter.SetCutFunction(plane)
    cutter.SetInputConnection(reader.GetOutputPort())
    cutter.Update()
    cutterMapper = vtk.vtkPolyDataMapper()
    cutterMapper.SetInputConnection(cutter.GetOutputPort())

    # create plane actor
    planeActor = vtk.vtkActor()
    planeActor.GetProperty().SetColor(1.0, 1, 0)
    planeActor.GetProperty().SetLineWidth(2)
    planeActor.SetMapper(cutterMapper)

    volume_color = vtk.vtkColorTransferFunction()
    volume_color.AddRGBPoint(0, 0.0, 0.0, 0.0)
    volume_color.AddRGBPoint(500, 1.0, 0.5, 0.3)
    volume_color.AddRGBPoint(1000, 1.0, 0.5, 0.3)
    volume_color.AddRGBPoint(1150, 1.0, 1.0, 0.9)

    # The opacity transfer function is used to control the opacity
    # of different tissue types.
    volume_scalar_opacity = vtk.vtkPiecewiseFunction()
    volume_scalar_opacity.AddPoint(0, 0.00)
    volume_scalar_opacity.AddPoint(500, 0.15)
    volume_scalar_opacity.AddPoint(1000, 0.15)
    volume_scalar_opacity.AddPoint(1150, 0.85)

    # The gradient opacity function is used to decrease the opacity
    # in the "flat" regions of the volume while maintaining the opacity
    # at the boundaries between tissue types.  The gradient is measured
    # as the amount by which the intensity changes over unit distance.
    # For most medical data, the unit distance is 1mm.
    volume_gradient_opacity = vtk.vtkPiecewiseFunction()
    volume_gradient_opacity.AddPoint(0, 0.0)
    volume_gradient_opacity.AddPoint(90, 0.5)
    volume_gradient_opacity.AddPoint(100, 1.0)

    # The VolumeProperty attaches the color and opacity functions to the
    # volume, and sets other volume properties.  The interpolation should
    # be set to linear to do a high-quality rendering.  The ShadeOn option
    # turns on directional lighting, which will usually enhance the
    # appearance of the volume and make it look more "3D".  However,
    # the quality of the shading depends on how accurately the gradient
    # of the volume can be calculated, and for noisy data the gradient
    # estimation will be very poor.  The impact of the shading can be
    # decreased by increasing the Ambient coefficient while decreasing
    # the Diffuse and Specular coefficient.  To increase the impact
    # of shading, decrease the Ambient and increase the Diffuse and Specular.
    volumeProperty = vtk.vtkVolumeProperty()
    volumeProperty.SetColor(volume_color)
    volumeProperty.SetScalarOpacity(volume_scalar_opacity)
    volumeProperty.SetGradientOpacity(volume_gradient_opacity)
    volumeProperty.SetInterpolationTypeToLinear()
    volumeProperty.ShadeOn()
    volumeProperty.SetAmbient(0.4)
    volumeProperty.SetDiffuse(0.6)
    volumeProperty.SetSpecular(0.2)

    # The vtkVolume is a vtkProp3D (like a vtkActor) and controls the position
    # and orientation of the volume in world coordinates.
    volume = vtk.vtkVolume()
    volume.SetMapper(volume_mapper)
    volume.SetProperty(volumeProperty)

    # Finally, add the volume to the renderer
    renderer.AddViewProp(volume)
    renderer.AddActor(planeActor)

    # Set up an initial view of the volume.  The focal point will be the
    # center of the volume, and the camera position will be 400mm to the
    # patient's left (which is our right).
    camera = renderer.GetActiveCamera()
    c = volume.GetCenter()
    camera.SetFocalPoint(c[0], c[1], c[2])
    camera.SetPosition(c[0] + 400, c[1], c[2])
    camera.SetViewUp(0, 0, -1)

    # Increase the size of the render window
    render_window.SetSize(640, 480)

    # Interact with the data.
    interactor.Initialize()

    def test(arg1, arg2):
        slice_numbers = []
        while not mouse_queue.empty():
            slice_numbers += [mouse_queue.get()]
        if len(slice_numbers) > 0:
            slice = slice_numbers[-1]
            plane.SetOrigin(0, 0, data_spacing[2] * slice)
            render_window.Render()

    interactor.AddObserver(vtk.vtkCommand.TimerEvent, test)
    timerId = interactor.CreateRepeatingTimer(1)
    render_window.Render()
    interactor.Start()
Exemple #41
0
    def __init__(self,
                 dimx=600,
                 dimy=600,
                 renWin=None,
                 iren=None,
                 ren=None,
                 debug=False):
        '''creates the rendering pipeline'''

        # Handle arguments
        if renWin is not None:
            self.renWin = renWin
        else:
            self.renWin = vtk.vtkRenderWindow()

        if iren is not None:
            self.iren = iren
        else:
            self.iren = vtk.vtkRenderWindowInteractor()

        # create a rendering window and renderer
        if ren is not None:
            self.ren = ren
        else:
            self.ren = vtk.vtkRenderer()
        self.renWin.SetSize(dimx, dimy)
        self.renWin.AddRenderer(self.ren)

        # img 3D as slice
        self.img3D = None
        self.slicenos = [0, 0, 0]
        self.sliceOrientation = SLICE_ORIENTATION_XY
        self.sliceActor = vtk.vtkImageActor()
        self.voi = vtk.vtkExtractVOI()
        self.wl = vtk.vtkImageMapToWindowLevelColors()
        self.ia = vtk.vtkImageHistogramStatistics()
        self.sliceActorNo = 0

        # Viewer Event manager
        self.event = ViewerEventManager()

        # create a renderwindowinteractor
        self.style = CILInteractorStyle(self)
        self.iren.SetInteractorStyle(self.style)
        self.iren.SetRenderWindow(self.renWin)

        # Render decimation
        self.decimate = vtk.vtkDecimatePro()

        self.ren.SetBackground(.1, .2, .4)

        self.actors = {}

        # Help text
        self.helpActor = vtk.vtkActor2D()
        self.helpActor.GetPositionCoordinate(
        ).SetCoordinateSystemToNormalizedDisplay()
        self.helpActor.GetPositionCoordinate().SetValue(0.1, 0.5)
        self.helpActor.VisibilityOff()
        self.ren.AddActor(self.helpActor)

        # volume render
        volumeMapper = vtk.vtkSmartVolumeMapper()
        #volumeMapper = vtk.vtkFixedPointVolumeRayCastMapper()
        self.volume_mapper = volumeMapper

        volumeProperty = vtk.vtkVolumeProperty()
        self.volume_property = volumeProperty

        # The volume holds the mapper and the property and
        # can be used to position/orient the volume.
        volume = vtk.vtkVolume()
        volume.SetMapper(volumeMapper)
        volume.SetProperty(volumeProperty)
        self.volume = volume
        self.volume_render_initialised = False

        # axis orientation widget
        om = vtk.vtkAxesActor()
        ori = vtk.vtkOrientationMarkerWidget()
        ori.SetOutlineColor(0.9300, 0.5700, 0.1300)
        ori.SetInteractor(self.iren)
        ori.SetOrientationMarker(om)
        ori.SetViewport(0.0, 0.0, 0.4, 0.4)
        ori.SetEnabled(1)
        ori.InteractiveOff()
        self.orientation_marker = ori

        self.iren.Initialize()
Exemple #42
0
    def buildPipeline(self):
        """ execute() -> None
        Dispatch the vtkRenderer to the actual rendering widget
        """
        extent = self.input().GetExtent()
        rangeBounds = self.getRangeBounds()
        self.sliceCenter = [(extent[2 * i + 1] - extent[2 * i]) / 2
                            for i in range(3)]
        spacing = self.input().GetSpacing()
        sx, sy, sz = spacing
        origin = self.input().GetOrigin()
        ox, oy, oz = origin
        self._range = [rangeBounds[0], rangeBounds[1], rangeBounds[0], 0]
        dataType = self.input().GetScalarTypeAsString()
        self.setMaxScalarValue(self.input().GetScalarType())
        self.pos = [spacing[i] * extent[2 * i] for i in range(3)]
        #        if ( (origin[0] + self.pos[0]) < 0.0): self.pos[0] = self.pos[0] + 360.0
        bounds = [(origin[i / 2] + spacing[i / 2] * extent[i])
                  for i in range(6)]
        print " @@@VolumeRenderer@@@   Data Type = %s, range = (%f,%f), max_scalar = %s" % (
            dataType, rangeBounds[0], rangeBounds[1], self._max_scalar_value)
        print "Extent: %s " % str(self.input().GetExtent())
        print "Spacing: %s " % str(spacing)
        print "Origin: %s " % str(origin)
        print "Dimensions: %s " % str(self.input().GetDimensions())
        print "Bounds: %s " % str(bounds)
        print "Input Bounds: %s " % str(self.input().GetBounds())
        print "VolumePosition: %s " % str(self.pos)

        #        self.inputInfo = self.inputPort.GetInformation()
        #        translation = inputInfo.Get( ResampleTranslationKey  )

        # Create transfer mapping scalar value to color
        self.colorTransferFunction = vtk.vtkColorTransferFunction()

        # Create transfer mapping scalar value to opacity
        self.opacityTransferFunction = vtk.vtkPiecewiseFunction()

        # The property describes how the data will look
        self.volumeProperty = vtk.vtkVolumeProperty()
        self.volumeProperty.SetInterpolationType(vtk.VTK_LINEAR_INTERPOLATION)
        self.volumeProperty.SetColor(self.colorTransferFunction)
        self.volumeProperty.SetScalarOpacity(self.opacityTransferFunction)
        #        self.volumeProperty.SetGradientOpacity(self.opacityTransferFunction)

        # The mapper knows how to render the data

        #        self.volumeMapperTexture2D = vtk.vtkVolumeTextureMapper2D()
        self.volumeMapper = vtk.vtkSmartVolumeMapper()
        self.volumeMapper.SetBlendModeToComposite()
        self.volumeMapper.CroppingOff()

        self.clipper = vtk.vtkBoxWidget()
        self.clipper.RotationEnabledOff()
        self.clipper.SetPlaceFactor(1.0)
        self.clipper.AddObserver('StartInteractionEvent', self.startClip)
        self.clipper.AddObserver('EndInteractionEvent', self.endClip)
        self.clipper.AddObserver('InteractionEvent', self.executeClip)
        #        self.clipper.AddObserver( 'AnyEvent', self.clipObserver )

        #        self.volumeMapper.SetScalarModeToUsePointFieldData()
        #        self.inputModule.inputToAlgorithm( self.volumeMapper )

        # The volume holds the mapper and the property and can be used to
        # position/orient the volume
        self.volume = vtk.vtkVolume()
        self.volume.SetScale(1.0, 1.0, 1.0)
        self.volume.SetMapper(self.volumeMapper)
        #        self.volume.SetScale( spacing[0], spacing[1], spacing[2] )
        self.setVolRenderCfg(None, False)

        self.volume.SetProperty(self.volumeProperty)
        #        self.clipper.AddObserver( 'AnyEvent', self.EventWatcher )

        #        self.input().AddObserver( 'AnyEvent', self.EventWatcher )

        self.volume.SetPosition(self.pos)

        self.renderer.AddVolume(self.volume)
        self.renderer.SetBackground(VTK_BACKGROUND_COLOR[0],
                                    VTK_BACKGROUND_COLOR[1],
                                    VTK_BACKGROUND_COLOR[2])
Exemple #43
0
    def __init__(
        self,
        inputobj=None,
        c='RdBu_r',
        alpha=(0.0, 0.0, 0.2, 0.4, 0.8, 1.0),
        alphaGradient=None,
        alphaUnit=1,
        mode=0,
        shade=False,
        spacing=None,
        dims=None,
        origin=None,
        mapper='smart',
    ):

        vtk.vtkVolume.__init__(self)
        BaseGrid.__init__(self)

        ###################
        if isinstance(inputobj, str):

            if "https://" in inputobj:
                from vedo.io import download
                inputobj = download(inputobj, verbose=False)  # fpath
            elif os.path.isfile(inputobj):
                pass
            else:
                inputobj = sorted(glob.glob(inputobj))

        ###################
        if 'gpu' in mapper:
            self._mapper = vtk.vtkGPUVolumeRayCastMapper()
        elif 'opengl_gpu' in mapper:
            self._mapper = vtk.vtkOpenGLGPUVolumeRayCastMapper()
        elif 'smart' in mapper:
            self._mapper = vtk.vtkSmartVolumeMapper()
        elif 'fixed' in mapper:
            self._mapper = vtk.vtkFixedPointVolumeRayCastMapper()
        elif isinstance(mapper, vtk.vtkMapper):
            self._mapper = mapper
        else:
            print("Error unknown mapper type", [mapper])
            raise RuntimeError()
        self.SetMapper(self._mapper)

        ###################
        inputtype = str(type(inputobj))
        #colors.printc('Volume inputtype', inputtype)

        if inputobj is None:
            img = vtk.vtkImageData()

        elif utils.isSequence(inputobj):

            if isinstance(inputobj[0], str):  # scan sequence of BMP files
                ima = vtk.vtkImageAppend()
                ima.SetAppendAxis(2)
                pb = utils.ProgressBar(0, len(inputobj))
                for i in pb.range():
                    f = inputobj[i]
                    picr = vtk.vtkBMPReader()
                    picr.SetFileName(f)
                    picr.Update()
                    mgf = vtk.vtkImageMagnitude()
                    mgf.SetInputData(picr.GetOutput())
                    mgf.Update()
                    ima.AddInputData(mgf.GetOutput())
                    pb.print('loading...')
                ima.Update()
                img = ima.GetOutput()

            else:
                if "ndarray" not in inputtype:
                    inputobj = np.array(inputobj)

                if len(inputobj.shape) == 1:
                    varr = numpy_to_vtk(inputobj,
                                        deep=True,
                                        array_type=vtk.VTK_FLOAT)
                else:
                    if len(inputobj.shape) > 2:
                        inputobj = np.transpose(inputobj, axes=[2, 1, 0])
                    varr = numpy_to_vtk(inputobj.ravel(order='F'),
                                        deep=True,
                                        array_type=vtk.VTK_FLOAT)
                varr.SetName('input_scalars')

                img = vtk.vtkImageData()
                if dims is not None:
                    img.SetDimensions(dims)
                else:
                    if len(inputobj.shape) == 1:
                        colors.printc(
                            "Error: must set dimensions (dims keyword) in Volume.",
                            c='r')
                        raise RuntimeError()
                    img.SetDimensions(inputobj.shape)
                img.GetPointData().SetScalars(varr)

                #to convert rgb to numpy
                #        img_scalar = data.GetPointData().GetScalars()
                #        dims = data.GetDimensions()
                #        n_comp = img_scalar.GetNumberOfComponents()
                #        temp = numpy_support.vtk_to_numpy(img_scalar)
                #        numpy_data = temp.reshape(dims[1],dims[0],n_comp)
                #        numpy_data = numpy_data.transpose(0,1,2)
                #        numpy_data = np.flipud(numpy_data)

        elif "ImageData" in inputtype:
            img = inputobj

        elif isinstance(inputobj, Volume):
            img = inputobj.inputdata()

        elif "UniformGrid" in inputtype:
            img = inputobj

        elif hasattr(
                inputobj,
                "GetOutput"):  # passing vtk object, try extract imagdedata
            if hasattr(inputobj, "Update"):
                inputobj.Update()
            img = inputobj.GetOutput()

        elif isinstance(inputobj, str):
            from vedo.io import loadImageData, download
            if "https://" in inputobj:
                inputobj = download(inputobj, verbose=False)
            img = loadImageData(inputobj)

        else:
            colors.printc("Volume(): cannot understand input type:\n",
                          inputtype,
                          c='r')
            return

        if dims is not None:
            img.SetDimensions(dims)

        if origin is not None:
            img.SetOrigin(origin)  ### DIFFERENT from volume.origin()!

        if spacing is not None:
            img.SetSpacing(spacing)

        self._data = img
        self._mapper.SetInputData(img)
        self.mode(mode).color(c).alpha(alpha).alphaGradient(alphaGradient)
        self.GetProperty().SetShade(True)
        self.GetProperty().SetInterpolationType(1)
        self.GetProperty().SetScalarOpacityUnitDistance(alphaUnit)

        # remember stuff:
        self._mode = mode
        self._color = c
        self._alpha = alpha
        self._alphaGrad = alphaGradient
        self._alphaUnit = alphaUnit
Exemple #44
0
    
    im = alg.GetOutputPort()
    #m = vtk.vtkPolyDataMapper()
    #m.SetInputConnection(im)

    #cf = vtk.vtkContourFilter()
    #cf.SetInputConnection(alg.GetOutputPort())
    #cf.SetValue(0, 200)
    
    # The volume will be displayed by ray-cast alpha compositing.
    # A ray-cast mapper is needed to do the ray-casting, and a
    # compositing function is needed to do the compositing along the ray.
    #rayCastFunction = vtk.vtkVolumeRayCastCompositeFunction()
    
    #volumeMapper = vtk.vtkVolumeRayCastMapper()
    volumeMapper = vtk.vtkSmartVolumeMapper()
    volumeMapper.SetInputConnection( im )
    #volumeMapper.SetVolumeRayCastFunction(rayCastFunction)
    
    attr = f['majEigenVal'][:]
    min = attr.min()
    max = attr.max()
    
    # The color transfer function maps voxel intensities to colors.
    # It is modality-specific, and often anatomy-specific as well.
    # The goal is to one color for flesh (between 500 and 1000)
    # and another color for bone (1150 and over).
    volumeColor = vtk.vtkColorTransferFunction()
    volumeColor.AddRGBPoint(min,    0.0, 0.0, 0.0)
    #volumeColor.AddRGBPoint(500,  1.0, 0.5, 0.3)
    #volumeColor.AddRGBPoint(1000, 1.0, 0.5, 0.3)
Exemple #45
0
    def BuildView(self):

        # ensure python 2-3 compatibility for checking string type (difference with unicode str handeling)
        PY3 = sys.version_info[0] == 3

        if not self.vmtkRenderer:
            self.vmtkRenderer = vmtkrenderer.vmtkRenderer()
            self.vmtkRenderer.Initialize()
            self.OwnRenderer = 1

        self.vmtkRenderer.RegisterScript(self) 

        if (self.ArrayName != ''):
            self.Image.GetPointData().SetActiveScalars(self.ArrayName)

        if PY3:
            string_types = str,
        else:
            string_types = basestring,
        if not isinstance(self.VolumeRenderingMethod, string_types):
            self.PrintError('Specified Rendering Method is not of required "string" type')
            
        # create volume mapper and apply requested volume rendering method
        volumeMapper = vtk.vtkSmartVolumeMapper()
        if self.VolumeRenderingMethod.lower() == 'default':
            volumeMapper.SetRequestedRenderModeToDefault()
        elif self.VolumeRenderingMethod.lower() == 'gpu':
            volumeMapper.SetRequestedRenderModeToGPU()
        elif self.VolumeRenderingMethod.lower() == 'ospray':
            volumeMapper.SetRequestedRenderModeToOSPRay()
        elif self.VolumeRenderingMethod.lower() == 'raycast':
            volumeMapper.SetRequestedRenderModeToRayCast()
        else:
            self.PrintError('Specified Rendering Method: ' + self.VolumeRenderingMethod + ' not supported. Please choose from ["default", "gpu", "ospray", "raycast"]')
        volumeMapper.SetInputData(self.Image)
        volumeMapper.SetBlendModeToComposite()
        
        
        # create the volume from the mapper (defining image data and render mode) with the defined properties
        # this is the last pipeline step applied. self.Volume just needs to now be added to the Renderer
        self.SetPresetVolumeProperty()
        self.Volume = vtk.vtkVolume()
        self.Volume.SetMapper(volumeMapper)
        self.Volume.SetProperty(self.VolumeProperty)

        # add the actors to the renderer
        self.vmtkRenderer.Renderer.AddVolume(self.Volume)

        # This next section is responsible for creating the box outline around the volume's data extent.
        if self.BoxOutline:
            outline = vtk.vtkOutlineFilter()
            outline.SetInputData(self.Image)
            outlineMapper = vtk.vtkPolyDataMapper()
            outlineMapper.SetInputConnection(outline.GetOutputPort())
            outlineActor = vtk.vtkActor()
            outlineActor.SetMapper(outlineMapper)

            # The SetInteractor method is how 3D widgets are associated with the
            # render window interactor. Internally, SetInteractor sets up a bunch
            # of callbacks using the Command/Observer mechanism (AddObserver()).
            boxWidget = vtk.vtkBoxWidget()
            boxWidget.SetInteractor(self.vmtkRenderer.RenderWindowInteractor)
            boxWidget.SetPlaceFactor(1.0)

            # Place the interactor initially. The output of the reader is used to
            # place the box widget.
            boxWidget.SetInputData(self.Image)
            boxWidget.PlaceWidget()
            boxWidget.InsideOutOn()

            # Add the actors to the renderer
            self.vmtkRenderer.Renderer.AddActor(outlineActor)

        # add preset callback
        self.vmtkRenderer.AddKeyBinding('w','Change volume render property.',self.PresetCallback)

        if (self.Display == 1):
            self.vmtkRenderer.Render()

        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()