Exemplo n.º 1
0
def volumeRender(reader,ren,renWin):
	#Create transfer mapping scalar value to opacity
	opacityTransferFunction = vtk.vtkPiecewiseFunction()
	opacityTransferFunction.AddPoint(1, 0.0)
	opacityTransferFunction.AddPoint(100, 0.1)
	opacityTransferFunction.AddPoint(255,1.0)

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

	volumeProperty = vtk.vtkVolumeProperty()
	volumeProperty.SetColor(colorTransferFunction)
	volumeProperty.SetScalarOpacity(opacityTransferFunction)
	volumeProperty.ShadeOn()
	volumeProperty.SetInterpolationTypeToLinear()

	compositeFunction = vtk.vtkVolumeRayCastCompositeFunction()
	volumeMapper = vtk.vtkFixedPointVolumeRayCastMapper()
	volumeMapper.SetInputConnection(reader.GetOutputPort())

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

	ren.RemoveAllViewProps()

	ren.AddVolume(volume)
	ren.SetBackground(1,1,1)

	renWin.Render()
 def set_data_reader(self, reader):
     volumeMapper = vtk.vtkFixedPointVolumeRayCastMapper()
     # volumeMapper.SetBlendModeToMaximumIntensity()
     volumeMapper.SetInputData(reader.GetOutput())
     volume = vtk.vtkVolume()
     volume.SetMapper(volumeMapper)
     self.ren.AddVolume(volume)
Exemplo n.º 3
0
    def init_all_VolumeRendering_component(self, flagMesh):
        self.flagMesh = flagMesh
        self.ren= vtk.vtkRenderer()
        self.renWin.AddRenderer(self.ren)
        self.iren = vtk.vtkXRenderWindowInteractor()
        self.iren.SetRenderWindow(self.renWin)

        self.ren.GetVolumes()

        self.alpha_channel_function = vtk.vtkPiecewiseFunction()
        self.alpha_channel_function.AddPoint(0, 0.0, 0.5, 0.0)
        self.alpha_channel_function.AddPoint(255, 1, 0.5, 0.0)

        self.color_function = vtk.vtkColorTransferFunction()
        self.color_function.AddRGBPoint(0, 0, 0.0, 0.0, 0.5, 0.0)
        self.color_function.AddRGBPoint(255, 1, 1, 1, 0.5, 0.0)

        self.volume_property = vtk.vtkVolumeProperty()
        self.volume_property.SetColor(self.color_function)
        self.volume_property.SetScalarOpacity(self.alpha_channel_function)

        self.data_importer = vtk.vtkImageImport()

        if self.flagMesh :
            self.volume_mapper = vtk.vtkPolyDataMapper()
        else:
            self.volume_mapper = vtk.vtkFixedPointVolumeRayCastMapper()

        self.volume = vtk.vtkVolume()
Exemplo n.º 4
0
def vismain(squash,rows,cols,channels,length):

  #alphaChannelFunc = vtk.vtkPiecewiseFunction()
  #alphaChannelFunc.AddPoint(0, 0.0)

  #volumeProperty = vtk.vtkVolumeProperty()
  #volumeProperty.SetScalarOpacity(alphaChannelFunc)

  volumeMapper = vtk.vtkFixedPointVolumeRayCastMapper()
  volumeMapper.SetInputConnection(fromMat2Vtk(squash,rows,cols,channels,length))
  volumeMapper.SetBlendModeToComposite()

  volume = vtk.vtkVolume()
  volume.SetMapper(volumeMapper)
  #volume.SetProperty(volumeProperty)
  volume.Update()   
  
  renderer = vtk.vtkRenderer()
  renderWin = vtk.vtkRenderWindow()
  renderWin.AddRenderer(renderer)
  renderInteractor = vtk.vtkRenderWindowInteractor()
  renderInteractor.SetRenderWindow(renderWin)

  renderer.AddVolume(volume)
  # ... set background color to white ...
  renderer.SetBackground(1, 1, 1)
  # ... and set window size.
  renderWin.SetSize(1000, 1000)

  renderWin.AddObserver("AbortCheckEvent", exitCheck)

  renderInteractor.Initialize()
  # Because nothing will be rendered without any input, we order the first render manually before control is handed over to the main-loop.
  renderWin.Render()
  renderInteractor.Start()
Exemplo n.º 5
0
def volumeRender():
    # Create the standard renderer, render window and interactor.
    ren1 = vtk.vtkRenderer()

    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren1)

    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    # Create the reader for the data.
    reader = vtk.vtkStructuredPointsReader()
    reader.SetFileName('./image/ironProt.vtk')

    # Create transfer mapping scalar value to opacity.
    volumeOpacity = vtk.vtkPiecewiseFunction()
    volumeOpacity.AddPoint(50, 0)
    volumeOpacity.AddPoint(150, 0.4)
    volumeOpacity.AddPoint(200, 0.7)
    volumeOpacity.AddPoint(255, 1)

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

    volumeColor.AddRGBPoint(0.0, 25.0, 25.0, 25.0)
    volumeColor.AddRGBPoint(64.0, 100.0, 100.0, 100.0)
    volumeColor.AddRGBPoint(128.0, 150.0, 150.0, 150.0)
    volumeColor.AddRGBPoint(192.0, 200.0, 200.0, 200.0)
    # The property describes how the data will look.
    volumeProperty = vtk.vtkVolumeProperty()
    volumeProperty.SetColor(volumeColor)
    volumeProperty.SetScalarOpacity(volumeOpacity)
    volumeProperty.ShadeOn()
    volumeProperty.SetInterpolationTypeToLinear()

    # The mapper / ray cast function know how to render the data.
    volumeMapper = vtk.vtkFixedPointVolumeRayCastMapper()
    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)

    colors = vtk.vtkNamedColors()

    ren1.AddVolume(volume)
    ren1.SetBackground(colors.GetColor3d("White"))
    ren1.GetActiveCamera().Azimuth(0)
    ren1.GetActiveCamera().Elevation(15)
    ren1.ResetCameraClippingRange()
    ren1.ResetCamera()

    renWin.SetSize(600, 600)
    renWin.Render()

    iren.Start()
def defaultEnvironment(environment, attribute):
    """
    Default 3d environment renderer. White is the highest value in the frame and black is the lowest value.
    """
    xbounds = environment.mesh.boundsX
    ybounds = environment.mesh.boundsY
    zbounds = environment.mesh.boundsZ

    attributeIndex = environment.current.variables[attribute]

    positions = environment.mesh.voxels
    data = environment.current.data[attributeIndex]

    xCount = np.unique(environment.mesh.voxels[environment.mesh.variables['x']]).shape[0]
    yCount = np.unique(environment.mesh.voxels[environment.mesh.variables['y']]).shape[0]
    zCount = np.unique(environment.mesh.voxels[environment.mesh.variables['z']]).shape[0]

    minimum = np.min(data)
    maximum = np.max(data)
    
    if not maximum == 0:
        data = data / maximum

    data = np.reshape(data, (xCount, yCount, zCount))

    imdata = vtk.vtkImageData()
    depthArray = numpy_support.numpy_to_vtk(data.ravel(), deep=True, array_type=vtk.VTK_DOUBLE)

    imdata.SetDimensions(data.shape)
    imdata.SetSpacing([(xbounds[1] - xbounds[0]) / xCount, (ybounds[1] - ybounds[0]) / yCount, (zbounds[1] - zbounds[0]) / zCount])
    imdata.SetOrigin([xbounds[0], ybounds[0], zbounds[0]])
    imdata.GetPointData().SetScalars(depthArray)

    colorFunc = vtk.vtkColorTransferFunction()
    colorFunc.AddRGBPoint(0.0, 0.0, 0.0, 0.0)
    colorFunc.AddRGBPoint(1.0, 1.0, 1.0, 1.0)

    opacity = vtk.vtkPiecewiseFunction()
    opacity.AddPoint(0.0, 0.0)
    opacity.AddPoint(1, 0.8)

    volumeProperty = vtk.vtkVolumeProperty()
    volumeProperty.SetColor(colorFunc)
    volumeProperty.SetScalarOpacity(opacity)
    volumeProperty.SetInterpolationTypeToLinear()
    volumeProperty.SetIndependentComponents(2)

    volumeMapper = vtk.vtkFixedPointVolumeRayCastMapper()
    volumeMapper.SetInputData(imdata)
    volumeMapper.SetBlendModeToMaximumIntensity()


    volume = vtk.vtkVolume()
    volume.SetMapper(volumeMapper)
    volume.SetProperty(volumeProperty)
    
    return volume
Exemplo n.º 7
0
def vtkGetVolumeRayCastMapper():
  if vtk.VTK_MAJOR_VERSION < 7:  
    compositeFunction = vtk.vtkVolumeRayCastCompositeFunction()
    vol_map = vtk.vtkVolumeRayCastMapper()
    vol_map.SetVolumeRayCastFunction(compositeFunction)
  else:
    vol_map = vtk.vtkFixedPointVolumeRayCastMapper()
    vol_map.SetBlendModeToComposite()  
  #
  return vol_map
Exemplo n.º 8
0
 def __init__(self, name, reader, res, spacing, mat):
     self.name = name
     mapper = vtk.vtkFixedPointVolumeRayCastMapper()
     mapper.SetInputConnection(reader.GetOutputPort())
     mapper.SetBlendModeToComposite()
     self.SetMapper(mapper)
     self.SetProperty(mat)
     self.reader = reader
     self.res = res
     self.spacing = spacing
Exemplo n.º 9
0
    def update_mapper(self):

        if self._gpu:
            mapper = vtk.vtkGPUVolumeRayCastMapper()
        else:
            mapper = vtk.vtkFixedPointVolumeRayCastMapper()

        mapper.SetInputData(self._volume)
        mapper.SetBlendModeToComposite()

        self._mapper = mapper
Exemplo n.º 10
0
    def _setup_for_fixed_point(self):
        """This doesn't seem to work.  After processing is complete,
        it stalls on actually rendering the volume.  No idea.
        """
        
        self._volume_mapper = vtk.vtkFixedPointVolumeRayCastMapper()
        self._volume_mapper.SetBlendModeToComposite()
        #self._volume_mapper.SetBlendModeToMaximumIntensity()

        module_utils.setup_vtk_object_progress(self, self._volume_mapper,
                                           'Preparing render.')
Exemplo n.º 11
0
    def volume_renderer(img):
        #Create the renderers, render window, and interactor
        renWin=vtk.vtkRenderWindow()
        iren = vtk.vtkRenderWindowInteractor()
        iren.SetRenderWindow(renWin)
        ren=vtk.vtkRenderer()
        ren.SetBackground(0.0, 0.0, 0.0)
        renWin.AddRenderer(ren)


        #Create a transfer function mapping scalar value to opacity
        oTFun=vtk.vtkPiecewiseFunction()
        # oTFun.AddSegment(0,1.0,256,0.1)

        oTFun.AddPoint(0, 0.0)
        oTFun.AddPoint(low, 0.1)
        oTFun.AddPoint(high, 0.8)
        oTFun.AddPoint(100, 0.05)

        cTFun=vtk.vtkColorTransferFunction()

        cTFun.AddRGBPoint(0, 0.0, 0.0, 0.0)  # background
        cTFun.AddRGBPoint(low, 0.7, 0.0, 0.3)
        cTFun.AddRGBPoint(high, 0.0, 0.0, 0.5)
        cTFun.AddRGBPoint(200, 1.0, 0.8, 0.5)

        gradient = vtk.vtkPiecewiseFunction()
        gradient.AddPoint(0, 0.0)
        gradient.AddPoint(high, 0.5)
        gradient.AddPoint(150, 1.0)



        property =vtk.vtkVolumeProperty()
        property.SetScalarOpacity(oTFun)
        property.SetColor(cTFun)
        property.SetInterpolationTypeToLinear()



        mapper =vtk.vtkFixedPointVolumeRayCastMapper()
        #mapper.SetBlendModeToMinimumIntensity()
        mapper.SetInputData(img )


        volume =vtk.vtkVolume()
        volume.SetMapper(mapper)
        volume.SetProperty(property)
        volume.Update()

        ren.AddViewProp(volume)

        iren.Initialize()
        iren.Start()
Exemplo n.º 12
0
    def BuildView(self):

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

        self.vmtkRenderer.RegisterScript(self)

        if self.Volume:
            self.vmtkRenderer.Renderer.RemoveVolume(self.Volume)

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

        scalarRange = [0.0, 0.0]

        if self.WindowLevel[0] > 0.0:
            scalarRange = [
                self.WindowLevel[1] - self.WindowLevel[0] / 2.0,
                self.WindowLevel[1] + self.WindowLevel[0] / 2.0
            ]
        else:
            scalarRange = self.Image.GetScalarRange()

        colorTransferFunction = vtk.vtkColorTransferFunction()
        colorTransferFunction.AddRGBPoint(scalarRange[0], 0.0, 0.0, 0.0)
        colorTransferFunction.AddRGBPoint(scalarRange[1], 1.0, 1.0, 1.0)

        volumeMapper = vtk.vtkFixedPointVolumeRayCastMapper()
        volumeMapper.SetInputData(self.Image)
        volumeMapper.SetBlendModeToMaximumIntensity()
        if self.AutoSampleDistance:
            volumeMapper.AutoAdjustSampleDistancesOn()
        else:
            volumeMapper.SetSampleDistance(self.SampleDistance)

        volumeProperty = vtk.vtkVolumeProperty()
        volumeProperty.ShadeOn()
        volumeProperty.SetInterpolationTypeToLinear()
        volumeProperty.SetColor(colorTransferFunction)

        self.Volume = vtk.vtkVolume()
        self.Volume.SetMapper(volumeMapper)
        self.Volume.SetProperty(volumeProperty)

        self.vmtkRenderer.Renderer.AddVolume(self.Volume)

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

        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
Exemplo n.º 13
0
def run_source():
    """https://www.creatis.insa-lyon.fr/~davila/bbtk/Software/new/doc/VTK_Documentation/report-about-vtk-2007-02.pdf"""
    pointSource = get_point_source()
    popSplatter = vtk.vtkGaussianSplatter()  # Splatter :
    popSplatter.SetSampleDimensions(300, 300, 300)  # points -> gauss sphere

    popSplatter.SetInputConnection(pointSource.GetOutputPort())
    # f(x) = scale * exp ( expF *(( r/ Radius )^2) )
    popSplatter.SetRadius(0.1)
    popSplatter.SetExponentFactor(1.0)
    popSplatter.SetScaleFactor(1.0)

    cast = vtk.vtkImageCast()  # uchar conversion
    cast.SetInputConnection(
        popSplatter.GetOutputPort())  # ( required by VRayCast )
    cast.SetOutputScalarTypeToUnsignedChar()

    alphaTF = vtk.vtkPiecewiseFunction()  # Opacity (A-TF)
    alphaTF.AddPoint(0, 0)
    alphaTF.AddPoint(1, 0.01)
    alphaTF.AddPoint(255, 0.5)
    colorTF = vtk.vtkColorTransferFunction()  # Color (RGB -TF)
    colorTF.AddRGBPoint(0, 1, 0.4, 0)
    colorTF.AddRGBPoint(255, 1, 0.0, 0)

    volumeProperty = vtk.vtkVolumeProperty()  # Property
    volumeProperty.SetColor(colorTF)
    volumeProperty.SetScalarOpacity(alphaTF)
    volumeProperty.SetInterpolationTypeToLinear()
    #compositeFunction = vtkVolumeRayCastCompositeFunction()# Mapper

    volumeMapper = vtk.vtkFixedPointVolumeRayCastMapper()  # ( Software )
    #volumeMapper.SetVolumeRayCastFunction(compositeFunction)
    volumeMapper.SetBlendModeToComposite()
    volumeMapper.SetInputConnection(cast.GetOutputPort())

    volume = vtk.vtkVolume()  # Volume = Mapper + Property
    volume.SetMapper(volumeMapper)
    volume.SetProperty(volumeProperty)

    ren = vtk.vtkRenderer()  # Renderer
    ren.AddVolume(volume)
    ren.ResetCamera()
    ren.GetActiveCamera().ParallelProjectionOn()

    renwin = vtk.vtkRenderWindow()  # Window
    renwin.AddRenderer(ren)
    renwin.SetSize(300, 300)
    renwin.SetDesiredUpdateRate(1.0)

    iren = vtk.vtkRenderWindowInteractor()  # Interactor
    iren.SetRenderWindow(renwin)
    iren.Start()
Exemplo n.º 14
0
def load_volume(filename):
    reader = vtk.vtkMetaImageReader()
    reader.SetFileName(filename)
    reader.Update()
    (xMin, xMax, yMin, yMax, zMin,
     zMax) = reader.GetExecutive().GetWholeExtent(
         reader.GetOutputInformation(0))
    (xSpacing, ySpacing, zSpacing) = reader.GetOutput().GetSpacing()
    (x0, y0, z0) = reader.GetOutput().GetOrigin()
    print(f'Origin: {(x0, y0, z0)}')
    print(f'Extents: min: {(xMin, yMin, zMin)}')
    print(f'         max: {(xMax, yMax, zMax)}')
    center = [
        x0 + xSpacing * 0.5 * (xMin + xMax),
        y0 + ySpacing * 0.5 * (yMin + yMax),
        z0 + zSpacing * 0.5 * (zMin + zMax)
    ]

    alphaChannelFunc = vtk.vtkPiecewiseFunction()
    alphaChannelFunc.AddPoint(0, 0.0)
    alphaChannelFunc.AddPoint(130, 0.01)
    alphaChannelFunc.AddPoint(400, 0.27)
    alphaChannelFunc.AddPoint(650, 0.9)
    alphaChannelFunc.AddPoint(1106, 1.0)

    colorFunc = vtk.vtkColorTransferFunction()
    colorFunc.AddRGBPoint(0, 0.0, 0.0, 0.0)
    colorFunc.AddRGBPoint(400, 1.0, 0.0, 0.0)
    colorFunc.AddRGBPoint(650, 1.0, 0.0, 0.0)
    colorFunc.AddRGBPoint(230, 1.0, 0.0, 0.0)
    colorFunc.AddRGBPoint(1106, 0.0, 0.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 properties.
    volumeProperty = vtk.vtkVolumeProperty()
    volumeProperty.SetColor(colorFunc)
    volumeProperty.SetScalarOpacity(alphaChannelFunc)

    volumeMapper = vtk.vtkFixedPointVolumeRayCastMapper()
    volumeMapper.CroppingOn()
    volumeMapper.SetInputConnection(reader.GetOutputPort())

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

    return volume, reader.GetOutputPort()
Exemplo n.º 15
0
    def BuildView(self):

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

        self.vmtkRenderer.RegisterScript(self) 

        if self.Volume:
            self.vmtkRenderer.Renderer.RemoveVolume(self.Volume)

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

        scalarRange = [0.0, 0.0]

        if self.WindowLevel[0] > 0.0:
            scalarRange = [self.WindowLevel[1] - self.WindowLevel[0]/2.0, self.WindowLevel[1] + self.WindowLevel[0]/2.0]
        else:
            scalarRange = self.Image.GetScalarRange()

        colorTransferFunction = vtk.vtkColorTransferFunction()
        colorTransferFunction.AddRGBPoint(scalarRange[0], 0.0, 0.0, 0.0)
        colorTransferFunction.AddRGBPoint(scalarRange[1], 1.0, 1.0, 1.0)

        volumeMapper = vtk.vtkFixedPointVolumeRayCastMapper()
        volumeMapper.SetInput(self.Image)
        volumeMapper.SetBlendModeToMaximumIntensity()
        if self.AutoSampleDistance:
            volumeMapper.AutoAdjustSampleDistancesOn()
        else:
            volumeMapper.SetSampleDistance(self.SampleDistance)
        
        volumeProperty = vtk.vtkVolumeProperty()
        volumeProperty.ShadeOn()
        volumeProperty.SetInterpolationTypeToLinear()
        volumeProperty.SetColor(colorTransferFunction)
        
        self.Volume = vtk.vtkVolume()
        self.Volume.SetMapper(volumeMapper)
        self.Volume.SetProperty(volumeProperty)
      
        self.vmtkRenderer.Renderer.AddVolume(self.Volume)

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

        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
Exemplo n.º 16
0
    def draw_voxels(self):

        self.show_axes = False

        u = self.data['voxels']
        u /= (2 * max([abs(min(u)), abs(max(u))]))
        u += 0.5
        u *= 255

        nx, ny, nz = u.shape
        U = asarray(u, dtype=uint8)
        dstr = U.tostring()

        img = vtkImageImport()
        img.CopyImportVoidPointer(dstr, len(dstr))
        img.SetDataScalarTypeToUnsignedChar()
        img.SetNumberOfScalarComponents(1)
        img.SetDataExtent(0, nz - 1, 0, ny - 1, 0, nx - 1)
        img.SetWholeExtent(0, nz - 1, 0, ny - 1, 0, nx - 1)

        self.gradient = gradient = vtkPiecewiseFunction()
        gradient.AddPoint(1, 0.0)
        gradient.AddPoint(255, 0.2)

        self.cbar = cbar = vtkColorTransferFunction()
        cbar.AddRGBPoint(0.0, 0.0, 0.0, 1.0)
        cbar.AddRGBPoint(42.0, 0.0, 0.5, 1.0)
        cbar.AddRGBPoint(84.0, 0.0, 1.0, 0.5)
        cbar.AddRGBPoint(128.0, 0.0, 1.0, 0.0)
        cbar.AddRGBPoint(168.0, 0.5, 1.0, 0.0)
        cbar.AddRGBPoint(212.0, 1.0, 0.5, 0.0)
        cbar.AddRGBPoint(255.0, 1.0, 0.0, 0.0)

        self.volprop = volprop = vtkVolumeProperty()
        volprop.SetColor(cbar)
        volprop.SetScalarOpacity(gradient)
        volprop.ShadeOff()
        volprop.SetInterpolationTypeToLinear()

        mapper = vtkFixedPointVolumeRayCastMapper()
        mapper.SetInputConnection(img.GetOutputPort())

        volume = vtkVolume()
        volume.SetMapper(mapper)
        volume.SetProperty(volprop)
        self.main.renderer.AddVolume(volume)

        self.main.camera.SetPosition(0, -2 * max([nx, ny, nz]), nz)
        self.main.camera.SetFocalPoint(0.5 * nx, 0.5 * ny, 0.5 * nz)
Exemplo n.º 17
0
def volumeRendering(image, image2, lowerThreshold, upperThreshold):

    color = vtk.vtkColorTransferFunction()
    color.AddRGBPoint(0, 0.0, 0.0, 0.0)  # background
    color.AddRGBPoint(lowerThreshold, 1.0, 0.0, 0.0)
    color.AddRGBPoint(upperThreshold, 0.0, 1.0, 0.0)

    opacity = vtk.vtkPiecewiseFunction()
    opacity.AddPoint(0, 0.0)
    opacity.AddPoint(lowerThreshold, 0.15)
    opacity.AddPoint(upperThreshold, 0.85)

    gradient = vtk.vtkPiecewiseFunction()
    gradient.AddPoint(0, 0.0)
    gradient.AddPoint(90, 0.5)
    gradient.AddPoint(100, 1.0)

    volumeProperty = vtk.vtkVolumeProperty()
    volumeProperty.SetColor(color)
    volumeProperty.SetScalarOpacity(opacity)
    volumeProperty.SetGradientOpacity(gradient)
    volumeProperty.SetInterpolationTypeToLinear()
    volumeProperty.ShadeOn()
    volumeProperty.SetAmbient(0.2)
    volumeProperty.SetDiffuse(0.7)
    volumeProperty.SetSpecular(0.3)

    volumeMapper = vtk.vtkFixedPointVolumeRayCastMapper()
    volumeMapper.SetInputData(image)

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

    ren = vtk.vtkRenderer()
    ren.AddViewProp(volume)
    ren.SetBackground(0, 0, 0)
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren)
    renWin.SetSize(400, 400)

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

    iren.Initialize()
    renWin.Render()
    iren.Start()
    def __init__(self):
        '''
        Constructor
        '''
        vtkPythonViewImage.__init__(self)
        
#        texture mapper in 3D: vtkVolumeMapper
        self.__VolumeMapper = None
#        texture mapper in 3D: vtkVolumeTextureMapper3D
        self.__VolumeTextureMapper = vtk.vtkVolumeTextureMapper3D()
#        volume ray cast mapper vtkFixedPointVolumeRayCastMapper
        self.__VolumeRayCastMapper = vtk.vtkFixedPointVolumeRayCastMapper()
#        volume property: vtkVolumeProperty
        self.__VolumeProperty = vtk.vtkVolumeProperty()
#        volume actor: vtkVolume
        self.__VolumeActor = vtk.vtkVolume()
#        opacity transfer function: vtkPiecewiseFunction
        self.__OpacityFunction = vtk.vtkPiecewiseFunction()
#        color transfer function: vtkColorTransferFunction
        self.__ColorFunction = vtk.vtkColorTransferFunction()
        
#        vtkProp3DCollection
        self.__PhantomCollection = vtk.vtkProp3DCollection()
#        blender: vtkImageBlend
        self.__Blender = None
        
#        image 3D cropping box callback: vtkImage3DCroppingBoxCallback
        self.__Callback = vtkPythonImage3DCroppingBoxCallback()
#        box widget: vtkOrientedBoxWidget
#        self.__BoxWidget = vtkOrientedBoxWidget()    # Now I could not wrap vtkOrientedBoxWidget
        self.__BoxWidget = vtk.vtkBoxWidget()
#        vtkPlane widget: vtkPlaneWidget
        self.__PlaneWidget = vtk.vtkPlaneWidget()
#        annotated cube actor: vtkAnnotatedCubeActor, vtkOrientationMarkerWidget
        self.__Cube = vtk.vtkAnnotatedCubeActor()
        self.__Marker = vtk.vtkOrientationMarkerWidget()
        
        self.SetupVolumeRendering()
        self.SetupWidgets()
        
        self.ShowAnnotationsOn()
        self.getTextProperty().SetColor(0, 0, 0)
        self.SetBackground(0.9, 0.9, 0.9) # white
        
        self.__FirstRender = 1
        self.__RenderingMode = self.PLANAR_RENDERING
        self.__VRQuality = 1
        
        self.__InteractorStyleSwitcher = None
Exemplo n.º 19
0
def main():

    #alphaChannelFunc = vtk.vtkPiecewiseFunction()
    #alphaChannelFunc.AddPoint(0, 0.0)

    #volumeProperty = vtk.vtkVolumeProperty()
    #volumeProperty.SetScalarOpacity(alphaChannelFunc)

    volumeMapper = vtk.vtkFixedPointVolumeRayCastMapper()
    volumeMapper.SetInputConnection(fromVid2Vtk(args))
    volumeMapper.SetBlendModeToComposite()

    opacityTransferFunction = vtk.vtkPiecewiseFunction()
    opacityTransferFunction.AddPoint(20, 0.0)
    opacityTransferFunction.AddPoint(255, 0.2)

    # Create transfer mapping scalar value to color.
    colorTransferFunction = vtk.vtkColorTransferFunction()
    colorTransferFunction.AddRGBPoint(0.0, 0.0, 0.0, 0.0)
    colorTransferFunction.AddRGBPoint(64.0, 1.0, 0.0, 0.0)
    colorTransferFunction.AddRGBPoint(128.0, 0.0, 0.0, 1.0)
    colorTransferFunction.AddRGBPoint(192.0, 0.0, 1.0, 0.0)
    colorTransferFunction.AddRGBPoint(255.0, 0.0, 0.2, 0.0)

    # The property describes how the data will look.
    volumeProperty = vtk.vtkVolumeProperty()
    volumeProperty.SetColor(colorTransferFunction)
    volumeProperty.SetScalarOpacity(opacityTransferFunction)
    #volumeProperty.ShadeOn()
    volumeProperty.SetInterpolationTypeToLinear()

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

    renderer = vtk.vtkRenderer()
    renderWin = vtk.vtkRenderWindow()
    renderWin.AddRenderer(renderer)
    renderInteractor = vtk.vtkRenderWindowInteractor()
    renderInteractor.SetRenderWindow(renderWin)

    renderer.AddVolume(volume)
    renderer.SetBackground(1, 1, 1)
    renderWin.SetSize(400, 400)

    renderInteractor.Initialize()
    renderWin.Render()
    renderInteractor.Start()
Exemplo n.º 20
0
    def volume_render(self, scalar_range):
        i1 = scalar_range[0]
        i2 = scalar_range[1]
        i3 = scalar_range[2]
        volumeMapper = vtk.vtkFixedPointVolumeRayCastMapper()
        volumeMapper.SetInputData(self.volume)

        # 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(0, 0.0, 0.0, 0.0)
        volumeColor.AddRGBPoint(i1, 1.0, 0.5, 0.3)
        volumeColor.AddRGBPoint(i2, 1.0, 0.5, 0.3)
        volumeColor.AddRGBPoint(i3, 1.0, 1.0, 0.9)

        # The opacity transfer function is used to control the opacity
        # of different tissue types.
        volumeScalarOpacity = vtk.vtkPiecewiseFunction()
        volumeScalarOpacity.AddPoint(0, 0.00)
        volumeScalarOpacity.AddPoint(i1, 0.15)
        volumeScalarOpacity.AddPoint(i2, 0.15)
        volumeScalarOpacity.AddPoint(i3, 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.
        volumeGradientOpacity = vtk.vtkPiecewiseFunction()
        volumeGradientOpacity.AddPoint(0, 0.0)
        volumeGradientOpacity.AddPoint(90, 0.5)
        volumeGradientOpacity.AddPoint(100, 1.0)

        volumeProperty = vtk.vtkVolumeProperty()
        volumeProperty.SetColor(volumeColor)
        volumeProperty.SetScalarOpacity(volumeScalarOpacity)
        volumeProperty.SetGradientOpacity(volumeGradientOpacity)
        volumeProperty.SetInterpolationTypeToLinear()
        volumeProperty.ShadeOn()
        volumeProperty.SetAmbient(0.4)
        volumeProperty.SetDiffuse(0.6)
        volumeProperty.SetSpecular(0.2)

        volume = vtk.vtkVolume()
        volume.SetMapper(volumeMapper)
        volume.SetProperty(volumeProperty)
        self.graphics.renderer.AddViewProp(volume)
Exemplo n.º 21
0
	def volumeRender(self):
		#Create transfer mapping scalar value to opacity
		opacityTransferFunction = vtk.vtkPiecewiseFunction()
		opacityTransferFunction.AddPoint(1, 0.0)
		opacityTransferFunction.AddPoint(100, 0.1)
		opacityTransferFunction.AddPoint(255,1.0)

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

		volumeProperty = vtk.vtkVolumeProperty()
		volumeProperty.SetColor(colorTransferFunction)
		volumeProperty.SetScalarOpacity(opacityTransferFunction)
		volumeProperty.ShadeOn()
		volumeProperty.SetInterpolationTypeToLinear()

		compositeFunction = vtk.vtkVolumeRayCastCompositeFunction()
		volumeMapper = vtk.vtkFixedPointVolumeRayCastMapper()
		volumeMapper.SetInputConnection(self.reader.GetOutputPort())

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

		ren = vtk.vtkRenderer()
		renWin = vtk.vtkRenderWindow()
		renWin.AddRenderer(ren)
		iren = vtk.vtkRenderWindowInteractor()
		iren.SetRenderWindow(renWin)
		ren.AddVolume(volume)
		ren.SetBackground(1,1,1)
		renWin.SetSize(600,600)
		renWin.Render()

		iren.Initialize()
		renWin.Render()
		iren.Start() 
Exemplo n.º 22
0
def main():
    # The main window
    window = gtk.Window()
    window.set_title("A GtkGLExtVTKRenderWindow Demo!")
    window.connect("destroy", gtk.mainquit)
    window.connect("delete_event", gtk.mainquit)
    window.set_border_width(10)

    vtkda = GtkGLExtVTKRenderWindow()
    vtkda.show()

    vbox = gtk.VBox(spacing=3)
    vbox.show()
    vbox.pack_start(vtkda)

    button = gtk.Button('My Button')
    button.show()
    vbox.pack_start(button)
    window.add(vbox)

    # if one of the cones from above is not commented out, shows only
    # the cone on a mac, otherwise, it shows
    reader = vtk.vtkPNMReader()
    reader.SetFilePattern("mini/checkerboard%i.pgm")
    size = 5

    reader.SetDataExtent(0, size, 0, size, 0, size)
    reader.SetDataSpacing(1, 1, 1)
    reader.SetDataScalarTypeToUnsignedChar()
    image = reader.GetOutput()
    image.Update()

    mapper = vtk.vtkFixedPointVolumeRayCastMapper()
    mapper.SetInput(image)
    if size < 20:
        mapper.SetSampleDistance(float(size) / 1000)
        mapper.SetInteractiveSampleDistance(float(size) / 500)
    volproperty = vtk.vtkVolumeProperty()
    color = vtk.vtkPiecewiseFunction()
    color.AddSegment(0, 0, 255, 1)
    volproperty.SetColor(0, color)
    volume = vtk.vtkVolume()
    volume.SetMapper(mapper)
    volume.SetProperty(volproperty)

    window.set_size_request(400, 400)

    # The VTK stuff.
    cone = vtk.vtkConeSource()
    cone.SetResolution(80)
    coneMapper = vtk.vtkPolyDataMapper()
    coneMapper.SetInput(cone.GetOutput())
    #coneActor = vtk.vtkLODActor()
    coneActor = vtk.vtkActor()
    coneActor.SetMapper(coneMapper)
    coneActor.GetProperty().SetColor(0.5, 0.5, 1.0)
    ren = vtk.vtkRenderer()
    vtkda.GetRenderWindow().AddRenderer(ren)
    ren.AddActor(coneActor)
    ren.AddActor(volume)

    # show the main window and start event processing.
    window.show()
    gtk.mainloop()
Exemplo n.º 23
0
    def create_volume_prop(volume: np.ndarray,
                           affine: np.ndarray) -> vtk.vtkVolume:
        """
        Convert a numpy 3D matrix to a vtkVolume object
        :param volume:
        :param affine:
        :return:
        """
        volume = volume / volume.max() * 255
        volume = volume.astype('uint8')
        dims = volume.shape

        maxValue = volume.max()
        minValue = volume.min()

        dataImporter = vtk.vtkImageImport()
        data_string = volume.tostring()
        dataImporter.CopyImportVoidPointer(data_string, len(data_string))
        dataImporter.SetDataScalarTypeToUnsignedChar()
        dataImporter.SetNumberOfScalarComponents(1)

        # todo ?????????????????
        # set data spacing
        _, _, spacing, _ = decompose(affine)
        z = abs(spacing)
        dataImporter.SetDataSpacing(z[2], z[0], z[1])
        # dataImporter.SetDataSpacing(2.4, 0.7, 0.7)

        dataImporter.SetDataExtent(0, dims[2] - 1, 0, dims[1] - 1, 0,
                                   dims[0] - 1)
        dataImporter.SetWholeExtent(0, dims[2] - 1, 0, dims[1] - 1, 0,
                                    dims[0] - 1)

        try:
            # Compute by GPU
            volume_mapper = vtk.vtkGPUVolumeRayCastMapper()
        except Exception as e:
            logging.warning("Failed to connect to GPU, render with CPU")
            # Compute by CPU
            volume_mapper = vtk.vtkFixedPointVolumeRayCastMapper()

        out_port: vtk.vtkAlgorithmOutput = dataImporter.GetOutputPort()
        volume_mapper.SetInputConnection(out_port)

        # 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).
        colorLUT = np.arange(minValue, maxValue, maxValue / 5.0)
        print(colorLUT)
        volumeColor = vtk.vtkColorTransferFunction()
        volumeColor.AddRGBPoint(colorLUT[0], 0.0, 0.0, 0.0)
        volumeColor.AddRGBPoint(colorLUT[1], 1.0, 0.5, 0.3)
        volumeColor.AddRGBPoint(colorLUT[2], 1.0, 0.5, 0.3)
        volumeColor.AddRGBPoint(colorLUT[3], 1.0, 1.0, 0.9)

        # The opacity transfer function is used to control the opacity
        # of different tissue types.
        volumeScalarOpacity = vtk.vtkPiecewiseFunction()
        volumeScalarOpacity.AddPoint(colorLUT[0], 0.00)
        volumeScalarOpacity.AddPoint(colorLUT[1], 0.15)
        volumeScalarOpacity.AddPoint(colorLUT[2], 0.5)
        volumeScalarOpacity.AddPoint(colorLUT[3], 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.
        volumeGradientOpacity = vtk.vtkPiecewiseFunction()
        volumeGradientOpacity.AddPoint(0, 0.0)
        volumeGradientOpacity.AddPoint(colorLUT[1] / 2, 0.5)
        volumeGradientOpacity.AddPoint(colorLUT[2] / 2, 1.0)

        volumeProperty = vtk.vtkVolumeProperty()
        volumeProperty.SetColor(volumeColor)
        volumeProperty.SetScalarOpacity(volumeScalarOpacity)
        volumeProperty.SetGradientOpacity(volumeGradientOpacity)
        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.
        actorVolume = vtk.vtkVolume()
        actorVolume.SetMapper(volume_mapper)
        actorVolume.SetProperty(volumeProperty)
        return actorVolume
Exemplo n.º 24
0
 def update(self):
     dicom_io = itk.GDCMImageIO.New()
     
     name_generator = itk.GDCMSeriesFileNames.New()
     name_generator.SetUseSeriesDetails(True)
     name_generator.SetDirectory(self._file_dir)
     
     series_uid = name_generator.GetSeriesUIDs()
 
     #cycle_number = len(series_uid)
     cycle_number = 1
     
     render_window = vtk.vtkRenderWindow()    
     render_window_interactor = vtk.vtkRenderWindowInteractor()
     
     camera = vtk.vtkCamera()
     camera.SetViewUp(0, 1, 0)
     camera.SetPosition(1.0, 0.0, 0.0)
     camera.SetFocalPoint(0.0, 0.0, 0.0)
     #camera.ComputeViewPlaneNormal()
     camera.Dolly(1.5)
     
     for cycle_id in range(0,cycle_number):
         print("*** load cycle: "+str(cycle_id)+" ***")
         
         series_identifier = series_uid[cycle_id]
         
         file_names = name_generator.GetFileNames(series_identifier)
         
         # sort file names
         file_names = list(file_names)
         file_names.sort()
         
         file_names = tuple(file_names)
     
         # set image type to signed short (16-bits/pixel)
         itk_reader = itk.ImageSeriesReader[itk.Image.SS3].New()
         itk_reader.SetImageIO(dicom_io)
         itk_reader.SetFileNames(file_names)
         itk_reader.Update()
         
         # ===================================
         spacing = itk_reader.GetOutput().GetSpacing()
         spacing[2] = 3
         itk_reader.GetOutput().SetSpacing(spacing)
         # ===================================
                    
         print(itk_reader().GetOutput().GetSpacing())
                    
         self.read_image(itk_reader)
         
         # only unsigned char or unsigned short can be accepted by vtkVolumeRayCastMapper, so convert signed short to unsigned short
         val_range = self._image.GetOutput().GetScalarRange()
         min_val = val_range[0]
         max_val = val_range[1]
         diff = max_val - min_val
         slope = 65536/diff # 16-bits/pixel
         inter = -slope*min_val
         shift = inter/slope
         
         shifter = vtk.vtkImageShiftScale()
         shifter.SetShift(shift)
         shifter.SetScale(slope)
         shifter.SetOutputScalarTypeToUnsignedShort()
         shifter.SetInputConnection(self._image.GetOutputPort())
         shifter.ReleaseDataFlagOff()
         shifter.Update()
         
         volume_mapper = vtk.vtkFixedPointVolumeRayCastMapper()
         volume_mapper.SetInputConnection(shifter.GetOutputPort())
         
         volume_color = vtk.vtkColorTransferFunction()
         
         volume_scalar_opacity = vtk.vtkPiecewiseFunction()
         
         volume_property = vtk.vtkVolumeProperty()
         volume_property.SetIndependentComponents(True)
         volume_property.SetColor(volume_color)
         volume_property.SetScalarOpacity(volume_scalar_opacity)
         volume_property.SetInterpolationTypeToNearest()
         
         volume = vtk.vtkVolume()
         volume.SetMapper(volume_mapper)
         volume.SetProperty(volume_property)
         
         volume_color.AddRGBSegment(0.0,0.0,0.0,0.0,1000,1.0,1.0,1.0)
         volume_scalar_opacity.AddSegment(0, 0, 65536, 1) # 16 bits/pixel
         volume_mapper.SetBlendModeToMaximumIntensity()
         
         renderer = vtk.vtkRenderer()
         render_window.AddRenderer(renderer)
         render_window_interactor.SetRenderWindow(render_window)
         
         renderer.AddViewProp(volume)
         #renderer.ResetCameraClippingRange()
         renderer.SetActiveCamera(camera)
         renderer.ResetCamera()
         renderer.SetBackground(0.0,0.0,0.0)
         
         render_window.Render()
         render_window_interactor.Initialize()
         #render_window_interactor.CreateRepeatingTimer(20)
         render_window_interactor.Start()
    def __init__(self, ren, renWin, iren):
        self.ren = ren
        self.renWin = renWin
        self.iren = iren

        # Create a gaussian
        gs = vtk.vtkImageGaussianSource()
        gs.SetWholeExtent(0, 30, 0, 30, 0, 30)
        gs.SetMaximum(255.0)
        gs.SetStandardDeviation(5)
        gs.SetCenter(15, 15, 15)

        # threshold to leave a gap that should show up for
        # gradient opacity
        t = vtk.vtkImageThreshold()
        t.SetInputConnection(gs.GetOutputPort())
        t.ReplaceInOn()
        t.SetInValue(0)
        t.ThresholdBetween(150, 200)

        # Use a shift scale to convert to unsigned char
        ss = vtk.vtkImageShiftScale()
        ss.SetInputConnection(t.GetOutputPort())
        ss.SetOutputScalarTypeToUnsignedChar()

        # grid will be used for two component dependent
        grid0 = vtk.vtkImageGridSource()
        grid0.SetDataScalarTypeToUnsignedChar()
        grid0.SetGridSpacing(10, 10, 10)
        grid0.SetLineValue(200)
        grid0.SetFillValue(10)
        grid0.SetDataExtent(0, 30, 0, 30, 0, 30)

        # use dilation to thicken the grid
        d = vtk.vtkImageContinuousDilate3D()
        d.SetInputConnection(grid0.GetOutputPort())
        d.SetKernelSize(3, 3, 3)

        # Now make a two component dependent
        iac = vtk.vtkImageAppendComponents()
        iac.AddInputConnection(d.GetOutputPort())
        iac.AddInputConnection(ss.GetOutputPort())

        # Some more gaussians for the four component indepent case
        gs1 = vtk.vtkImageGaussianSource()
        gs1.SetWholeExtent(0, 30, 0, 30, 0, 30)
        gs1.SetMaximum(255.0)
        gs1.SetStandardDeviation(4)
        gs1.SetCenter(5, 5, 5)

        t1 = vtk.vtkImageThreshold()
        t1.SetInputConnection(gs1.GetOutputPort())
        t1.ReplaceInOn()
        t1.SetInValue(0)
        t1.ThresholdBetween(150, 256)

        gs2 = vtk.vtkImageGaussianSource()
        gs2.SetWholeExtent(0, 30, 0, 30, 0, 30)
        gs2.SetMaximum(255.0)
        gs2.SetStandardDeviation(4)
        gs2.SetCenter(12, 12, 12)

        gs3 = vtk.vtkImageGaussianSource()
        gs3.SetWholeExtent(0, 30, 0, 30, 0, 30)
        gs3.SetMaximum(255.0)
        gs3.SetStandardDeviation(4)
        gs3.SetCenter(19, 19, 19)

        t3 = vtk.vtkImageThreshold()
        t3.SetInputConnection(gs3.GetOutputPort())
        t3.ReplaceInOn()
        t3.SetInValue(0)
        t3.ThresholdBetween(150, 256)

        gs4 = vtk.vtkImageGaussianSource()
        gs4.SetWholeExtent(0, 30, 0, 30, 0, 30)
        gs4.SetMaximum(255.0)
        gs4.SetStandardDeviation(4)
        gs4.SetCenter(26, 26, 26)

        # we need a few append filters ...
        iac1 = vtk.vtkImageAppendComponents()
        iac1.AddInputConnection(t1.GetOutputPort())
        iac1.AddInputConnection(gs2.GetOutputPort())

        iac2 = vtk.vtkImageAppendComponents()
        iac2.AddInputConnection(iac1.GetOutputPort())
        iac2.AddInputConnection(t3.GetOutputPort())

        iac3 = vtk.vtkImageAppendComponents()
        iac3.AddInputConnection(iac2.GetOutputPort())
        iac3.AddInputConnection(gs4.GetOutputPort())

        # create the four component dependend -
        # use lines in x, y, z for colors
        gridR = vtk.vtkImageGridSource()
        gridR.SetDataScalarTypeToUnsignedChar()
        gridR.SetGridSpacing(10, 100, 100)
        gridR.SetLineValue(250)
        gridR.SetFillValue(100)
        gridR.SetDataExtent(0, 30, 0, 30, 0, 30)

        dR = vtk.vtkImageContinuousDilate3D()
        dR.SetInputConnection(gridR.GetOutputPort())
        dR.SetKernelSize(2, 2, 2)

        gridG = vtk.vtkImageGridSource()
        gridG.SetDataScalarTypeToUnsignedChar()
        gridG.SetGridSpacing(100, 10, 100)
        gridG.SetLineValue(250)
        gridG.SetFillValue(100)
        gridG.SetDataExtent(0, 30, 0, 30, 0, 30)

        dG = vtk.vtkImageContinuousDilate3D()
        dG.SetInputConnection(gridG.GetOutputPort())
        dG.SetKernelSize(2, 2, 2)

        gridB = vtk.vtkImageGridSource()
        gridB.SetDataScalarTypeToUnsignedChar()
        gridB.SetGridSpacing(100, 100, 10)
        gridB.SetLineValue(0)
        gridB.SetFillValue(250)
        gridB.SetDataExtent(0, 30, 0, 30, 0, 30)

        dB = vtk.vtkImageContinuousDilate3D()
        dB.SetInputConnection(gridB.GetOutputPort())
        dB.SetKernelSize(2, 2, 2)

        # need some appending
        iacRG = vtk.vtkImageAppendComponents()
        iacRG.AddInputConnection(dR.GetOutputPort())
        iacRG.AddInputConnection(dG.GetOutputPort())

        iacRGB = vtk.vtkImageAppendComponents()
        iacRGB.AddInputConnection(iacRG.GetOutputPort())
        iacRGB.AddInputConnection(dB.GetOutputPort())

        iacRGBA = vtk.vtkImageAppendComponents()
        iacRGBA.AddInputConnection(iacRGB.GetOutputPort())
        iacRGBA.AddInputConnection(ss.GetOutputPort())

        # We need a bunch of opacity functions

        # this one is a simple ramp to .2
        rampPoint2 = vtk.vtkPiecewiseFunction()
        rampPoint2.AddPoint(0, 0.0)
        rampPoint2.AddPoint(255, 0.2)

        # this one is a simple ramp to 1
        ramp1 = vtk.vtkPiecewiseFunction()
        ramp1.AddPoint(0, 0.0)
        ramp1.AddPoint(255, 1.0)

        # this one shows a sharp surface
        surface = vtk.vtkPiecewiseFunction()
        surface.AddPoint(0, 0.0)
        surface.AddPoint(10, 0.0)
        surface.AddPoint(50, 1.0)
        surface.AddPoint(255, 1.0)


        # this one is constant 1
        constant1 = vtk.vtkPiecewiseFunction()
        constant1.AddPoint(0, 1.0)
        constant1.AddPoint(255, 1.0)

        # this one is used for gradient opacity
        gop = vtk.vtkPiecewiseFunction()
        gop.AddPoint(0, 0.0)
        gop.AddPoint(20, 0.0)
        gop.AddPoint(60, 1.0)
        gop.AddPoint(255, 1.0)


        # We need a bunch of color functions

        # This one is a simple rainbow
        rainbow = vtk.vtkColorTransferFunction()
        rainbow.SetColorSpaceToHSV()
        rainbow.HSVWrapOff()
        rainbow.AddHSVPoint(0, 0.1, 1.0, 1.0)
        rainbow.AddHSVPoint(255, 0.9, 1.0, 1.0)

        # this is constant red
        red = vtk.vtkColorTransferFunction()
        red.AddRGBPoint(0, 1, 0, 0)
        red.AddRGBPoint(255, 1, 0, 0)

        # this is constant green
        green = vtk.vtkColorTransferFunction()
        green.AddRGBPoint(0, 0, 1, 0)
        green.AddRGBPoint(255, 0, 1, 0)

        # this is constant blue
        blue = vtk.vtkColorTransferFunction()
        blue.AddRGBPoint(0, 0, 0, 1)
        blue.AddRGBPoint(255, 0, 0, 1)

        # this is constant yellow
        yellow = vtk.vtkColorTransferFunction()
        yellow.AddRGBPoint(0, 1, 1, 0)
        yellow.AddRGBPoint(255, 1, 1, 0)


        #ren = vtk.vtkRenderer()
        #renWin = vtk.vtkRenderWindow()
        self.renWin.AddRenderer(self.ren)
        self.renWin.SetSize(500, 500)
        #iren = vtk.vtkRenderWindowInteractor()
        self.iren.SetRenderWindow(self.renWin)

        self.ren.GetCullers().InitTraversal()
        culler = self.ren.GetCullers().GetNextItem()
        culler.SetSortingStyleToBackToFront()

        # We need 25 mapper / actor pairs which we will render
        # in a grid. Going down we will vary the input data
        # with the top row unsigned char, then float, then
        # two dependent components, then four dependent components
        # then four independent components. Going across we
        # will vary the rendering method with MIP, Composite,
        # Composite Shade, Composite GO, and Composite GO Shade.

        # Create the 5 by 5 grids
        self.volumeProperty = [[0 for col in range(0, 5)] for row in range(0, 5)]
        self.volumeMapper = [[0 for col in range(0, 5)] for row in range(0, 5)]
        volume = [[0 for col in range(0, 5)] for row in range(0, 5)]

        for i in range(0, 5):
            for j in range(0, 5):

                self.volumeProperty[i][j] = vtk.vtkVolumeProperty()
                self.volumeMapper[i][j] = vtk.vtkFixedPointVolumeRayCastMapper()
                self.volumeMapper[i][j].SetSampleDistance(0.25)

                volume[i][j] = vtk.vtkVolume()
                volume[i][j].SetMapper(self.volumeMapper[i][j])
                volume[i][j].SetProperty(self.volumeProperty[i][j])

                volume[i][j].AddPosition(i * 30, j * 30, 0)

                self.ren.AddVolume(volume[i][j])



        for i in range(0, 5):

            self.volumeMapper[0][i].SetInputConnection(t.GetOutputPort())
            self.volumeMapper[1][i].SetInputConnection(ss.GetOutputPort())
            self.volumeMapper[2][i].SetInputConnection(iac.GetOutputPort())
            self.volumeMapper[3][i].SetInputConnection(iac3.GetOutputPort())
            self.volumeMapper[4][i].SetInputConnection(iacRGBA.GetOutputPort())

            self.volumeMapper[i][0].SetBlendModeToMaximumIntensity()
            self.volumeMapper[i][1].SetBlendModeToComposite()
            self.volumeMapper[i][2].SetBlendModeToComposite()
            self.volumeMapper[i][3].SetBlendModeToComposite()
            self.volumeMapper[i][4].SetBlendModeToComposite()

            self.volumeProperty[0][i].IndependentComponentsOn()
            self.volumeProperty[1][i].IndependentComponentsOn()
            self.volumeProperty[2][i].IndependentComponentsOff()
            self.volumeProperty[3][i].IndependentComponentsOn()
            self.volumeProperty[4][i].IndependentComponentsOff()

            self.volumeProperty[0][i].SetColor(rainbow)
            self.volumeProperty[0][i].SetScalarOpacity(rampPoint2)
            self.volumeProperty[0][i].SetGradientOpacity(constant1)

            self.volumeProperty[1][i].SetColor(rainbow)
            self.volumeProperty[1][i].SetScalarOpacity(rampPoint2)
            self.volumeProperty[1][i].SetGradientOpacity(constant1)

            self.volumeProperty[2][i].SetColor(rainbow)
            self.volumeProperty[2][i].SetScalarOpacity(rampPoint2)
            self.volumeProperty[2][i].SetGradientOpacity(constant1)

            self.volumeProperty[3][i].SetColor(0, red)
            self.volumeProperty[3][i].SetColor(1, green)
            self.volumeProperty[3][i].SetColor(2, blue)
            self.volumeProperty[3][i].SetColor(3, yellow)
            self.volumeProperty[3][i].SetScalarOpacity(0, rampPoint2)
            self.volumeProperty[3][i].SetScalarOpacity(1, rampPoint2)
            self.volumeProperty[3][i].SetScalarOpacity(2, rampPoint2)
            self.volumeProperty[3][i].SetScalarOpacity(3, rampPoint2)
            self.volumeProperty[3][i].SetGradientOpacity(0, constant1)
            self.volumeProperty[3][i].SetGradientOpacity(1, constant1)
            self.volumeProperty[3][i].SetGradientOpacity(2, constant1)
            self.volumeProperty[3][i].SetGradientOpacity(3, constant1)
            self.volumeProperty[3][i].SetComponentWeight(0, 1)
            self.volumeProperty[3][i].SetComponentWeight(1, 1)
            self.volumeProperty[3][i].SetComponentWeight(2, 1)
            self.volumeProperty[3][i].SetComponentWeight(3, 1)

            self.volumeProperty[4][i].SetColor(rainbow)
            self.volumeProperty[4][i].SetScalarOpacity(rampPoint2)
            self.volumeProperty[4][i].SetGradientOpacity(constant1)

            self.volumeProperty[i][2].ShadeOn()
            self.volumeProperty[i][4].ShadeOn(0)
            self.volumeProperty[i][4].ShadeOn(1)
            self.volumeProperty[i][4].ShadeOn(2)
            self.volumeProperty[i][4].ShadeOn(3)


        self.volumeProperty[0][0].SetScalarOpacity(ramp1)
        self.volumeProperty[1][0].SetScalarOpacity(ramp1)
        self.volumeProperty[2][0].SetScalarOpacity(ramp1)
        self.volumeProperty[3][0].SetScalarOpacity(0, surface)
        self.volumeProperty[3][0].SetScalarOpacity(1, surface)
        self.volumeProperty[3][0].SetScalarOpacity(2, surface)
        self.volumeProperty[3][0].SetScalarOpacity(3, surface)
        self.volumeProperty[4][0].SetScalarOpacity(ramp1)

        self.volumeProperty[0][2].SetScalarOpacity(surface)
        self.volumeProperty[1][2].SetScalarOpacity(surface)
        self.volumeProperty[2][2].SetScalarOpacity(surface)
        self.volumeProperty[3][2].SetScalarOpacity(0, surface)
        self.volumeProperty[3][2].SetScalarOpacity(1, surface)
        self.volumeProperty[3][2].SetScalarOpacity(2, surface)
        self.volumeProperty[3][2].SetScalarOpacity(3, surface)
        self.volumeProperty[4][2].SetScalarOpacity(surface)

        self.volumeProperty[0][4].SetScalarOpacity(surface)
        self.volumeProperty[1][4].SetScalarOpacity(surface)
        self.volumeProperty[2][4].SetScalarOpacity(surface)
        self.volumeProperty[3][4].SetScalarOpacity(0, surface)
        self.volumeProperty[3][4].SetScalarOpacity(1, surface)
        self.volumeProperty[3][4].SetScalarOpacity(2, surface)
        self.volumeProperty[3][4].SetScalarOpacity(3, surface)
        self.volumeProperty[4][4].SetScalarOpacity(surface)

        self.volumeProperty[0][3].SetGradientOpacity(gop)
        self.volumeProperty[1][3].SetGradientOpacity(gop)
        self.volumeProperty[2][3].SetGradientOpacity(gop)
        self.volumeProperty[3][3].SetGradientOpacity(0, gop)
        self.volumeProperty[3][3].SetGradientOpacity(2, gop)
        self.volumeProperty[4][3].SetGradientOpacity(gop)

        self.volumeProperty[3][3].SetScalarOpacity(0, ramp1)
        self.volumeProperty[3][3].SetScalarOpacity(2, ramp1)

        self.volumeProperty[0][4].SetGradientOpacity(gop)
        self.volumeProperty[1][4].SetGradientOpacity(gop)
        self.volumeProperty[2][4].SetGradientOpacity(gop)
        self.volumeProperty[3][4].SetGradientOpacity(0, gop)
        self.volumeProperty[3][4].SetGradientOpacity(2, gop)
        self.volumeProperty[4][4].SetGradientOpacity(gop)

        self.renWin.Render()

        self.ren.GetActiveCamera().Dolly(1.3)
        self.ren.GetActiveCamera().Azimuth(15)
        self.ren.GetActiveCamera().Elevation(5)
        self.ren.ResetCameraClippingRange()
Exemplo n.º 26
0
    def __init__(
        self,
        inputobj=None,
        c=('b', 'lb', 'lg', 'y', 'r'),
        alpha=(0.0, 0.0, 0.2, 0.4, 0.8, 1),
        alphaGradient=None,
        mode=0,
        origin=None,
        spacing=None,
        shape=None,
        mapperType='smart',
    ):

        vtk.vtkVolume.__init__(self)
        ActorBase.__init__(self)

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

        if isinstance(inputobj, str):
            import glob
            inputobj = sorted(glob.glob(inputobj))

        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)

                varr = numpy_to_vtk(inputobj.ravel(order='F'),
                                    deep=True,
                                    array_type=vtk.VTK_FLOAT)
                varr.SetName('input_scalars')

                img = vtk.vtkImageData()
                if shape is not None:
                    img.SetDimensions(shape)
                else:
                    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 "UniformGrid" in inputtype:
            img = inputobj
        elif "UnstructuredGrid" in inputtype:
            img = inputobj
            mapperType = 'tetra'
        elif hasattr(
                inputobj,
                "GetOutput"):  # passing vtk object, try extract imagdedata
            if hasattr(inputobj, "Update"):
                inputobj.Update()
            img = inputobj.GetOutput()
        else:
            colors.printc("Volume(): cannot understand input type:\n",
                          inputtype,
                          c=1)
            return

        if 'gpu' in mapperType:
            self._mapper = vtk.vtkGPUVolumeRayCastMapper()
        elif 'opengl_gpu' in mapperType:
            self._mapper = vtk.vtkOpenGLGPUVolumeRayCastMapper()
        elif 'smart' in mapperType:
            self._mapper = vtk.vtkSmartVolumeMapper()
        elif 'fixed' in mapperType:
            self._mapper = vtk.vtkFixedPointVolumeRayCastMapper()
        elif 'tetra' in mapperType:
            self._mapper = vtk.vtkProjectedTetrahedraMapper()
        elif 'unstr' in mapperType:
            self._mapper = vtk.vtkUnstructuredGridVolumeRayCastMapper()
        else:
            print("Error unknown mapperType", mapperType)
            raise RuntimeError()

        if origin is not None:
            img.SetOrigin(origin)
        if spacing is not None:
            img.SetSpacing(spacing)
        if shape is not None:
            img.SetDimensions(shape)

        self._imagedata = img
        self._mapper.SetInputData(img)
        self.SetMapper(self._mapper)
        self.mode(mode).color(c).alpha(alpha).alphaGradient(alphaGradient)
        self.GetProperty().SetInterpolationType(1)
        # remember stuff:
        self._mode = mode
        self._color = c
        self._alpha = alpha
        self._alphaGrad = alphaGradient
    def testVolumePicker(self):
        # volume render a medical data set

        # renderer and interactor
        ren = vtk.vtkRenderer()

        renWin = vtk.vtkRenderWindow()
        renWin.AddRenderer(ren)

        iRen = vtk.vtkRenderWindowInteractor()
        iRen.SetRenderWindow(renWin)

        # read the volume
        v16 = vtk.vtkVolume16Reader()
        v16.SetDataDimensions(64, 64)
        v16.SetImageRange(1, 93)
        v16.SetDataByteOrderToLittleEndian()
        v16.SetFilePrefix(VTK_DATA_ROOT + "/Data/headsq/quarter")
        v16.SetDataSpacing(3.2, 3.2, 1.5)

        #---------------------------------------------------------
        # set up the volume rendering

        volumeMapper = vtk.vtkFixedPointVolumeRayCastMapper()
        volumeMapper.SetInputConnection(v16.GetOutputPort())

        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)

        volumeGradientOpacity = vtk.vtkPiecewiseFunction()
        volumeGradientOpacity.AddPoint(0, 0.0)
        volumeGradientOpacity.AddPoint(90, 0.5)
        volumeGradientOpacity.AddPoint(100, 1.0)

        volumeProperty = vtk.vtkVolumeProperty()
        volumeProperty.SetColor(volumeColor)
        volumeProperty.SetScalarOpacity(volumeScalarOpacity)
        volumeProperty.SetGradientOpacity(volumeGradientOpacity)
        volumeProperty.SetInterpolationTypeToLinear()
        volumeProperty.ShadeOn()
        volumeProperty.SetAmbient(0.6)
        volumeProperty.SetDiffuse(0.6)
        volumeProperty.SetSpecular(0.1)

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

        #---------------------------------------------------------
        # Do the surface rendering
        boneExtractor = vtk.vtkMarchingCubes()
        boneExtractor.SetInputConnection(v16.GetOutputPort())
        boneExtractor.SetValue(0, 1150)

        boneNormals = vtk.vtkPolyDataNormals()
        boneNormals.SetInputConnection(boneExtractor.GetOutputPort())
        boneNormals.SetFeatureAngle(60.0)

        boneStripper = vtk.vtkStripper()
        boneStripper.SetInputConnection(boneNormals.GetOutputPort())

        boneMapper = vtk.vtkPolyDataMapper()
        boneMapper.SetInputConnection(boneStripper.GetOutputPort())
        boneMapper.ScalarVisibilityOff()

        boneProperty = vtk.vtkProperty()
        boneProperty.SetColor(1.0, 1.0, 0.9)

        bone = vtk.vtkActor()
        bone.SetMapper(boneMapper)
        bone.SetProperty(boneProperty)

        #---------------------------------------------------------
        # Create an image actor

        table = vtk.vtkLookupTable()
        table.SetRange(0, 2000)
        table.SetRampToLinear()
        table.SetValueRange(0, 1)
        table.SetHueRange(0, 0)
        table.SetSaturationRange(0, 0)

        mapToColors = vtk.vtkImageMapToColors()
        mapToColors.SetInputConnection(v16.GetOutputPort())
        mapToColors.SetLookupTable(table)

        imageActor = vtk.vtkImageActor()
        imageActor.GetMapper().SetInputConnection(mapToColors.GetOutputPort())
        imageActor.SetDisplayExtent(32, 32, 0, 63, 0, 92)

        #---------------------------------------------------------
        # make a transform and some clipping planes

        transform = vtk.vtkTransform()
        transform.RotateWXYZ(-20, 0.0, -0.7, 0.7)

        volume.SetUserTransform(transform)
        bone.SetUserTransform(transform)
        imageActor.SetUserTransform(transform)

        c = volume.GetCenter()

        volumeClip = vtk.vtkPlane()
        volumeClip.SetNormal(0, 1, 0)
        volumeClip.SetOrigin(c)

        boneClip = vtk.vtkPlane()
        boneClip.SetNormal(0, 0, 1)
        boneClip.SetOrigin(c)

        volumeMapper.AddClippingPlane(volumeClip)
        boneMapper.AddClippingPlane(boneClip)

        #---------------------------------------------------------
        ren.AddViewProp(volume)
        ren.AddViewProp(bone)
        ren.AddViewProp(imageActor)

        camera = ren.GetActiveCamera()
        camera.SetFocalPoint(c)
        camera.SetPosition(c[0] + 500, c[1] - 100, c[2] - 100)
        camera.SetViewUp(0, 0, -1)

        ren.ResetCameraClippingRange()

        renWin.Render()

        #---------------------------------------------------------
        # the cone should point along the Z axis
        coneSource = vtk.vtkConeSource()
        coneSource.CappingOn()
        coneSource.SetHeight(12)
        coneSource.SetRadius(5)
        coneSource.SetResolution(31)
        coneSource.SetCenter(6, 0, 0)
        coneSource.SetDirection(-1, 0, 0)

        #---------------------------------------------------------
        picker = vtk.vtkVolumePicker()
        picker.SetTolerance(1.0e-6)
        picker.SetVolumeOpacityIsovalue(0.01)
        # This should usually be left alone, but is used here to increase coverage
        picker.UseVolumeGradientOpacityOn()

        # A function to point an actor along a vector
        def PointCone(actor, n):
            if n[0] < 0.0:
                actor.RotateWXYZ(180, 0, 1, 0)
                actor.RotateWXYZ(180, (n[0] - 1.0) * 0.5, n[1] * 0.5, n[2] * 0.5)
            else:
                actor.RotateWXYZ(180, (n[0] + 1.0) * 0.5, n[1] * 0.5, n[2] * 0.5)

        # Pick the actor
        picker.Pick(192, 103, 0, ren)
        #print picker
        p = picker.GetPickPosition()
        n = picker.GetPickNormal()

        coneActor1 = vtk.vtkActor()
        coneActor1.PickableOff()
        coneMapper1 = vtk.vtkDataSetMapper()
        coneMapper1.SetInputConnection(coneSource.GetOutputPort())
        coneActor1.SetMapper(coneMapper1)
        coneActor1.GetProperty().SetColor(1, 0, 0)
        coneActor1.SetPosition(p)
        PointCone(coneActor1, n)
        ren.AddViewProp(coneActor1)

        # Pick the volume
        picker.Pick(90, 180, 0, ren)
        p = picker.GetPickPosition()
        n = picker.GetPickNormal()

        coneActor2 = vtk.vtkActor()
        coneActor2.PickableOff()
        coneMapper2 = vtk.vtkDataSetMapper()
        coneMapper2.SetInputConnection(coneSource.GetOutputPort())
        coneActor2.SetMapper(coneMapper2)
        coneActor2.GetProperty().SetColor(1, 0, 0)
        coneActor2.SetPosition(p)
        PointCone(coneActor2, n)
        ren.AddViewProp(coneActor2)

        # Pick the image
        picker.Pick(200, 200, 0, ren)
        p = picker.GetPickPosition()
        n = picker.GetPickNormal()

        coneActor3 = vtk.vtkActor()
        coneActor3.PickableOff()
        coneMapper3 = vtk.vtkDataSetMapper()
        coneMapper3.SetInputConnection(coneSource.GetOutputPort())
        coneActor3.SetMapper(coneMapper3)
        coneActor3.GetProperty().SetColor(1, 0, 0)
        coneActor3.SetPosition(p)
        PointCone(coneActor3, n)
        ren.AddViewProp(coneActor3)

        # Pick a clipping plane
        picker.PickClippingPlanesOn()
        picker.Pick(145, 160, 0, ren)
        p = picker.GetPickPosition()
        n = picker.GetPickNormal()

        coneActor4 = vtk.vtkActor()
        coneActor4.PickableOff()
        coneMapper4 = vtk.vtkDataSetMapper()
        coneMapper4.SetInputConnection(coneSource.GetOutputPort())
        coneActor4.SetMapper(coneMapper4)
        coneActor4.GetProperty().SetColor(1, 0, 0)
        coneActor4.SetPosition(p)
        PointCone(coneActor4, n)
        ren.AddViewProp(coneActor4)

        ren.ResetCameraClippingRange()

        # render and interact with data

        renWin.Render()

        img_file = "VolumePicker.png"
        vtk.test.Testing.compareImage(iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25)
        vtk.test.Testing.interact()
Exemplo n.º 28
0
    def LoadVolume(self):
        proj = prj.Project()
        #image = imagedata_utils.to_vtk(n_array, spacing, slice_number, orientation)

        if not self.loaded_image:
            self.LoadImage()
            self.loaded_image = 1

        image = self.image

        number_filters = len(self.config['convolutionFilters'])

        if (prj.Project().original_orientation == const.AXIAL):
            flip_image = True
        else:
            flip_image = False

        #if (flip_image):
        update_progress = vtk_utils.ShowProgress(2 + number_filters)
        # Flip original vtkImageData
        flip = vtk.vtkImageFlip()
        flip.SetInputData(image)
        flip.SetFilteredAxis(1)
        flip.FlipAboutOriginOn()
        #  flip.ReleaseDataFlagOn()

        flip_ref = weakref.ref(flip)
        flip_ref().AddObserver(
            "ProgressEvent",
            lambda obj, evt: update_progress(flip_ref(), "Rendering..."))
        flip.Update()
        image = flip.GetOutput()

        scale = image.GetScalarRange()
        self.scale = scale

        cast = vtk.vtkImageShiftScale()
        cast.SetInputData(image)
        cast.SetShift(abs(scale[0]))
        cast.SetOutputScalarTypeToUnsignedShort()
        #  cast.ReleaseDataFlagOn()
        cast_ref = weakref.ref(cast)
        cast_ref().AddObserver(
            "ProgressEvent",
            lambda obj, evt: update_progress(cast_ref(), "Rendering..."))
        cast.Update()
        image2 = cast

        self.imagedata = image2
        if self.config['advancedCLUT']:
            self.Create16bColorTable(scale)
            self.CreateOpacityTable(scale)
        else:
            self.Create8bColorTable(scale)
            self.Create8bOpacityTable(scale)

        image2 = self.ApplyConvolution(image2.GetOutput(), update_progress)
        self.final_imagedata = image2

        # Changed the vtkVolumeRayCast to vtkFixedPointVolumeRayCastMapper
        # because it's faster and the image is better
        # TODO: To test if it's true.
        if const.TYPE_RAYCASTING_MAPPER:
            volume_mapper = vtk.vtkVolumeRayCastMapper()
            #volume_mapper.AutoAdjustSampleDistancesOff()
            #volume_mapper.SetInput(image2)
            #volume_mapper.SetVolumeRayCastFunction(composite_function)
            #volume_mapper.SetGradientEstimator(gradientEstimator)
            volume_mapper.IntermixIntersectingGeometryOn()
            self.volume_mapper = volume_mapper
        else:

            if int(ses.Session().rendering) == 0:
                volume_mapper = vtk.vtkFixedPointVolumeRayCastMapper()
                #volume_mapper.AutoAdjustSampleDistancesOff()
                self.volume_mapper = volume_mapper
                volume_mapper.IntermixIntersectingGeometryOn()
            else:
                volume_mapper = vtk.vtkGPUVolumeRayCastMapper()
                volume_mapper.UseJitteringOn()
                self.volume_mapper = volume_mapper

        self.SetTypeRaycasting()
        volume_mapper.SetInputData(image2)

        # TODO: Look to this
        #volume_mapper_hw = vtk.vtkVolumeTextureMapper3D()
        #volume_mapper_hw.SetInput(image2)

        #Cut Plane
        #CutPlane(image2, volume_mapper)

        #self.color_transfer = color_transfer

        volume_properties = vtk.vtkVolumeProperty()
        #volume_properties.IndependentComponentsOn()
        volume_properties.SetInterpolationTypeToLinear()
        volume_properties.SetColor(self.color_transfer)

        try:
            volume_properties.SetScalarOpacity(self.opacity_transfer_func)
        except NameError:
            pass

        if not self.volume_mapper.IsA("vtkGPUVolumeRayCastMapper"):
            # Using these lines to improve the raycasting quality. These values
            # seems related to the distance from ray from raycasting.
            # TODO: Need to see values that improve the quality and don't decrease
            # the performance. 2.0 seems to be a good value to pix_diag
            pix_diag = 2.0
            volume_mapper.SetImageSampleDistance(0.25)
            volume_mapper.SetSampleDistance(pix_diag / 5.0)
            volume_properties.SetScalarOpacityUnitDistance(pix_diag)

        self.volume_properties = volume_properties

        self.SetShading()

        volume = vtk.vtkVolume()
        volume.SetMapper(volume_mapper)
        volume.SetProperty(volume_properties)
        self.volume = volume

        colour = self.GetBackgroundColour()

        self.exist = 1

        if self.plane:
            self.plane.SetVolumeMapper(volume_mapper)

        Publisher.sendMessage('Load volume into viewer',
                              volume=volume,
                              colour=colour,
                              ww=self.ww,
                              wl=self.wl)

        del flip
        del cast
Exemplo n.º 29
0
    coneActor.SetMapper(coneMapper)
    coneActor.GetProperty().SetColor(0.5, 0.5, 1.0)

    # if one of the cones from above is not commented out, shows only
    # the cone on a mac, otherwise, it shows
    reader = vtk.vtkPNMReader()
    reader.SetFilePattern("mini/checkerboard%i.pgm")
    size = 5

    reader.SetDataExtent(0, size, 0, size, 0, size)
    reader.SetDataSpacing(1, 1, 1)
    reader.SetDataScalarTypeToUnsignedChar()
    image = reader.GetOutput()
    image.Update()

    mapper = vtk.vtkFixedPointVolumeRayCastMapper()
    mapper.SetInput(image)
    if size < 20:
        mapper.SetSampleDistance(float(size) / 1000)
        mapper.SetInteractiveSampleDistance(float(size) / 500)
    volproperty = vtk.vtkVolumeProperty()
    color = vtk.vtkPiecewiseFunction()
    color.AddSegment(0, 0, 255, 1)
    volproperty.SetColor(0, color)
    volume = vtk.vtkVolume()
    volume.SetMapper(mapper)
    volume.SetProperty(volproperty)

    ren = vtk.vtkRenderer()
    ren.SetBackground(.5, .5, .5)
    vtkda.GetRenderWindow().AddRenderer(ren)
Exemplo n.º 30
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
Exemplo n.º 31
0
    def SetUp(self):
        '''
        Set up cursor3D
        '''
        def OnClosing():
            self.root.quit()

        def ViewerDown(tkvw):
            viewer = tkvw.GetImageViewer()
            ViewerSetZSlice(tkvw, viewer.GetZSlice() - 1)

        def ViewerUp(tkvw):
            viewer = tkvw.GetImageViewer()
            ViewerSetZSlice(tkvw, viewer.GetZSlice() + 1)

        def ViewerSetZSlice(tkvw, z):
            viewer = tkvw.GetImageViewer()
            viewer.SetZSlice(z)
            txt = 'slice: ' + str(z)
            sliceLabel.configure(text=txt)
            tkvw.Render()

        def SetCursorFromViewer(event):
            x = int(event.x)
            y = int(event.y)
            # We have to flip y axis because tk uses upper right origin.
            self.root.update_idletasks()
            height = int(self.tkvw.configure()['height'][4])
            y = height - y
            z = self.tkvw.GetImageViewer().GetZSlice()
            SetCursor(x / IMAGE_MAG_X, y / IMAGE_MAG_Y, z / IMAGE_MAG_Z)

        def SetCursor(x, y, z):

            CURSOR_X = x
            CURSOR_Y = y
            CURSOR_Z = z

            axes.SetOrigin(CURSOR_X, CURSOR_Y, CURSOR_Z)
            imageCursor.SetCursorPosition(CURSOR_X * IMAGE_MAG_X,
                                          CURSOR_Y * IMAGE_MAG_Y,
                                          CURSOR_Z * IMAGE_MAG_Z)

            self.viewer.Render()
            self.tkrw.Render()

        # Pipeline stuff.
        reader = vtk.vtkSLCReader()
        reader.SetFileName(VTK_DATA_ROOT + "/Data/neghip.slc")
        # Cursor stuff

        magnify = vtk.vtkImageMagnify()
        magnify.SetInputConnection(reader.GetOutputPort())
        magnify.SetMagnificationFactors(IMAGE_MAG_X, IMAGE_MAG_Y, IMAGE_MAG_Z)

        imageCursor = vtk.vtkImageCursor3D()
        imageCursor.SetInputConnection(magnify.GetOutputPort())
        imageCursor.SetCursorPosition(CURSOR_X * IMAGE_MAG_X,
                                      CURSOR_Y * IMAGE_MAG_Y,
                                      CURSOR_Z * IMAGE_MAG_Z)
        imageCursor.SetCursorValue(255)
        imageCursor.SetCursorRadius(50 * IMAGE_MAG_X)

        axes = vtk.vtkAxes()
        axes.SymmetricOn()
        axes.SetOrigin(CURSOR_X, CURSOR_Y, CURSOR_Z)
        axes.SetScaleFactor(50.0)

        axes_mapper = vtk.vtkPolyDataMapper()
        axes_mapper.SetInputConnection(axes.GetOutputPort())

        axesActor = vtk.vtkActor()
        axesActor.SetMapper(axes_mapper)
        axesActor.GetProperty().SetAmbient(0.5)

        # Image viewer stuff.
        viewer = vtk.vtkImageViewer()
        viewer.SetInputConnection(imageCursor.GetOutputPort())
        viewer.SetZSlice(CURSOR_Z * IMAGE_MAG_Z)
        viewer.SetColorWindow(256)
        viewer.SetColorLevel(128)

        # Create transfer functions for opacity and color.
        opacity_transfer_function = vtk.vtkPiecewiseFunction()
        opacity_transfer_function.AddPoint(20, 0.0)
        opacity_transfer_function.AddPoint(255, 0.2)

        color_transfer_function = vtk.vtkColorTransferFunction()
        color_transfer_function.AddRGBPoint(0, 0, 0, 0)
        color_transfer_function.AddRGBPoint(64, 1, 0, 0)
        color_transfer_function.AddRGBPoint(128, 0, 0, 1)
        color_transfer_function.AddRGBPoint(192, 0, 1, 0)
        color_transfer_function.AddRGBPoint(255, 0, .2, 0)

        # Create properties, mappers, volume actors, and ray cast function.
        volume_property = vtk.vtkVolumeProperty()
        volume_property.SetColor(color_transfer_function)
        #         volume_property.SetColor(color_transfer_function[0],
        #                                  color_transfer_function[1],
        #                                  color_transfer_function[2])
        volume_property.SetScalarOpacity(opacity_transfer_function)

        volume_mapper = vtk.vtkFixedPointVolumeRayCastMapper()
        volume_mapper.SetInputConnection(reader.GetOutputPort())

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

        # Create outline.
        outline = vtk.vtkOutlineFilter()
        outline.SetInputConnection(reader.GetOutputPort())

        outline_mapper = vtk.vtkPolyDataMapper()
        outline_mapper.SetInputConnection(outline.GetOutputPort())

        outlineActor = vtk.vtkActor()
        outlineActor.SetMapper(outline_mapper)
        outlineActor.GetProperty().SetColor(1, 1, 1)

        # Create the renderer.
        ren = vtk.vtkRenderer()
        ren.AddActor(axesActor)
        ren.AddVolume(volume)
        ren.SetBackground(0.1, 0.2, 0.4)

        renWin = vtk.vtkRenderWindow()
        renWin.AddRenderer(ren)
        renWin.SetSize(256, 256)

        # Create the GUI: two renderer widgets and a quit button.
        self.root = tkinter.Tk()
        self.root.title("cursor3D")
        # Define what to do when the user explicitly closes a window.
        self.root.protocol("WM_DELETE_WINDOW", OnClosing)

        # Help label, frame and quit button
        helpLabel = tkinter.Label(
            self.root,
            text=
            "MiddleMouse (or shift-LeftMouse) in image viewer to place cursor")
        displayFrame = tkinter.Frame(self.root)
        quitButton = tkinter.Button(self.root, text="Quit", command=OnClosing)

        # Pack the GUI.
        helpLabel.pack()
        displayFrame.pack(fill=BOTH, expand=TRUE)
        quitButton.pack(fill=X)

        # Create the viewer widget.
        viewerFrame = tkinter.Frame(displayFrame)
        viewerFrame.pack(padx=3,
                         pady=3,
                         side=LEFT,
                         anchor=N,
                         fill=BOTH,
                         expand=FALSE)
        self.tkvw = vtkTkImageViewerWidget(viewerFrame,
                                           iv=viewer,
                                           width=264,
                                           height=264)
        viewerControls = tkinter.Frame(viewerFrame)
        viewerControls.pack(side=BOTTOM, anchor=S, fill=BOTH, expand=TRUE)
        self.tkvw.pack(side=TOP, anchor=N, fill=BOTH, expand=FALSE)
        downButton = tkinter.Button(viewerControls,
                                    text="Down",
                                    command=[ViewerDown, self.tkvw])
        upButton = tkinter.Button(viewerControls,
                                  text="Up",
                                  command=[ViewerUp, self.tkvw])
        sliceLabel = tkinter.Label(viewerControls,
                                   text="slice: " +
                                   str(CURSOR_Z * IMAGE_MAG_Z))
        downButton.pack(side=LEFT, expand=TRUE, fill=BOTH)
        upButton.pack(side=LEFT, expand=TRUE, fill=BOTH)
        sliceLabel.pack(side=LEFT, expand=TRUE, fill=BOTH)

        # Create the render widget
        renderFrame = tkinter.Frame(displayFrame)
        renderFrame.pack(padx=3,
                         pady=3,
                         side=LEFT,
                         anchor=N,
                         fill=BOTH,
                         expand=TRUE)
        self.tkrw = vtkTkRenderWidget(renderFrame,
                                      rw=renWin,
                                      width=264,
                                      height=264)

        self.tkrw.pack(side=TOP, anchor=N, fill=BOTH, expand=TRUE)

        # Bindings
        self.tkvw.BindTkImageViewer()
        self.tkrw.BindTkRenderWidget()

        # Lets add an extra binding of the middle button in the image viewer
        # to set the cursor location.
        self.tkvw.bind('<Button-2>', SetCursorFromViewer)
        self.tkvw.bind('<Shift-Button-1>', SetCursorFromViewer)

        # Associate the functions with the buttons and label.
        #
        downButton.config(command=partial(ViewerDown, self.tkvw))
        upButton.config(command=partial(ViewerUp, self.tkvw))
Exemplo n.º 32
0
    def SetUp(self):
        """
        Set up cursor3D
        """

        def OnClosing():
            self.root.quit()

        def ViewerDown(tkvw):
            viewer = tkvw.GetImageViewer()
            ViewerSetZSlice(tkvw, viewer.GetZSlice() - 1)

        def ViewerUp(tkvw):
            viewer = tkvw.GetImageViewer()
            ViewerSetZSlice(tkvw, viewer.GetZSlice() + 1)

        def ViewerSetZSlice(tkvw, z):
            viewer = tkvw.GetImageViewer()
            viewer.SetZSlice(z)
            txt = "slice: " + str(z)
            sliceLabel.configure(text=txt)
            tkvw.Render()

        def SetCursorFromViewer(event):
            x = int(event.x)
            y = int(event.y)
            # We have to flip y axis because tk uses upper right origin.
            self.root.update_idletasks()
            height = int(self.tkvw.configure()["height"][4])
            y = height - y
            z = self.tkvw.GetImageViewer().GetZSlice()
            SetCursor(x / IMAGE_MAG_X, y / IMAGE_MAG_Y, z / IMAGE_MAG_Z)

        def SetCursor(x, y, z):

            CURSOR_X = x
            CURSOR_Y = y
            CURSOR_Z = z

            axes.SetOrigin(CURSOR_X, CURSOR_Y, CURSOR_Z)
            imageCursor.SetCursorPosition(CURSOR_X * IMAGE_MAG_X, CURSOR_Y * IMAGE_MAG_Y, CURSOR_Z * IMAGE_MAG_Z)

            self.viewer.Render()
            self.tkrw.Render()

        # Pipeline stuff.
        reader = vtk.vtkSLCReader()
        reader.SetFileName(VTK_DATA_ROOT + "/Data/neghip.slc")
        # Cursor stuff

        magnify = vtk.vtkImageMagnify()
        magnify.SetInputConnection(reader.GetOutputPort())
        magnify.SetMagnificationFactors(IMAGE_MAG_X, IMAGE_MAG_Y, IMAGE_MAG_Z)

        imageCursor = vtk.vtkImageCursor3D()
        imageCursor.SetInputConnection(magnify.GetOutputPort())
        imageCursor.SetCursorPosition(CURSOR_X * IMAGE_MAG_X, CURSOR_Y * IMAGE_MAG_Y, CURSOR_Z * IMAGE_MAG_Z)
        imageCursor.SetCursorValue(255)
        imageCursor.SetCursorRadius(50 * IMAGE_MAG_X)

        axes = vtk.vtkAxes()
        axes.SymmetricOn()
        axes.SetOrigin(CURSOR_X, CURSOR_Y, CURSOR_Z)
        axes.SetScaleFactor(50.0)

        axes_mapper = vtk.vtkPolyDataMapper()
        axes_mapper.SetInputConnection(axes.GetOutputPort())

        axesActor = vtk.vtkActor()
        axesActor.SetMapper(axes_mapper)
        axesActor.GetProperty().SetAmbient(0.5)

        # Image viewer stuff.
        viewer = vtk.vtkImageViewer()
        viewer.SetInputConnection(imageCursor.GetOutputPort())
        viewer.SetZSlice(CURSOR_Z * IMAGE_MAG_Z)
        viewer.SetColorWindow(256)
        viewer.SetColorLevel(128)

        # Create transfer functions for opacity and color.
        opacity_transfer_function = vtk.vtkPiecewiseFunction()
        opacity_transfer_function.AddPoint(20, 0.0)
        opacity_transfer_function.AddPoint(255, 0.2)

        color_transfer_function = vtk.vtkColorTransferFunction()
        color_transfer_function.AddRGBPoint(0, 0, 0, 0)
        color_transfer_function.AddRGBPoint(64, 1, 0, 0)
        color_transfer_function.AddRGBPoint(128, 0, 0, 1)
        color_transfer_function.AddRGBPoint(192, 0, 1, 0)
        color_transfer_function.AddRGBPoint(255, 0, 0.2, 0)

        # Create properties, mappers, volume actors, and ray cast function.
        volume_property = vtk.vtkVolumeProperty()
        volume_property.SetColor(color_transfer_function)
        #         volume_property.SetColor(color_transfer_function[0],
        #                                  color_transfer_function[1],
        #                                  color_transfer_function[2])
        volume_property.SetScalarOpacity(opacity_transfer_function)

        volume_mapper = vtk.vtkFixedPointVolumeRayCastMapper()
        volume_mapper.SetInputConnection(reader.GetOutputPort())

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

        # Create outline.
        outline = vtk.vtkOutlineFilter()
        outline.SetInputConnection(reader.GetOutputPort())

        outline_mapper = vtk.vtkPolyDataMapper()
        outline_mapper.SetInputConnection(outline.GetOutputPort())

        outlineActor = vtk.vtkActor()
        outlineActor.SetMapper(outline_mapper)
        outlineActor.GetProperty().SetColor(1, 1, 1)

        # Create the renderer.
        ren = vtk.vtkRenderer()
        ren.AddActor(axesActor)
        ren.AddVolume(volume)
        ren.SetBackground(0.1, 0.2, 0.4)

        renWin = vtk.vtkRenderWindow()
        renWin.AddRenderer(ren)
        renWin.SetSize(256, 256)

        # Create the GUI: two renderer widgets and a quit button.
        self.root = tkinter.Tk()
        self.root.title("cursor3D")
        # Define what to do when the user explicitly closes a window.
        self.root.protocol("WM_DELETE_WINDOW", OnClosing)

        # Help label, frame and quit button
        helpLabel = tkinter.Label(self.root, text="MiddleMouse (or shift-LeftMouse) in image viewer to place cursor")
        displayFrame = tkinter.Frame(self.root)
        quitButton = tkinter.Button(self.root, text="Quit", command=OnClosing)

        # Pack the GUI.
        helpLabel.pack()
        displayFrame.pack(fill=BOTH, expand=TRUE)
        quitButton.pack(fill=X)

        # Create the viewer widget.
        viewerFrame = tkinter.Frame(displayFrame)
        viewerFrame.pack(padx=3, pady=3, side=LEFT, anchor=N, fill=BOTH, expand=FALSE)
        self.tkvw = vtkTkImageViewerWidget(viewerFrame, iv=viewer, width=264, height=264)
        viewerControls = tkinter.Frame(viewerFrame)
        viewerControls.pack(side=BOTTOM, anchor=S, fill=BOTH, expand=TRUE)
        self.tkvw.pack(side=TOP, anchor=N, fill=BOTH, expand=FALSE)
        downButton = tkinter.Button(viewerControls, text="Down", command=[ViewerDown, self.tkvw])
        upButton = tkinter.Button(viewerControls, text="Up", command=[ViewerUp, self.tkvw])
        sliceLabel = tkinter.Label(viewerControls, text="slice: " + str(CURSOR_Z * IMAGE_MAG_Z))
        downButton.pack(side=LEFT, expand=TRUE, fill=BOTH)
        upButton.pack(side=LEFT, expand=TRUE, fill=BOTH)
        sliceLabel.pack(side=LEFT, expand=TRUE, fill=BOTH)

        # Create the render widget
        renderFrame = tkinter.Frame(displayFrame)
        renderFrame.pack(padx=3, pady=3, side=LEFT, anchor=N, fill=BOTH, expand=TRUE)
        self.tkrw = vtkTkRenderWidget(renderFrame, rw=renWin, width=264, height=264)

        self.tkrw.pack(side=TOP, anchor=N, fill=BOTH, expand=TRUE)

        # Bindings
        self.tkvw.BindTkImageViewer()
        self.tkrw.BindTkRenderWidget()

        # Lets add an extra binding of the middle button in the image viewer
        # to set the cursor location.
        self.tkvw.bind("<Button-2>", SetCursorFromViewer)
        self.tkvw.bind("<Shift-Button-1>", SetCursorFromViewer)

        # Associate the functions with the buttons and label.
        #
        downButton.config(command=partial(ViewerDown, self.tkvw))
        upButton.config(command=partial(ViewerUp, self.tkvw))
	def updateData(self, data, ctf = None):
		"""
		Method that initializes the VTK rendering based
					 on a dataset
		"""            
		if self.data:
			del self.data
		self.data = data
		
		self.outline.SetInput(self.data)
		self.outlinemapper.SetInput (self.outline.GetOutput ())
		self.outlineactor.SetMapper (self.outlinemapper)
		self.outlineactor.GetProperty().SetColor((255, 255, 255))

		self.renderer.AddActor(self.outlineactor)

		# Create transfer mapping scalar value to opacity
		opacityTransferFunction = vtk.vtkPiecewiseFunction()
		opacityTransferFunction.AddPoint(10, 0.0)
		opacityTransferFunction.AddPoint(255, 0.2)

		colorTransferFunction = ctf
		if not colorTransferFunction:
			print "DIDN'T GET CTF!!"
			# Create transfer mapping scalar value to color
			colorTransferFunction = vtk.vtkColorTransferFunction()
			colorTransferFunction.AddRGBPoint(0.0, 0.0, 0.0, 0.0)
			colorTransferFunction.AddRGBPoint(255.0, 0.0, 1.0, 0.0)
		
		volumeProperty = vtk.vtkVolumeProperty()
		volumeProperty.SetColor(colorTransferFunction)
		volumeProperty.SetScalarOpacity(opacityTransferFunction)
		volumeProperty.ShadeOff()

		data.Update()
		ncomps = data.GetNumberOfScalarComponents()
		if ncomps > 1:
			volumeProperty.IndependentComponentsOff()
		else:
			volumeProperty.IndependentComponentsOn()


		self.volumeMapper =  vtk.vtkFixedPointVolumeRayCastMapper()
		self.volumeMapper.SetIntermixIntersectingGeometry(1)
		self.volumeMapper.SetSampleDistance(2)
		self.volumeMapper.SetBlendModeToComposite()
	
		self.volumeMapper.SetInput(self.data)
		volumeMapper = self.volumeMapper

		volume = vtk.vtkVolume()
		# temporary
		self.renderer.AddVolume(volume)
		
		volume.SetMapper(volumeMapper)
		volume.SetProperty(volumeProperty)
		
		txt = ("X", "Y", "Z")
		for t in txt:
			eval ("self.axes.%sAxisVisibilityOn ()" % t)
			eval ("self.axes.Get%sAxisActor2D().SetLabelFactor(0.5)" % t)

		self.axes.GetProperty ().SetColor ((255, 255, 255))
		self.axes.SetNumberOfLabels (2)
		self.axes.SetFontFactor (1.0)
		self.axes.SetFlyModeToOuterEdges ()
		self.axes.SetCornerOffset (0.0)
		self.axes.ScalingOff ()
		self.axes.SetCamera (self.renderer.GetActiveCamera ())

		self.renderer.AddActor (self.axes)
		self.axes.SetInput (self.outline.GetOutput ())
		

		self.volume = volume
		self.volumeMapper = volumeMapper
		self.volumeProperty = volumeProperty
		self.wxrenwin.Render()
Exemplo n.º 34
0
    def createActor(self, vtkImageData):
        logging.debug("In VtkImageVolume::createActor()")
        self.vtkImageData = vtkImageData
       
        self.mapper = vtk.vtkFixedPointVolumeRayCastMapper()
        self.mapper.SetInput(self.vtkImageData)#clip.GetOutput())
        
        self.updateClipPlanes()

        self.independentComponents = True
        self.scalar = self.vtkImageData.GetScalarRange()
        self.opacityWindow = self.scalar[1] - self.scalar[0]
#        print "self.scalar[1] - self.scalar[0]:", self.scalar[1] , self.scalar[0]
        self.opacityLevel = (self.scalar[1] + self.scalar[0]) / 2.0
        
         
        self.lastmousex = 0
        self.lastmousey = 0

        (xpos, ypos) = self.interactor.GetEventPosition()
        self.opacityWindow += xpos - self.lastmousex
        self.opacityLevel += ypos - self.lastmousey
        
        self.lastmousex = xpos
        self.lastmousey = ypos

        self.createCubeOrientation()

        self.colorFun = vtk.vtkColorTransferFunction()
        self.colorFun.RemoveAllPoints()
        self.opacityFun = vtk.vtkPiecewiseFunction()
        self.opacityFun.RemoveAllPoints()

        self.volumeProperty = vtk.vtkVolumeProperty()
        self.volumeProperty.SetIndependentComponents(self.independentComponents)
        self.volumeProperty.SetColor(self.colorFun)
        self.volumeProperty.SetScalarOpacity(self.opacityFun)
        self.volumeProperty.SetInterpolationTypeToLinear()

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

        self.interactor.Modified()
        self.interactor.Render()
        
        self.mode = None
        self.changeHounsfieldMode("MIP")
            
        self.interactorStyle = vtk.vtkInteractorStyleTrackballCamera()
        self.renderer.SetBackground(0.0, 0.0, 0.0)

        self.camera.SetFocalPoint(0, 0, 0)
        self.camera.SetPosition(0, -1, 0)
        self.camera.SetViewUp(0, 0, 1)
        self.renderer.ResetCamera()
        
        
        self.defaultWindow = self.opacityWindow
        self.defaultLevel = self.opacityLevel
        self.setWindowLevel(self.opacityWindow, self.opacityLevel)
	def updateMethod(self):
		"""
		Set the Rendering method used
		"""				
		self.parameters["QualityValue"] = 0
		if not self.initDone:
			return

		method = self.parameters["Method"]
		self.volumeProperty.SetScalarOpacity(self.otfs[method])
		self.updateOpacityTransferFunction()
		
		tbl = ["Ray cast", "Texture Map", "3D texture map", "MIP", "Isosurface"]
		Logging.info("Volume rendering method: ", tbl[method], kw = "rendering")
		
		#Ray Casting, RGBA Ray Casting, Texture Mapping, MIP
		composites = [vtk.vtkVolumeRayCastCompositeFunction,
					  None,
					  None,
					  vtk.vtkVolumeRayCastMIPFunction,
					  vtk.vtkVolumeRayCastIsosurfaceFunction
					  ]
		blendModes = ["Composite", "Composite", "Composite", "MaximumIntensity", "Composite"]
		if method in [RAYCAST, MIP, ISOSURFACE]:
			# Iso surfacing with fixedpoint mapper is not supported
			if method != ISOSURFACE:
				self.mapper = vtk.vtkFixedPointVolumeRayCastMapper()
				
				#self.mapper.SetAutoAdjustSampleDistances(1)
				self.sampleDistance = self.mapper.GetSampleDistance()
				#self.volumeProperty.IndependentComponentsOff()
				mode = blendModes[method]
				Logging.info("Setting fixed point rendering mode to ", mode, kw = "rendering")
				eval("self.mapper.SetBlendModeTo%s()" % mode)
			else:
				self.mapper = vtk.vtkVolumeRayCastMapper()
				self.function = composites[method]()
				Logging.info("Using ray cast function ", self.function, kw = "rendering")
				self.mapper.SetVolumeRayCastFunction(self.function)
		elif method == TEXTURE_MAPPING_3D: # 3d texture mapping
			self.mapper = vtk.vtkVolumeTextureMapper3D()
			self.sampleDistance = self.mapper.GetSampleDistance()
		elif method == TEXTURE_MAPPING: # texture mapping
			self.mapper = vtk.vtkVolumeTextureMapper2D()
			self.maxPlanes = self.mapper.GetMaximumNumberOfPlanes()

# changed following because seems like a mistake, 19.7.2007 SS
#		if self.haveVolpro and self.method in [RAYCAST, ISOSURFACE, MIP] and self.parameters["UseVolumepro"]:
		if self.haveVolpro and method in [RAYCAST, ISOSURFACE, MIP] and self.parameters["UseVolumepro"]:
			# use volumepro accelerated rendering
			self.mapper = vtk.vtkVolumeProMapper()

			modes = ["Composite", None, None, "MaximumIntensity", "MinimumIntensity"]
			acc = modes[method]
			cmd = "self.mapper.SetBlendModeTo%s()" % acc
			Logging.info("Setting blending mode to ", acc, kw = "rendering")
			eval(cmd)
			Logging.info("Setting parallel projetion", kw = "rendering")
			self.renderer.GetActiveCamera().ParallelProjectionOn()			  
			#self.settingEdit.Enable(0)
			#self.qualitySlider.Enable(0)
		else:
			self.renderer.GetActiveCamera().ParallelProjectionOff()		
			
		self.mapperUpdated = True
Exemplo n.º 36
0
    def updateMethod(self):
        """
		Set the Rendering method used
		"""
        self.parameters["QualityValue"] = 0
        if not self.initDone:
            return

        method = self.parameters["Method"]
        self.volumeProperty.SetScalarOpacity(self.otfs[method])
        self.updateOpacityTransferFunction()

        tbl = [
            "Ray cast", "Texture Map", "3D texture map", "MIP", "Isosurface"
        ]
        Logging.info("Volume rendering method: ", tbl[method], kw="rendering")

        #Ray Casting, RGBA Ray Casting, Texture Mapping, MIP
        composites = [
            vtk.vtkVolumeRayCastCompositeFunction, None, None,
            vtk.vtkVolumeRayCastMIPFunction,
            vtk.vtkVolumeRayCastIsosurfaceFunction
        ]
        blendModes = [
            "Composite", "Composite", "Composite", "MaximumIntensity",
            "Composite"
        ]
        if method in [RAYCAST, MIP, ISOSURFACE]:
            # Iso surfacing with fixedpoint mapper is not supported
            if method != ISOSURFACE:
                self.mapper = vtk.vtkFixedPointVolumeRayCastMapper()

                #self.mapper.SetAutoAdjustSampleDistances(1)
                self.sampleDistance = self.mapper.GetSampleDistance()
                #self.volumeProperty.IndependentComponentsOff()
                mode = blendModes[method]
                Logging.info("Setting fixed point rendering mode to ",
                             mode,
                             kw="rendering")
                eval("self.mapper.SetBlendModeTo%s()" % mode)
            else:
                self.mapper = vtk.vtkVolumeRayCastMapper()
                self.function = composites[method]()
                Logging.info("Using ray cast function ",
                             self.function,
                             kw="rendering")
                self.mapper.SetVolumeRayCastFunction(self.function)
        elif method == TEXTURE_MAPPING_3D:  # 3d texture mapping
            self.mapper = vtk.vtkVolumeTextureMapper3D()
            self.sampleDistance = self.mapper.GetSampleDistance()
        elif method == TEXTURE_MAPPING:  # texture mapping
            self.mapper = vtk.vtkVolumeTextureMapper2D()
            self.maxPlanes = self.mapper.GetMaximumNumberOfPlanes()


# changed following because seems like a mistake, 19.7.2007 SS
#		if self.haveVolpro and self.method in [RAYCAST, ISOSURFACE, MIP] and self.parameters["UseVolumepro"]:
        if self.haveVolpro and method in [
                RAYCAST, ISOSURFACE, MIP
        ] and self.parameters["UseVolumepro"]:
            # use volumepro accelerated rendering
            self.mapper = vtk.vtkVolumeProMapper()

            modes = [
                "Composite", None, None, "MaximumIntensity", "MinimumIntensity"
            ]
            acc = modes[method]
            cmd = "self.mapper.SetBlendModeTo%s()" % acc
            Logging.info("Setting blending mode to ", acc, kw="rendering")
            eval(cmd)
            Logging.info("Setting parallel projetion", kw="rendering")
            self.renderer.GetActiveCamera().ParallelProjectionOn()
            #self.settingEdit.Enable(0)
            #self.qualitySlider.Enable(0)
        else:
            self.renderer.GetActiveCamera().ParallelProjectionOff()

        self.mapperUpdated = True
Exemplo n.º 37
0
def main():
    colors = vtk.vtkNamedColors()

    fileName = 'C:/Users/chenjiaxing/Desktop/Python/vmtk/Spine_Neck.vti'

    reader = vtk.vtkXMLImageDataReader()
    reader.SetFileName(fileName)
    reader.Update()
    cast = vtk.vtkImageCast()
    cast.SetInputData(reader.GetOutput())  
    cast.SetOutputScalarTypeToFloat()
    cast.SetOutputScalarTypeToUnsignedChar()
    cast.Update()
    #**********************************************************************
    rayCastFun = vtk.vtkPiecewiseFunction()
    #定义光线经过体数据后的颜色计算方式
    volumeMapper = vtk.vtkFixedPointVolumeRayCastMapper()
    #光线投射法-最常用的体绘制方法
    volumeMapper.SetInputData(cast.GetOutput())
    #volumeMapper.SetVolumeRayCastFunction(rayCastFun)
    ##method 2

    #vtk.vtkGPUVolumeRayCastMapper> volumeMapperGpu = vtk.vtkGPUVolumeRayCastMapper()

    ##基于GPU加速的光线投射体绘制算法

    #volumeMapperGpu.SetInputData(cast.GetOutput())

    #volumeMapperGpu.SetImageSampleDistance(0.5)

    #volumeMapperGpu.SetSampleDistance(1.0)

    #volumeMapperGpu.SetAutoAdjustSampleDistances(1)

 

    #***********************************************************************

    volumeProperty = vtk.vtkVolumeProperty()#定义对象属性
    volumeProperty.SetInterpolationTypeToLinear()
    volumeProperty.ShadeOn()
    volumeProperty.SetAmbient(0.4)
    volumeProperty.SetDiffuse(0.6)
    volumeProperty.SetSpecular(0.2)
    compositeOpacity = vtk.vtkPiecewiseFunction()
    #Defines a piecewise function mapping.
    compositeOpacity.AddPoint(0, 0.00)
    compositeOpacity.AddPoint(216.19, 0.00)
    compositeOpacity.AddPoint(216.19, 0.851)
    compositeOpacity.AddPoint(256, 1)
    volumeProperty.SetScalarOpacity(compositeOpacity)
    color = vtk.vtkColorTransferFunction()
    color.AddRGBPoint(0, 0.231373, 0.298039, 0.7529)
    color.AddRGBPoint(210.8, 0.517, 0.654, 0.988)
    color.AddRGBPoint(256, 0.705, 0.0156, 0.149)
    volumeProperty.SetColor(color)
    volume = vtk.vtkVolume()
    #represents a volume(data & properties) in a rendered scene
    #volume.SetMapper(volumeMapperGpu)

    volume.SetMapper(volumeMapper)
    volume.SetProperty(volumeProperty)
    rendererVolume = vtk.vtkRenderer()
    renderWindow = vtk.vtkRenderWindow()
    renderWindowInteractor = vtk.vtkRenderWindowInteractor()
    rendererVolume.AddVolume(volume)
    renderWindow.AddRenderer(rendererVolume)
    renderWindowInteractor.SetRenderWindow(renderWindow)
    renderWindow.Render()
    renderWindowInteractor.Start()
Exemplo n.º 38
0
opacityTransferFunction.ClampingOn()

# Create transfer mapping scalar value to color
colorTransferFunction = vtk.vtkColorTransferFunction()
colorTransferFunction.AddHSVPoint(0.0, 0.66, 1.0, 1.0)
colorTransferFunction.AddHSVPoint(50.0, 0.33, 1.0, 1.0)
colorTransferFunction.AddHSVPoint(100.0, 0.00, 1.0, 1.0)

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

# The mapper knows how to render the data
volumeMapper = vtk.vtkFixedPointVolumeRayCastMapper()
volumeMapper.SetInputConnection(readerSS.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)

ren1.AddVolume(volume)

# ren1 AddActor contourActor
ren1.AddActor(boundsActor)

######################################################################
Sphere = vtk.vtkSphereSource()
Exemplo n.º 39
0
    def LoadVolume(self):
        proj = prj.Project()
        #image = imagedata_utils.to_vtk(n_array, spacing, slice_number, orientation) 

        if not self.loaded_image:
            self.LoadImage()
            self.loaded_image = 1

        image = self.image

        number_filters = len(self.config['convolutionFilters'])
        
        if (prj.Project().original_orientation == const.AXIAL):
            flip_image = True
        else:
            flip_image = False
        
        #if (flip_image):    
        update_progress= vtk_utils.ShowProgress(2 + number_filters) 
        # Flip original vtkImageData
        flip = vtk.vtkImageFlip()
        flip.SetInputData(image)
        flip.SetFilteredAxis(1)
        flip.FlipAboutOriginOn()
        #  flip.ReleaseDataFlagOn()

        flip_ref = weakref.ref(flip)
        flip_ref().AddObserver("ProgressEvent", lambda obj,evt:
                            update_progress(flip_ref(), "Rendering..."))
        flip.Update()
        image = flip.GetOutput()
        
        scale = image.GetScalarRange()
        self.scale = scale

        cast = vtk.vtkImageShiftScale()
        cast.SetInputData(image)
        cast.SetShift(abs(scale[0]))
        cast.SetOutputScalarTypeToUnsignedShort()
        #  cast.ReleaseDataFlagOn()
        cast_ref = weakref.ref(cast)
        cast_ref().AddObserver("ProgressEvent", lambda obj,evt:
                            update_progress(cast_ref(), "Rendering..."))
        cast.Update()
        image2 = cast

        self.imagedata = image2
        if self.config['advancedCLUT']:
            self.Create16bColorTable(scale)
            self.CreateOpacityTable(scale)
        else:
            self.Create8bColorTable(scale)
            self.Create8bOpacityTable(scale)

        image2 = self.ApplyConvolution(image2.GetOutput(), update_progress)
        self.final_imagedata = image2

        # Changed the vtkVolumeRayCast to vtkFixedPointVolumeRayCastMapper
        # because it's faster and the image is better
        # TODO: To test if it's true.
        if const.TYPE_RAYCASTING_MAPPER:
            volume_mapper = vtk.vtkVolumeRayCastMapper()
            #volume_mapper.AutoAdjustSampleDistancesOff()
            #volume_mapper.SetInput(image2)
            #volume_mapper.SetVolumeRayCastFunction(composite_function)
            #volume_mapper.SetGradientEstimator(gradientEstimator)
            volume_mapper.IntermixIntersectingGeometryOn()
            self.volume_mapper = volume_mapper
        else:

            if int(ses.Session().rendering) == 0:
                volume_mapper = vtk.vtkFixedPointVolumeRayCastMapper()
                #volume_mapper.AutoAdjustSampleDistancesOff()
                self.volume_mapper = volume_mapper
                volume_mapper.IntermixIntersectingGeometryOn()
            else:
                volume_mapper = vtk.vtkGPUVolumeRayCastMapper()
                self.volume_mapper = volume_mapper

        self.SetTypeRaycasting()
        volume_mapper.SetInputData(image2)

        # TODO: Look to this
        #volume_mapper_hw = vtk.vtkVolumeTextureMapper3D()
        #volume_mapper_hw.SetInput(image2)

        #Cut Plane
        #CutPlane(image2, volume_mapper)

        #self.color_transfer = color_transfer

        volume_properties = vtk.vtkVolumeProperty()
        #volume_properties.IndependentComponentsOn()
        volume_properties.SetInterpolationTypeToLinear()
        volume_properties.SetColor(self.color_transfer)

        try:
            volume_properties.SetScalarOpacity(self.opacity_transfer_func)
        except NameError:
            pass

        # Using these lines to improve the raycasting quality. These values
        # seems related to the distance from ray from raycasting.
        # TODO: Need to see values that improve the quality and don't decrease
        # the performance. 2.0 seems to be a good value to pix_diag
        pix_diag = 2.0
        volume_mapper.SetImageSampleDistance(0.25)
        volume_mapper.SetSampleDistance(pix_diag / 5.0)
        volume_properties.SetScalarOpacityUnitDistance(pix_diag)

        self.volume_properties = volume_properties

        self.SetShading()

        volume = vtk.vtkVolume()
        volume.SetMapper(volume_mapper)
        volume.SetProperty(volume_properties)
        self.volume = volume

        colour = self.GetBackgroundColour()

        self.exist = 1

        Publisher.sendMessage('Load volume into viewer',
                                    (volume, colour, (self.ww, self.wl)))
        del flip
        del cast
Exemplo n.º 40
0
def dual_volumeRendering(image, image2, lowerThreshold, upperThreshold,
                         sigmoid_image):

    color = vtk.vtkColorTransferFunction()
    color.AddRGBPoint(0, 0.0, 0.0, 0.0)  # background
    color.AddRGBPoint(lowerThreshold, 0.0, 0.0, 0.0)
    color.AddRGBPoint(upperThreshold, 1.0, 1.0, 1.0)

    opacity = vtk.vtkPiecewiseFunction()
    opacity.AddPoint(0, 0.0)
    opacity.AddPoint(lowerThreshold, 0.0)
    opacity.AddPoint(upperThreshold, 1)

    gradient = vtk.vtkPiecewiseFunction()
    gradient.AddPoint(0, 0.0)
    # gradient.AddPoint(90, 0.5)
    gradient.AddPoint(255, 1.0)

    volumeProperty = vtk.vtkVolumeProperty()
    volumeProperty.SetColor(color)
    volumeProperty.SetScalarOpacity(opacity)
    volumeProperty.SetGradientOpacity(gradient)
    volumeProperty.SetInterpolationTypeToLinear()
    volumeProperty.ShadeOn()
    volumeProperty.SetAmbient(0.1)
    volumeProperty.SetDiffuse(0.7)
    volumeProperty.SetSpecular(0.1)

    color2 = vtk.vtkColorTransferFunction()
    color2.AddRGBPoint(0, 0.0, 0.0, 0.0)  # background
    color2.AddRGBPoint(lowerThreshold, 0.0, 0.0, 0.0)
    color2.AddRGBPoint(upperThreshold, 1.0, 0.0, 0.0)

    opacity2 = vtk.vtkPiecewiseFunction()
    opacity2.AddPoint(0, 0.0)
    opacity2.AddPoint(lowerThreshold, 0.0)
    opacity2.AddPoint(upperThreshold, 1.0)

    gradient2 = vtk.vtkPiecewiseFunction()
    gradient2.AddPoint(0, 0.0)
    # gradient2.AddPoint(90, 0.5)
    # gradient2.AddPoint(100,1.0)
    gradient2.AddPoint(255, 1.0)

    volumeProperty2 = vtk.vtkVolumeProperty()
    volumeProperty2.SetColor(color2)
    volumeProperty2.SetScalarOpacity(opacity2)
    volumeProperty2.SetGradientOpacity(gradient2)
    volumeProperty2.SetInterpolationTypeToLinear()
    volumeProperty2.ShadeOn()
    volumeProperty2.SetAmbient(0.1)
    volumeProperty2.SetDiffuse(1.0)
    volumeProperty2.SetSpecular(0.1)

    #######################################
    color3 = vtk.vtkColorTransferFunction()
    color3.AddRGBPoint(0, 0.0, 0.0, 0.0)  # background
    color3.AddRGBPoint(lowerThreshold, 0.0, 0.0, 0.0)
    color3.AddRGBPoint(upperThreshold, 0.0, 1.0, 0.0)

    opacity3 = vtk.vtkPiecewiseFunction()
    opacity3.AddPoint(0, 0.0)
    opacity3.AddPoint(lowerThreshold, 0.0)
    opacity3.AddPoint(upperThreshold, 1)

    gradient3 = vtk.vtkPiecewiseFunction()
    gradient3.AddPoint(0, 0.0)
    # gradient.AddPoint(90, 0.5)
    gradient3.AddPoint(255, 1.0)

    volumeProperty3 = vtk.vtkVolumeProperty()
    volumeProperty3.SetColor(color3)
    volumeProperty3.SetScalarOpacity(opacity)
    volumeProperty3.SetGradientOpacity(gradient)
    volumeProperty3.SetInterpolationTypeToLinear()
    volumeProperty3.ShadeOn()
    volumeProperty3.SetAmbient(0.1)
    volumeProperty3.SetDiffuse(0.7)
    volumeProperty3.SetSpecular(0.1)
    ###########################################

    volumeMapper = vtk.vtkFixedPointVolumeRayCastMapper()
    volumeMapper.SetInputData(image)

    volumeMapper2 = vtk.vtkFixedPointVolumeRayCastMapper()
    volumeMapper2.SetInputData(image2)

    volumeMapper3 = vtk.vtkFixedPointVolumeRayCastMapper()
    volumeMapper3.SetInputData(sigmoid_image)

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

    volume2 = vtk.vtkVolume()
    volume2.SetMapper(volumeMapper2)
    volume2.SetProperty(volumeProperty2)
    volume2.Update()

    volume3 = vtk.vtkVolume()
    volume3.SetMapper(volumeMapper3)
    volume3.SetProperty(volumeProperty3)
    volume3.Update()

    sphere_view = vtk.vtkSphereSource()
    sphere_view.SetCenter(30, 0, 550)
    sphere_view.SetRadius(5.0)
    # sphere_view.SetColor(0.0,1.0,1.0)
    # mapper
    mapper = vtk.vtkPolyDataMapper()
    if vtk.VTK_MAJOR_VERSION <= 5:
        mapper.SetInput(sphere_view.GetOutput())
    else:
        mapper.SetInputConnection(sphere_view.GetOutputPort())

    # actor
    sphere_actor = vtk.vtkActor()
    sphere_actor.SetMapper(mapper)
    sphere_actor.GetProperty().SetColor(1.0, 0.0, 1.0)

    ren = vtk.vtkRenderer()
    ren.AddActor(sphere_actor)
    # ren.AddActor(vol2_actor)
    ren.AddViewProp(volume)
    ren.AddViewProp(volume2)
    ren.AddViewProp(volume3)
    ren.SetBackground(0, 0, 0)
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren)
    renWin.SetSize(400, 400)

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

    iren.Initialize()
    renWin.Render()
    iren.Start()
Exemplo n.º 41
0
def main():
    colors = vtk.vtkNamedColors()

    colors.SetColor("BkgColor", [51, 77, 102, 255])

    # 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.
    ren = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    # 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
    # uses 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.vtkPNGReader()
    reader.SetFileDimensionality(2)  #存储在文件中的维数
    reader.SetFilePrefix(
        "E:\PYproject\BrainConnect/allen_data/img512/s")  #指定图像文件的前缀
    #reader.SetFileNameSliceSpacing()#当读取具有常规但非连续切片的文件(例如filename.1,filename.3,filename.5)时,可以指定间距以跳过丢失的文件(默认值= 1)
    reader.SetFilePattern(
        "%s%d.png")  #配合SetFilePrefix使用,用于从FilePrefix和切片编号构建文件名的snprintf样式格式字符串
    reader.SetDataExtent(0, 511, 0, 511, 0,
                         131)  #设置disk数据范围,前两个为img大小,最后一个为slice数量
    reader.SetDataSpacing(1, 1, 4)  #设置文件中数据的间距

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

    # 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(0, 0.0, 0.0, 0.0)
    volumeColor.AddRGBPoint(500, 0.0, 139.0, 139.0)
    volumeColor.AddRGBPoint(1000, 255.0, 215.5, 0.3)
    volumeColor.AddRGBPoint(1150, 139.0, 105.0, 105.9)

    # The opacity transfer function is used to control the opacity
    # of different tissue types.
    volumeScalarOpacity = vtk.vtkPiecewiseFunction()
    volumeScalarOpacity.AddPoint(0, 0.00)
    volumeScalarOpacity.AddPoint(500, 0.15)
    volumeScalarOpacity.AddPoint(1000, 0.15)
    volumeScalarOpacity.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.
    volumeGradientOpacity = vtk.vtkPiecewiseFunction()
    volumeGradientOpacity.AddPoint(0, 0.0)
    volumeGradientOpacity.AddPoint(90, 0.5)
    volumeGradientOpacity.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(volumeColor)
    volumeProperty.SetScalarOpacity(volumeScalarOpacity)
    volumeProperty.SetGradientOpacity(volumeGradientOpacity)
    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(volumeMapper)
    volume.SetProperty(volumeProperty)

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

    # 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 = ren.GetActiveCamera()
    c = volume.GetCenter()
    camera.SetViewUp(0, 0, -1)
    camera.SetPosition(c[0], c[1] - 400, c[2])
    camera.SetFocalPoint(c[0], c[1], c[2])
    camera.Azimuth(30.0)
    camera.Elevation(30.0)

    # Set a background color for the renderer
    ren.SetBackground(colors.GetColor3d("BkgColor"))

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

    # Interact with the data.
    iren.Start()
Exemplo n.º 42
0
 def update(self):
     # only unsigned char or unsigned short can be accepted by vtkVolumeRayCastMapper, so convert signed short to unsigned short
     val_range = self._image.GetOutput().GetScalarRange()
     min_val = val_range[0]
     max_val = val_range[1]
     diff = max_val - min_val
     slope = 65536/diff # 16 bits/pixel
     inter = -slope*min_val
     shift = inter/slope
     
     shifter = vtk.vtkImageShiftScale()
     shifter.SetShift(shift)
     shifter.SetScale(slope)
     shifter.SetOutputScalarTypeToUnsignedShort()
     shifter.SetInputConnection(self._image.GetOutputPort())
     shifter.ReleaseDataFlagOff()
     shifter.Update()
     
     volume_mapper = vtk.vtkFixedPointVolumeRayCastMapper()
     volume_mapper.SetInputConnection(shifter.GetOutputPort())
     
     volume_color = vtk.vtkColorTransferFunction()
     
     volume_scalar_opacity = vtk.vtkPiecewiseFunction()
     
     volume_property = vtk.vtkVolumeProperty()
     volume_property.SetIndependentComponents(True)
     volume_property.SetColor(volume_color)
     volume_property.SetScalarOpacity(volume_scalar_opacity)
     volume_property.SetInterpolationTypeToLinear()
     
     volume = vtk.vtkVolume()
     volume.SetMapper(volume_mapper)
     volume.SetProperty(volume_property)
     
     volume_color.AddRGBSegment(0.0,0.0,0.0,0.0,1000,1.0,1.0,1.0)
     volume_scalar_opacity.AddSegment(0, 0, 65536, 1) # 16 bits/pixel
     volume_mapper.SetBlendModeToMaximumIntensity()
     
     camera = vtk.vtkCamera()
     camera.SetViewUp(0.0, 0.0, -1.0)
     camera.SetPosition(0.0, 1.0, 0.0)
     camera.SetFocalPoint(0.0, 0.0, 0.0)
     camera.ComputeViewPlaneNormal()
     camera.Dolly(1.5)
     
     renderer = vtk.vtkRenderer()
     renderer.AddViewProp(volume)
     renderer.SetActiveCamera(camera)
     renderer.ResetCamera()
     renderer.SetBackground(0.0,0.0,0.0)
     renderer.ResetCameraClippingRange()
     
     render_window = vtk.vtkRenderWindow()
     render_window.AddRenderer(renderer)
     
     render_window_interactor = vtk.vtkRenderWindowInteractor()
     render_window_interactor.SetRenderWindow(render_window)
     render_window_interactor.Initialize()
     render_window.Render()
     render_window_interactor.Start()
    def __init__(self, ren, renWin, iren):
        self.ren = ren
        self.renWin = renWin
        self.iren = iren

        # Create a gaussian
        gs = vtk.vtkImageGaussianSource()
        gs.SetWholeExtent(0, 30, 0, 30, 0, 30)
        gs.SetMaximum(255.0)
        gs.SetStandardDeviation(5)
        gs.SetCenter(15, 15, 15)

        # threshold to leave a gap that should show up for
        # gradient opacity
        t = vtk.vtkImageThreshold()
        t.SetInputConnection(gs.GetOutputPort())
        t.ReplaceInOn()
        t.SetInValue(0)
        t.ThresholdBetween(150, 200)

        # Use a shift scale to convert to unsigned char
        ss = vtk.vtkImageShiftScale()
        ss.SetInputConnection(t.GetOutputPort())
        ss.SetOutputScalarTypeToUnsignedChar()

        # grid will be used for two component dependent
        grid0 = vtk.vtkImageGridSource()
        grid0.SetDataScalarTypeToUnsignedChar()
        grid0.SetGridSpacing(10, 10, 10)
        grid0.SetLineValue(200)
        grid0.SetFillValue(10)
        grid0.SetDataExtent(0, 30, 0, 30, 0, 30)

        # use dilation to thicken the grid
        d = vtk.vtkImageContinuousDilate3D()
        d.SetInputConnection(grid0.GetOutputPort())
        d.SetKernelSize(3, 3, 3)

        # Now make a two component dependent
        iac = vtk.vtkImageAppendComponents()
        iac.AddInputConnection(d.GetOutputPort())
        iac.AddInputConnection(ss.GetOutputPort())

        # Some more gaussians for the four component indepent case
        gs1 = vtk.vtkImageGaussianSource()
        gs1.SetWholeExtent(0, 30, 0, 30, 0, 30)
        gs1.SetMaximum(255.0)
        gs1.SetStandardDeviation(4)
        gs1.SetCenter(5, 5, 5)

        t1 = vtk.vtkImageThreshold()
        t1.SetInputConnection(gs1.GetOutputPort())
        t1.ReplaceInOn()
        t1.SetInValue(0)
        t1.ThresholdBetween(150, 256)

        gs2 = vtk.vtkImageGaussianSource()
        gs2.SetWholeExtent(0, 30, 0, 30, 0, 30)
        gs2.SetMaximum(255.0)
        gs2.SetStandardDeviation(4)
        gs2.SetCenter(12, 12, 12)

        gs3 = vtk.vtkImageGaussianSource()
        gs3.SetWholeExtent(0, 30, 0, 30, 0, 30)
        gs3.SetMaximum(255.0)
        gs3.SetStandardDeviation(4)
        gs3.SetCenter(19, 19, 19)

        t3 = vtk.vtkImageThreshold()
        t3.SetInputConnection(gs3.GetOutputPort())
        t3.ReplaceInOn()
        t3.SetInValue(0)
        t3.ThresholdBetween(150, 256)

        gs4 = vtk.vtkImageGaussianSource()
        gs4.SetWholeExtent(0, 30, 0, 30, 0, 30)
        gs4.SetMaximum(255.0)
        gs4.SetStandardDeviation(4)
        gs4.SetCenter(26, 26, 26)

        # we need a few append filters ...
        iac1 = vtk.vtkImageAppendComponents()
        iac1.AddInputConnection(t1.GetOutputPort())
        iac1.AddInputConnection(gs2.GetOutputPort())

        iac2 = vtk.vtkImageAppendComponents()
        iac2.AddInputConnection(iac1.GetOutputPort())
        iac2.AddInputConnection(t3.GetOutputPort())

        iac3 = vtk.vtkImageAppendComponents()
        iac3.AddInputConnection(iac2.GetOutputPort())
        iac3.AddInputConnection(gs4.GetOutputPort())

        # create the four component dependent -
        # use lines in x, y, z for colors
        gridR = vtk.vtkImageGridSource()
        gridR.SetDataScalarTypeToUnsignedChar()
        gridR.SetGridSpacing(10, 100, 100)
        gridR.SetLineValue(250)
        gridR.SetFillValue(100)
        gridR.SetDataExtent(0, 30, 0, 30, 0, 30)

        dR = vtk.vtkImageContinuousDilate3D()
        dR.SetInputConnection(gridR.GetOutputPort())
        dR.SetKernelSize(2, 2, 2)

        gridG = vtk.vtkImageGridSource()
        gridG.SetDataScalarTypeToUnsignedChar()
        gridG.SetGridSpacing(100, 10, 100)
        gridG.SetLineValue(250)
        gridG.SetFillValue(100)
        gridG.SetDataExtent(0, 30, 0, 30, 0, 30)

        dG = vtk.vtkImageContinuousDilate3D()
        dG.SetInputConnection(gridG.GetOutputPort())
        dG.SetKernelSize(2, 2, 2)

        gridB = vtk.vtkImageGridSource()
        gridB.SetDataScalarTypeToUnsignedChar()
        gridB.SetGridSpacing(100, 100, 10)
        gridB.SetLineValue(0)
        gridB.SetFillValue(250)
        gridB.SetDataExtent(0, 30, 0, 30, 0, 30)

        dB = vtk.vtkImageContinuousDilate3D()
        dB.SetInputConnection(gridB.GetOutputPort())
        dB.SetKernelSize(2, 2, 2)

        # need some appending
        iacRG = vtk.vtkImageAppendComponents()
        iacRG.AddInputConnection(dR.GetOutputPort())
        iacRG.AddInputConnection(dG.GetOutputPort())

        iacRGB = vtk.vtkImageAppendComponents()
        iacRGB.AddInputConnection(iacRG.GetOutputPort())
        iacRGB.AddInputConnection(dB.GetOutputPort())

        iacRGBA = vtk.vtkImageAppendComponents()
        iacRGBA.AddInputConnection(iacRGB.GetOutputPort())
        iacRGBA.AddInputConnection(ss.GetOutputPort())

        # We need a bunch of opacity functions

        # this one is a simple ramp to .2
        rampPoint2 = vtk.vtkPiecewiseFunction()
        rampPoint2.AddPoint(0, 0.0)
        rampPoint2.AddPoint(255, 0.2)

        # this one is a simple ramp to 1
        ramp1 = vtk.vtkPiecewiseFunction()
        ramp1.AddPoint(0, 0.0)
        ramp1.AddPoint(255, 1.0)

        # this one shows a sharp surface
        surface = vtk.vtkPiecewiseFunction()
        surface.AddPoint(0, 0.0)
        surface.AddPoint(10, 0.0)
        surface.AddPoint(50, 1.0)
        surface.AddPoint(255, 1.0)

        # this one is constant 1
        constant1 = vtk.vtkPiecewiseFunction()
        constant1.AddPoint(0, 1.0)
        constant1.AddPoint(255, 1.0)

        # this one is used for gradient opacity
        gop = vtk.vtkPiecewiseFunction()
        gop.AddPoint(0, 0.0)
        gop.AddPoint(20, 0.0)
        gop.AddPoint(60, 1.0)
        gop.AddPoint(255, 1.0)

        # We need a bunch of color functions

        # This one is a simple rainbow
        rainbow = vtk.vtkColorTransferFunction()
        rainbow.SetColorSpaceToHSV()
        rainbow.HSVWrapOff()
        rainbow.AddHSVPoint(0, 0.1, 1.0, 1.0)
        rainbow.AddHSVPoint(255, 0.9, 1.0, 1.0)

        # this is constant red
        red = vtk.vtkColorTransferFunction()
        red.AddRGBPoint(0, 1, 0, 0)
        red.AddRGBPoint(255, 1, 0, 0)

        # this is constant green
        green = vtk.vtkColorTransferFunction()
        green.AddRGBPoint(0, 0, 1, 0)
        green.AddRGBPoint(255, 0, 1, 0)

        # this is constant blue
        blue = vtk.vtkColorTransferFunction()
        blue.AddRGBPoint(0, 0, 0, 1)
        blue.AddRGBPoint(255, 0, 0, 1)

        # this is constant yellow
        yellow = vtk.vtkColorTransferFunction()
        yellow.AddRGBPoint(0, 1, 1, 0)
        yellow.AddRGBPoint(255, 1, 1, 0)

        #ren = vtk.vtkRenderer()
        #renWin = vtk.vtkRenderWindow()
        self.renWin.AddRenderer(self.ren)
        self.renWin.SetSize(500, 500)
        #iren = vtk.vtkRenderWindowInteractor()
        self.iren.SetRenderWindow(self.renWin)

        self.ren.GetCullers().InitTraversal()
        culler = self.ren.GetCullers().GetNextItem()
        culler.SetSortingStyleToBackToFront()

        # We need 25 mapper / actor pairs which we will render
        # in a grid. Going down we will vary the input data
        # with the top row unsigned char, then float, then
        # two dependent components, then four dependent components
        # then four independent components. Going across we
        # will vary the rendering method with MIP, Composite,
        # Composite Shade, Composite GO, and Composite GO Shade.

        # Create the 5 by 5 grids
        self.volumeProperty = [[0 for col in range(0, 5)]
                               for row in range(0, 5)]
        self.volumeMapper = [[0 for col in range(0, 5)] for row in range(0, 5)]
        volume = [[0 for col in range(0, 5)] for row in range(0, 5)]

        for i in range(0, 5):
            for j in range(0, 5):

                self.volumeProperty[i][j] = vtk.vtkVolumeProperty()
                self.volumeMapper[i][j] = vtk.vtkFixedPointVolumeRayCastMapper(
                )
                self.volumeMapper[i][j].SetSampleDistance(0.25)
                self.volumeMapper[i][j].SetNumberOfThreads(1)

                volume[i][j] = vtk.vtkVolume()
                volume[i][j].SetMapper(self.volumeMapper[i][j])
                volume[i][j].SetProperty(self.volumeProperty[i][j])

                volume[i][j].AddPosition(i * 30, j * 30, 0)

                self.ren.AddVolume(volume[i][j])

        for i in range(0, 5):

            self.volumeMapper[0][i].SetInputConnection(t.GetOutputPort())
            self.volumeMapper[1][i].SetInputConnection(ss.GetOutputPort())
            self.volumeMapper[2][i].SetInputConnection(iac.GetOutputPort())
            self.volumeMapper[3][i].SetInputConnection(iac3.GetOutputPort())
            self.volumeMapper[4][i].SetInputConnection(iacRGBA.GetOutputPort())

            self.volumeMapper[i][0].SetBlendModeToMaximumIntensity()
            self.volumeMapper[i][1].SetBlendModeToComposite()
            self.volumeMapper[i][2].SetBlendModeToComposite()
            self.volumeMapper[i][3].SetBlendModeToComposite()
            self.volumeMapper[i][4].SetBlendModeToComposite()

            self.volumeProperty[0][i].IndependentComponentsOn()
            self.volumeProperty[1][i].IndependentComponentsOn()
            self.volumeProperty[2][i].IndependentComponentsOff()
            self.volumeProperty[3][i].IndependentComponentsOn()
            self.volumeProperty[4][i].IndependentComponentsOff()

            self.volumeProperty[0][i].SetColor(rainbow)
            self.volumeProperty[0][i].SetScalarOpacity(rampPoint2)
            self.volumeProperty[0][i].SetGradientOpacity(constant1)

            self.volumeProperty[1][i].SetColor(rainbow)
            self.volumeProperty[1][i].SetScalarOpacity(rampPoint2)
            self.volumeProperty[1][i].SetGradientOpacity(constant1)

            self.volumeProperty[2][i].SetColor(rainbow)
            self.volumeProperty[2][i].SetScalarOpacity(rampPoint2)
            self.volumeProperty[2][i].SetGradientOpacity(constant1)

            self.volumeProperty[3][i].SetColor(0, red)
            self.volumeProperty[3][i].SetColor(1, green)
            self.volumeProperty[3][i].SetColor(2, blue)
            self.volumeProperty[3][i].SetColor(3, yellow)
            self.volumeProperty[3][i].SetScalarOpacity(0, rampPoint2)
            self.volumeProperty[3][i].SetScalarOpacity(1, rampPoint2)
            self.volumeProperty[3][i].SetScalarOpacity(2, rampPoint2)
            self.volumeProperty[3][i].SetScalarOpacity(3, rampPoint2)
            self.volumeProperty[3][i].SetGradientOpacity(0, constant1)
            self.volumeProperty[3][i].SetGradientOpacity(1, constant1)
            self.volumeProperty[3][i].SetGradientOpacity(2, constant1)
            self.volumeProperty[3][i].SetGradientOpacity(3, constant1)
            self.volumeProperty[3][i].SetComponentWeight(0, 1)
            self.volumeProperty[3][i].SetComponentWeight(1, 1)
            self.volumeProperty[3][i].SetComponentWeight(2, 1)
            self.volumeProperty[3][i].SetComponentWeight(3, 1)

            self.volumeProperty[4][i].SetColor(rainbow)
            self.volumeProperty[4][i].SetScalarOpacity(rampPoint2)
            self.volumeProperty[4][i].SetGradientOpacity(constant1)

            self.volumeProperty[i][2].ShadeOn()
            self.volumeProperty[i][4].ShadeOn(0)
            self.volumeProperty[i][4].ShadeOn(1)
            self.volumeProperty[i][4].ShadeOn(2)
            self.volumeProperty[i][4].ShadeOn(3)

        self.volumeProperty[0][0].SetScalarOpacity(ramp1)
        self.volumeProperty[1][0].SetScalarOpacity(ramp1)
        self.volumeProperty[2][0].SetScalarOpacity(ramp1)
        self.volumeProperty[3][0].SetScalarOpacity(0, surface)
        self.volumeProperty[3][0].SetScalarOpacity(1, surface)
        self.volumeProperty[3][0].SetScalarOpacity(2, surface)
        self.volumeProperty[3][0].SetScalarOpacity(3, surface)
        self.volumeProperty[4][0].SetScalarOpacity(ramp1)

        self.volumeProperty[0][2].SetScalarOpacity(surface)
        self.volumeProperty[1][2].SetScalarOpacity(surface)
        self.volumeProperty[2][2].SetScalarOpacity(surface)
        self.volumeProperty[3][2].SetScalarOpacity(0, surface)
        self.volumeProperty[3][2].SetScalarOpacity(1, surface)
        self.volumeProperty[3][2].SetScalarOpacity(2, surface)
        self.volumeProperty[3][2].SetScalarOpacity(3, surface)
        self.volumeProperty[4][2].SetScalarOpacity(surface)

        self.volumeProperty[0][4].SetScalarOpacity(surface)
        self.volumeProperty[1][4].SetScalarOpacity(surface)
        self.volumeProperty[2][4].SetScalarOpacity(surface)
        self.volumeProperty[3][4].SetScalarOpacity(0, surface)
        self.volumeProperty[3][4].SetScalarOpacity(1, surface)
        self.volumeProperty[3][4].SetScalarOpacity(2, surface)
        self.volumeProperty[3][4].SetScalarOpacity(3, surface)
        self.volumeProperty[4][4].SetScalarOpacity(surface)

        self.volumeProperty[0][3].SetGradientOpacity(gop)
        self.volumeProperty[1][3].SetGradientOpacity(gop)
        self.volumeProperty[2][3].SetGradientOpacity(gop)
        self.volumeProperty[3][3].SetGradientOpacity(0, gop)
        self.volumeProperty[3][3].SetGradientOpacity(2, gop)
        self.volumeProperty[4][3].SetGradientOpacity(gop)

        self.volumeProperty[3][3].SetScalarOpacity(0, ramp1)
        self.volumeProperty[3][3].SetScalarOpacity(2, ramp1)

        self.volumeProperty[0][4].SetGradientOpacity(gop)
        self.volumeProperty[1][4].SetGradientOpacity(gop)
        self.volumeProperty[2][4].SetGradientOpacity(gop)
        self.volumeProperty[3][4].SetGradientOpacity(0, gop)
        self.volumeProperty[3][4].SetGradientOpacity(2, gop)
        self.volumeProperty[4][4].SetGradientOpacity(gop)

        self.renWin.Render()

        self.ren.GetActiveCamera().Dolly(1.3)
        self.ren.GetActiveCamera().Azimuth(15)
        self.ren.GetActiveCamera().Elevation(5)
        self.ren.ResetCameraClippingRange()
Exemplo n.º 44
0
    def create_volume(self):
        if self._actor is None:
            if int(ses.Session().rendering) == 0:
                self._volume_mapper = vtk.vtkFixedPointVolumeRayCastMapper()
                #volume_mapper.AutoAdjustSampleDistancesOff()
                self._volume_mapper.IntermixIntersectingGeometryOn()
                pix_diag = 2.0
                self._volume_mapper.SetImageSampleDistance(0.25)
                self._volume_mapper.SetSampleDistance(pix_diag / 5.0)
            else:
                self._volume_mapper = vtk.vtkGPUVolumeRayCastMapper()
                self._volume_mapper.UseJitteringOn()

                if LooseVersion(vtk.vtkVersion().GetVTKVersion()
                                ) > LooseVersion('8.0'):
                    self._volume_mapper.SetBlendModeToIsoSurface()

            #  else:
            #  isosurfaceFunc = vtk.vtkVolumeRayCastIsosurfaceFunction()
            #  isosurfaceFunc.SetIsoValue(127)

            #  self._volume_mapper = vtk.vtkVolumeRayCastMapper()
            #  self._volume_mapper.SetVolumeRayCastFunction(isosurfaceFunc)

            self._flip = vtk.vtkImageFlip()
            self._flip.SetInputData(self.mask.imagedata)
            self._flip.SetFilteredAxis(1)
            self._flip.FlipAboutOriginOn()

            self._volume_mapper.SetInputConnection(self._flip.GetOutputPort())
            self._volume_mapper.Update()

            r, g, b = self.colour

            self._color_transfer = vtk.vtkColorTransferFunction()
            self._color_transfer.RemoveAllPoints()
            self._color_transfer.AddRGBPoint(0.0, 0, 0, 0)
            self._color_transfer.AddRGBPoint(254.0, r, g, b)
            self._color_transfer.AddRGBPoint(255.0, r, g, b)

            self._piecewise_function = vtk.vtkPiecewiseFunction()
            self._piecewise_function.RemoveAllPoints()
            self._piecewise_function.AddPoint(0.0, 0.0)
            self._piecewise_function.AddPoint(127, 1.0)

            self._volume_property = vtk.vtkVolumeProperty()
            self._volume_property.SetColor(self._color_transfer)
            self._volume_property.SetScalarOpacity(self._piecewise_function)
            self._volume_property.ShadeOn()
            self._volume_property.SetInterpolationTypeToLinear()
            self._volume_property.SetSpecular(0.75)
            self._volume_property.SetSpecularPower(2)

            if not self._volume_mapper.IsA("vtkGPUVolumeRayCastMapper"):
                self._volume_property.SetScalarOpacityUnitDistance(pix_diag)
            else:
                if LooseVersion(vtk.vtkVersion().GetVTKVersion()
                                ) > LooseVersion('8.0'):
                    self._volume_property.GetIsoSurfaceValues().SetValue(
                        0, 127)

            self._actor = vtk.vtkVolume()
            self._actor.SetMapper(self._volume_mapper)
            self._actor.SetProperty(self._volume_property)
            self._actor.Update()
Exemplo n.º 45
0
    def _render_blurry_particles(self, particles_dataset):
        particles_per_species = dict((k, vtk.vtkPoints()) for k in self._species_idmap.iterkeys())

        scaling = self.settings.scaling

        position_idx = particles_dataset.dtype.names.index('position')
        species_id_idx = particles_dataset.dtype.names.index('species_id')
        for p in particles_dataset:
            pos = p[position_idx]
            display_species_id = self._species_idmap.get(p[species_id_idx])
            if display_species_id is None:
                continue
            particles_per_species[display_species_id].InsertNextPoint(
                pos * scaling / self._world_size)

        nx = ny = nz = self.settings.fluorimetry_axial_voxel_number

        for display_species_id, points in particles_per_species.iteritems():
            poly_data = vtk.vtkPolyData()
            poly_data.SetPoints(points)
            poly_data.ComputeBounds()

            pattr = self._pattrs[display_species_id]
            # Calc standard deviation of gauss distribution function
            wave_length = pattr['fluorimetry_wave_length']
            sigma = scaling * 0.5 * wave_length / self._world_size

            # Create guassian splatter
            gs = vtk.vtkGaussianSplatter()
            gs.SetInput(poly_data)
            gs.SetSampleDimensions(nx, ny, nz)
            gs.SetRadius(sigma)
            gs.SetExponentFactor(-.5)
            gs.ScalarWarpingOff()
            gs.SetModelBounds([-sigma, scaling + sigma] * 3)
            gs.SetAccumulationModeToMax()

            # Create filter for volume rendering
            filter = vtk.vtkImageShiftScale()
            # Scales to unsigned char
            filter.SetScale(255. * pattr['fluorimetry_brightness'])
            filter.ClampOverflowOn()
            filter.SetOutputScalarTypeToUnsignedChar()
            filter.SetInputConnection(gs.GetOutputPort())

            mapper = vtk.vtkFixedPointVolumeRayCastMapper()
            mapper.SetInputConnection(filter.GetOutputPort())

            volume = vtk.vtkVolume()
            property = volume.GetProperty() # vtk.vtkVolumeProperty()
            color = pattr['fluorimetry_luminescence_color']
            color_tfunc = vtk.vtkColorTransferFunction()
            color_tfunc.AddRGBPoint(0, color[0], color[1], color[2])
            property.SetColor(color_tfunc)
            opacity_tfunc = vtk.vtkPiecewiseFunction()
            opacity_tfunc.AddPoint(0, 0.0)
            opacity_tfunc.AddPoint(255., 1.0)
            property.SetScalarOpacity(opacity_tfunc)
            property.SetInterpolationTypeToLinear()

            if self.settings.fluorimetry_shadow_display:
                property.ShadeOn()
            else:
                property.ShadeOff()

            volume.SetMapper(mapper)

            self.renderer.AddVolume(volume)
Exemplo n.º 46
0
    def addVol(self, data, header=None):
        pix_diag = 5.0 / 10.0

        img = vtkImageImportFromArray()
        img.SetArray(data)
        img.ConvertIntToUnsignedShortOn()
        """
		Origin and Data spacing setting are essential for a normalized volume rendering of
		the DWI image volumes
		------- dawdling for a long time for addressing the problem that the volume is too thin
		and even resorted to pre-resampling of the DWI volumes
		"""
        # img.GetImport().SetDataSpacing(0.9375, 0.9375, 4.5200)
        img.GetImport().SetDataSpacing(header["pixdim"][1:4])
        # img.GetImport().SetDataOrigin(128.0, 128.0, 68.50)
        img.GetImport().SetDataOrigin(
            header["dim"][0] * header["pixdim"][0],
            header["dim"][1] * header["pixdim"][1],
            header["dim"][2] * header["pixdim"][2],
        )
        print img.GetDataExtent()

        volMapper = vtk.vtkFixedPointVolumeRayCastMapper()
        # compositeFunction = vtk.vtkFixedPointVolumeRayCastCompositeHelper()
        # compositeFunction.SetCompositeMethodToInterpolateFirst()
        # compositeFunction.SetCompositeMethodToClassifyFirst()
        # volMapper.SetVolumeRayCastFunction(compositeFunction)

        volMapper.SetSampleDistance(pix_diag / 5.0)
        volMapper.SetImageSampleDistance(1.0)
        volMapper.SetInputConnection(img.GetOutputPort())

        # The property describes how the data will look
        self.volProperty = volProperty = vtk.vtkVolumeProperty()
        volProperty.SetColor(self.color_tf)
        volProperty.SetScalarOpacity(self.opacity_tf)
        volProperty.SetGradientOpacity(self.opacity_tf)
        if self.parent.lighting:
            volProperty.ShadeOn()
            # volProperty.SetInterpolationTypeToLinear()
        volProperty.SetInterpolationTypeToNearest()
        volProperty.SetScalarOpacityUnitDistance(pix_diag / 5.0)

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

        self.ren.AddVolume(vol)

        boxWidget = vtk.vtkBoxWidget()
        boxWidget.SetInteractor(self.parent.m_ui.renderView)
        boxWidget.SetPlaceFactor(1.0)

        planes = vtk.vtkPlanes()

        def ClipVolumeRender(obj, event):
            obj.GetPlanes(planes)
            volMapper.SetClippingPlanes(planes)

        boxWidget.SetInput(img.GetOutput())
        boxWidget.PlaceWidget(img.GetOutput().GetBounds())
        boxWidget.InsideOutOn()
        boxWidget.AddObserver("InteractionEvent", ClipVolumeRender)

        outlineProperty = boxWidget.GetOutlineProperty()
        outlineProperty.SetRepresentationToWireframe()
        outlineProperty.SetAmbient(1.0)
        outlineProperty.SetAmbientColor(1, 1, 1)
        outlineProperty.SetLineWidth(3)

        selectedOutlineProperty = boxWidget.GetSelectedOutlineProperty()
        selectedOutlineProperty.SetRepresentationToWireframe()
        selectedOutlineProperty.SetAmbient(1.0)
        selectedOutlineProperty.SetAmbientColor(1, 0, 0)
        selectedOutlineProperty.SetLineWidth(1)

        outline = vtk.vtkOutlineFilter()
        outline.SetInputConnection(img.GetOutputPort())
        outlineMapper = vtk.vtkPolyDataMapper()
        outlineMapper.SetInputConnection(outline.GetOutputPort())
        outlineActor = vtk.vtkActor()
        outlineActor.SetMapper(outlineMapper)

        self.ren.AddActor(outlineActor)
        self.volnum += 1
Exemplo n.º 47
0
    def __init__(self,imagetype,prefix,extent):

        if imagetype == "jpg":
            reader = vtk.vtkJPEGReader()
        elif imagetype == "pnm":
            reader = vtk.vtkPNMReader()
        elif imagetype == "tif":
            reader = vtk.vtkTIFFReader()
        # todo: add more image types
        else:
            print "unknown type!"
            sys.exit()

        reader.SetDataExtent(extent)
        #reader.SetFilePrefix(prefix)
        reader.SetFilePattern(prefix)
        reader.SetDataSpacing(1,1,1)
        imageoriginal = reader.GetOutput()

        # pad the image with extra voxels because of vtk off by 1
        # annoyance in calculating image bounds
#         extentcopy = extent[:]
#         for i in xrange(1,7,2):
#             extentcopy[i] += 1
#         padder = vtk.vtkImageConstantPad()
#         padder.SetInput(imageoriginal)
#         padder.SetOutputWholeExtent(extentcopy) 
#         padder.SetConstant(255) # arbitrary
#         self.image = padder.GetOutput()
#         self.image.Update()
        self.image = imageoriginal
        self.image.Update()

        # must use this particular mapper so color images work, also
        # handles off by 1 annoyance in a slightly better way.
        mapper = vtk.vtkFixedPointVolumeRayCastMapper()
        mapper.IntermixIntersectingGeometryOn()
        min_extent = min(extent[1:6:2])
        # todo: can use a built in function for this
        # for very small images we need to reset the sample distance
        if min_extent < 50:
            mapper.SetSampleDistance(float(min_extent)/100)
            mapper.SetInteractiveSampleDistance(float(min_extent)/50)
        mapper.SetInput(self.image)

        volproperty = vtk.vtkVolumeProperty()
        volproperty.IndependentComponentsOff()

        # we initially set the opacity to a constant value of 1, but
        # we need the function so we can change it later
        self.opacity = vtk.vtkPiecewiseFunction()
        self.opacity.AddSegment(0,1,255,1)

        # the type of color function we use depends on how many
        # components the image has, 3 for a color image, 1 for a black
        # and white image
        num_components = self.image.GetNumberOfScalarComponents()
        
        if num_components == 1:
            color = vtk.vtkPiecewiseFunction()
            color.AddSegment(0,0,255,1)
            volproperty.SetColor(color)
            volproperty.SetScalarOpacity(self.opacity)
        elif num_components == 4:
##             red = vtk.vtkColorTransferFunction()
##             red.AddRGBSegment(0,0,0,0,255,1,0,0)
##             green = vtk.vtkColorTransferFunction()
##             green.AddRGBSegment(0,0,0,0,255,0,1,0)
##             blue = vtk.vtkColorTransferFunction()
##             blue.AddRGBSegment(0,0,0,0,255,0,0,1)
##             volproperty.SetColor(0,red)
##             volproperty.SetColor(1,green)
##             volproperty.SetColor(2,blue)
            volproperty.SetScalarOpacity(self.opacity)
##             volproperty.SetScalarOpacity(1,self.opacity)
##             volproperty.SetScalarOpacity(2,self.opacity)
        else:
            pass
        print num_components

        volume = vtk.vtkVolume()
        volume.SetMapper(mapper)
        volume.SetProperty(volproperty)

        self.ren = vtk.vtkRenderer()
        self.ren.AddActor(volume)
        # on mac, this shows only the cone
        #self.DrawCone()
        #print self.ren.VisibleActorCount()
        #print self.ren.VisibleVolumeCount()
        self.ren.ResetCamera()