Пример #1
0
def volume(vol,voxsz=(1.0,1.0,1.0),affine=None,center_origin=1,info=1,maptype=0,trilinear=1,iso=0,iso_thr=100,opacitymap=None,colormap=None):    
    ''' Create a volume and return a volumetric actor using volumetric rendering. 
    This function has many different interesting capabilities. The maptype, opacitymap and colormap are the most crucial parameters here.
    
    Parameters:
    ----------------
    vol : array, shape (N, M, K), dtype uint8
         an array representing the volumetric dataset that we want to visualize using volumetric rendering            
        
    voxsz : sequence of 3 floats
            default (1., 1., 1.)
            
    affine : array, shape (4,4), default None
            as given by volumeimages             
            
    center_origin : int {0,1}, default 1
             it considers that the center of the volume is the 
            point (-vol.shape[0]/2.0+0.5,-vol.shape[1]/2.0+0.5,-vol.shape[2]/2.0+0.5)
            
    info : int {0,1}, default 1
            if 1 it prints out some info about the volume, the method and the dataset.
            
    trilinear: int {0,1}, default 1
            Use trilinear interpolation, default 1, gives smoother rendering. If you want faster interpolation use 0 (Nearest).
            
    maptype : int {0,1}, default 0,        
            The maptype is a very important parameter which affects the raycasting algorithm in use for the rendering. 
            The options are:
            If 0 then vtkVolumeTextureMapper2D is used.
            If 1 then vtkVolumeRayCastFunction is used.
            
    iso : int {0,1} default 0,
            If iso is 1 and maptype is 1 then  we use vtkVolumeRayCastIsosurfaceFunction which generates an isosurface at 
            the predefined iso_thr value. If iso is 0 and maptype is 1 vtkVolumeRayCastCompositeFunction is used.
            
    iso_thr : int, default 100,
            if iso is 1 then then this threshold in the volume defines the value which will be used to create the isosurface.
            
    opacitymap : array, shape (N,2), default None.
            The opacity map assigns a transparency coefficient to every point in the volume.
            The default value uses the histogram of the volume to calculate the opacitymap.
    colormap : array, shape (N,4), default None.
            The color map assigns a color value to every point in the volume.
            When None from the histogram it uses a red-blue colormap.
                
    Returns:
    ----------
    vtkVolume    
    
    Notes:
    --------
    What is the difference between TextureMapper2D and RayCastFunction? 
    Coming soon... See VTK user's guide [book] & The Visualization Toolkit [book] and VTK's online documentation & online docs.
    
    What is the difference between RayCastIsosurfaceFunction and RayCastCompositeFunction?
    Coming soon... See VTK user's guide [book] & The Visualization Toolkit [book] and VTK's online documentation & online docs.
    
    What about trilinear interpolation?
    Coming soon... well when time permits really ... :-)
    
    Examples:
    ------------
    First example random points    
    
    >>> from dipy.viz import fos
    >>> import numpy as np
    >>> vol=100*np.random.rand(100,100,100)
    >>> vol=vol.astype('uint8')
    >>> print vol.min(), vol.max()
    >>> r = fos.ren()
    >>> v = fos.volume(vol)
    >>> fos.add(r,v)
    >>> fos.show(r)
    
    Second example with a more complicated function
        
    >>> from dipy.viz import fos
    >>> import numpy as np
    >>> x, y, z = np.ogrid[-10:10:20j, -10:10:20j, -10:10:20j]
    >>> s = np.sin(x*y*z)/(x*y*z)
    >>> r = fos.ren()
    >>> v = fos.volume(s)
    >>> fos.add(r,v)
    >>> fos.show(r)
    
    If you find this function too complicated you can always use mayavi. 
    Please do not forget to use the -wthread switch in ipython if you are running mayavi.
    
    >>> from enthought.mayavi import mlab       
    >>> import numpy as np
    >>> x, y, z = np.ogrid[-10:10:20j, -10:10:20j, -10:10:20j]
    >>> s = np.sin(x*y*z)/(x*y*z)
    >>> mlab.pipeline.volume(mlab.pipeline.scalar_field(s))
    >>> mlab.show()
    
    More mayavi demos are available here:
    
    http://code.enthought.com/projects/mayavi/docs/development/html/mayavi/mlab.html
    
    '''
    if vol.ndim!=3:    
        raise ValueError('3d numpy arrays only please')
    
    if info :
        print('Datatype',vol.dtype,'converted to uint8' )
    
    vol=np.interp(vol,[vol.min(),vol.max()],[0,255])
    vol=vol.astype('uint8')

    if opacitymap==None:
        
        bin,res=np.histogram(vol.ravel())
        res2=np.interp(res,[vol.min(),vol.max()],[0,1])
        opacitymap=np.vstack((res,res2)).T
        opacitymap=opacitymap.astype('float32')
                
        '''
        opacitymap=np.array([[ 0.0, 0.0],
                          [50.0, 0.9]])
        ''' 

    if info:
        print 'opacitymap', opacitymap
        
    if colormap==None:

        bin,res=np.histogram(vol.ravel())
        res2=np.interp(res,[vol.min(),vol.max()],[0,1])
        zer=np.zeros(res2.shape)
        colormap=np.vstack((res,res2,zer,res2[::-1])).T
        colormap=colormap.astype('float32')

        '''
        colormap=np.array([[0.0, 0.5, 0.0, 0.0],
                                        [64.0, 1.0, 0.5, 0.5],
                                        [128.0, 0.9, 0.2, 0.3],
                                        [196.0, 0.81, 0.27, 0.1],
                                        [255.0, 0.5, 0.5, 0.5]])
        '''

    if info:
        print 'colormap', colormap                        
    
    im = vtk.vtkImageData()
    im.SetScalarTypeToUnsignedChar()
    im.SetDimensions(vol.shape[0],vol.shape[1],vol.shape[2])
    #im.SetOrigin(0,0,0)
    #im.SetSpacing(voxsz[2],voxsz[0],voxsz[1])
    im.AllocateScalars()        
    
    for i in range(vol.shape[0]):
        for j in range(vol.shape[1]):
            for k in range(vol.shape[2]):
                
                im.SetScalarComponentFromFloat(i,j,k,0,vol[i,j,k])
    
    if affine != None:

        aff = vtk.vtkMatrix4x4()
        aff.DeepCopy((affine[0,0],affine[0,1],affine[0,2],affine[0,3],affine[1,0],affine[1,1],affine[1,2],affine[1,3],affine[2,0],affine[2,1],affine[2,2],affine[2,3],affine[3,0],affine[3,1],affine[3,2],affine[3,3]))
        #aff.DeepCopy((affine[0,0],affine[0,1],affine[0,2],0,affine[1,0],affine[1,1],affine[1,2],0,affine[2,0],affine[2,1],affine[2,2],0,affine[3,0],affine[3,1],affine[3,2],1))
        #aff.DeepCopy((affine[0,0],affine[0,1],affine[0,2],127.5,affine[1,0],affine[1,1],affine[1,2],-127.5,affine[2,0],affine[2,1],affine[2,2],-127.5,affine[3,0],affine[3,1],affine[3,2],1))
        
        reslice = vtk.vtkImageReslice()
        reslice.SetInput(im)
        #reslice.SetOutputDimensionality(2)
        #reslice.SetOutputOrigin(127,-145,147)    
        
        reslice.SetResliceAxes(aff)
        #reslice.SetOutputOrigin(-127,-127,-127)    
        #reslice.SetOutputExtent(-127,128,-127,128,-127,128)
        #reslice.SetResliceAxesOrigin(0,0,0)
        #print 'Get Reslice Axes Origin ', reslice.GetResliceAxesOrigin()
        #reslice.SetOutputSpacing(1.0,1.0,1.0)
        
        reslice.SetInterpolationModeToLinear()    
        #reslice.UpdateWholeExtent()
        
        #print 'reslice GetOutputOrigin', reslice.GetOutputOrigin()
        #print 'reslice GetOutputExtent',reslice.GetOutputExtent()
        #print 'reslice GetOutputSpacing',reslice.GetOutputSpacing()
    
        changeFilter=vtk.vtkImageChangeInformation() 
        changeFilter.SetInput(reslice.GetOutput())
        #changeFilter.SetInput(im)
        if center_origin:
            changeFilter.SetOutputOrigin(-vol.shape[0]/2.0+0.5,-vol.shape[1]/2.0+0.5,-vol.shape[2]/2.0+0.5)
            print 'ChangeFilter ', changeFilter.GetOutputOrigin()
        
    opacity = vtk.vtkPiecewiseFunction()
    for i in range(opacitymap.shape[0]):
        opacity.AddPoint(opacitymap[i,0],opacitymap[i,1])

    color = vtk.vtkColorTransferFunction()
    for i in range(colormap.shape[0]):
        color.AddRGBPoint(colormap[i,0],colormap[i,1],colormap[i,2],colormap[i,3])
        
    if(maptype==0): 
    
        property = vtk.vtkVolumeProperty()
        property.SetColor(color)
        property.SetScalarOpacity(opacity)
        
        if trilinear:
            property.SetInterpolationTypeToLinear()
        else:
            prop.SetInterpolationTypeToNearest()
            
        if info:
            print('mapper VolumeTextureMapper2D')
        mapper = vtk.vtkVolumeTextureMapper2D()
        if affine == None:
            mapper.SetInput(im)
        else:
            #mapper.SetInput(reslice.GetOutput())
            mapper.SetInput(changeFilter.GetOutput())
        
    
    if (maptype==1):

        property = vtk.vtkVolumeProperty()
        property.SetColor(color)
        property.SetScalarOpacity(opacity)
        property.ShadeOn()
        if trilinear:
            property.SetInterpolationTypeToLinear()
        else:
            prop.SetInterpolationTypeToNearest()

        if iso:
            isofunc=vtk.vtkVolumeRayCastIsosurfaceFunction()
            isofunc.SetIsoValue(iso_thr)
        else:
            compositeFunction = vtk.vtkVolumeRayCastCompositeFunction()
        
        if info:
            print('mapper VolumeRayCastMapper')
            
        mapper = vtk.vtkVolumeRayCastMapper()
        if iso:
            mapper.SetVolumeRayCastFunction(isofunc)
            if info:
                print('Isosurface')
        else:
            mapper.SetVolumeRayCastFunction(compositeFunction)   
            
            #mapper.SetMinimumImageSampleDistance(0.2)
            if info:
                print('Composite')
             
        if affine == None:
            mapper.SetInput(im)
        else:
            #mapper.SetInput(reslice.GetOutput())    
            mapper.SetInput(changeFilter.GetOutput())
            #Return mid position in world space    
            #im2=reslice.GetOutput()
            #index=im2.FindPoint(vol.shape[0]/2.0,vol.shape[1]/2.0,vol.shape[2]/2.0)
            #print 'Image Getpoint ' , im2.GetPoint(index)
           
        
    volum = vtk.vtkVolume()
    volum.SetMapper(mapper)
    volum.SetProperty(property)

    if info :  
         
        print 'Origin',   volum.GetOrigin()
        print 'Orientation',   volum.GetOrientation()
        print 'OrientationW',    volum.GetOrientationWXYZ()
        print 'Position',    volum.GetPosition()
        print 'Center',    volum.GetCenter()  
        print 'Get XRange', volum.GetXRange()
        print 'Get YRange', volum.GetYRange()
        print 'Get ZRange', volum.GetZRange()  
        print 'Volume data type', vol.dtype
        
    return volum
Пример #2
0
    def WriteImageToDisk(self, filename):
        """Writes thumbnail to disk"""
        ren = vtk.vtkRenderer()
        renWin = vtk.vtkRenderWindow()
        renWin.AddRenderer(ren)
        ren.SetBackground(1.0, 1.0, 1.0)
        renWin.SetSize(200, 200)
        renWin.OffScreenRenderingOn()

        # determine image range
        self._image.Update()
        r = self._image.GetScalarRange()
        t = self._threshold

        # determine image spacing
        sp = self._image.GetSpacing()

        # cast image to unsigned char
        typ = self._image.GetScalarType()
        if ((typ != 3) or (typ != 5)):
            cast = vtk.vtkImageShiftScale()
            cast.SetInput(self._image)
            cast.SetOutputScalarTypeToUnsignedChar()
            cast.SetShift(-r[0])
            if r[1] == r[0]:
                cast.SetScale(255.0 / (r[1] - r[0] + 1))
                t = (self._threshold - r[0]) * (255.0 / (r[1] - r[0] + 1))
            else:
                cast.SetScale(255.0 / (r[1] - r[0]))
                t = (self._threshold - r[0]) * (255.0 / (r[1] - r[0]))
            r = [0, 255.0]
            o = cast.GetOutput()
        else:
            o = self._image.GetOutput()

        # build a LUT
        tfun = vtk.vtkPiecewiseFunction()
        tfun.AddPoint(r[0], 0.0)
        tfun.AddPoint(t - (r[1] - r[0]) / 1024., 0.0)
        tfun.AddPoint(t, 0.2)
        tfun.AddPoint(r[1], 0.2)
        ctfun = vtk.vtkColorTransferFunction()
        ctfun.AddRGBPoint(r[0], 1, 1, 1)
        ctfun.AddRGBPoint(r[1], 1, 1, 1)

        function = vtk.vtkVolumeRayCastIsosurfaceFunction()	         # tunable
        function.SetIsoValue(t)
        volumeMapper = vtk.vtkVolumeRayCastMapper()
        volumeMapper.SetInput(o)
        volumeMapper.SetVolumeRayCastFunction(function)
        volumeMapper.SetSampleDistance(max(sp) * 1.0)              # tunable
        volumeProperty = vtk.vtkVolumeProperty()
        volumeProperty.SetColor(ctfun)
        volumeProperty.SetScalarOpacity(tfun)
        volumeProperty.SetInterpolationTypeToLinear()            # tunable
        volumeProperty.ShadeOn()

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

        # Add volume to renderer
        ren.AddVolume(newvol)

        # set up inital camera
        camera = ren.GetActiveCamera()
        camera.Elevation(-60.0)
        camera.SetViewAngle(20)

        # grab image
        renWin.Render()
        windowToimage = vtk.vtkWindowToImageFilter()
        windowToimage.SetInput(renWin)

        # save image
        writer = vtk.vtkJPEGWriter()
        writer.SetInput(windowToimage.GetOutput())
        writer.SetFileName(filename)
        writer.SetQuality(85)
        writer.Write()
    def updateRendering(self):
        """
		Update the Rendering of this module
		"""
        method = self.parameters["Method"]
        self.setMethod(method)

        if self.volumeModule:
            self.volumeModule.function = vtk.vtkVolumeRayCastIsosurfaceFunction()
            self.volumeModule.function.SetIsoValue(self.parameters["IsoValue"])
            self.volumeModule.showTimepoint(self.timepoint)
            return

        if not self.init:
            self.init = 1
            self.mapper.ColorByArrayComponent(0, 0)
        self.mapper.AddObserver("ProgressEvent", lib.messenger.send)
        lib.messenger.connect(self.mapper, "ProgressEvent", self.updateProgress)
        dataUnit = self.getInputDataUnit(1)
        if not dataUnit:
            dataUnit = self.dataUnit
        dataCtf = dataUnit.getColorTransferFunction()
        if self.parameters["SolidColor"]:
            minval, maxval = dataCtf.GetRange()
            ctf = vtk.vtkColorTransferFunction()
            ctf.AddRGBPoint(int(minval), 0, 0, 0)
            r, g, b = dataCtf.GetColor(maxval)
            ctf.AddRGBPoint(int(minval) + 1, r, g, b)
            ctf.AddRGBPoint(maxval, r, g, b)
        else:
            ctf = dataCtf
        self.mapper.SetLookupTable(ctf)
        self.mapper.ScalarVisibilityOn()

        minVal, maxVal = self.data.GetScalarRange()
        self.setScalarRange(minVal, maxVal)

        self.mapper.SetScalarRange(minVal, maxVal)
        self.mapper.SetColorModeToMapScalars()

        opacity = self.parameters["Transparency"]
        opacity = (100 - opacity) / 100.0
        Logging.info("Using opacity ", opacity, kw="visualizer")
        if opacity != 1:
            cullers = self.parent.getRenderer().GetCullers()
            cullers.InitTraversal()
            culler = cullers.GetNextItem()
            culler.SetSortingStyleToBackToFront()
            # print cullers, culler
            # self.parent.getRenderer().GetRenderWindow().SetAlphaBitPlanes(1)
            # self.parent.getRenderer().GetRenderWindow().SetMultiSamples(0)
            # self.parent.getRenderer().SetUseDepthPeeling(1)
            # self.parent.getRenderer().SetMaximumNumberOfPeels(100)
            # self.parent.getRenderer().SetOcclusionRatio(1.0)
            # print self.parent.getRenderer().GetLastRenderingUsedDepthPeeling()

        self.actor.GetProperty().SetOpacity(opacity)

        polyinput = self.getPolyDataInput(1)
        if polyinput:
            Logging.info("Using polydata input", kw="visualizer")
            self.mapper.SetInput(polyinput)
            VisualizationModule.updateRendering(self, polyinput)
            self.parent.Render()
            return

        x, y, z = self.dataUnit.getDimensions()
        input = self.getInput(1)
        input = optimize.optimize(image=input, updateExtent=(0, x - 1, 0, y - 1, 0, z - 1))

        if self.parameters["Gaussian"]:
            Logging.info("Doing gaussian smoothing", kw="visualizer")
            if not self.smooth:
                self.smooth = vtk.vtkImageGaussianSmooth()
            self.smooth.SetInput(input)
            input = self.smooth.GetOutput()

        self.contour.SetInput(input)
        input = self.contour.GetOutput()

        multi = self.parameters["MultipleSurfaces"]

        if not multi:
            Logging.info("Using single isovalue=%d" % int(self.parameters["IsoValue"]), kw="visualizer")
            self.contour.SetValue(0, self.parameters["IsoValue"])
        else:
            begin = self.parameters["SurfaceRangeBegin"]
            end = self.parameters["SurfaceRangeEnd"]
            n = self.parameters["SurfaceAmnt"]
            Logging.info("Generating %d values in range %d-%d" % (n, begin, end), kw="visualizer")
            self.contour.GenerateValues(n, begin, end)
            n = self.contour.GetNumberOfContours()
            for i in range(0, n):
                self.contour.SetValue(i, int(self.contour.GetValue(i)))
                # print self.contour

                # TODO: should decimateLevel and preserveTopology be instance variables?
        decimateLevel = self.parameters["Simplify"]
        preserveTopology = self.parameters["PreserveTopology"]
        if decimateLevel != 0:
            self.decimate.SetPreserveTopology(preserveTopology)
            if not preserveTopology:
                self.decimate.SplittingOn()
                self.decimate.BoundaryVertexDeletionOn()
            else:
                self.decimate.SplittingOff()
                self.decimate.BoundaryVertexDeletionOff()
            self.decimate.SetTargetReduction(decimateLevel / 100.0)

            Logging.info(
                "Decimating %.2f%%, preserve topology: %s" % (decimateLevel, preserveTopology), kw="visualizer"
            )
            self.decimate.SetInput(input)
            input = self.decimate.GetOutput()

        if self.parameters["Normals"]:
            angle = self.parameters["FeatureAngle"]
            Logging.info("Generating normals at angle", angle, kw="visualizer")
            self.normals.SetFeatureAngle(angle)
            self.normals.SetInput(input)
            input = self.normals.GetOutput()

        self.mapper.SetInput(input)
        VisualizationModule.updateRendering(self, input)
        self.parent.Render()
Пример #4
0
    def updateRendering(self):
        """
		Update the Rendering of this module
		"""
        method = self.parameters["Method"]
        self.setMethod(method)

        if self.volumeModule:
            self.volumeModule.function = vtk.vtkVolumeRayCastIsosurfaceFunction(
            )
            self.volumeModule.function.SetIsoValue(self.parameters["IsoValue"])
            self.volumeModule.showTimepoint(self.timepoint)
            return

        if not self.init:
            self.init = 1
            self.mapper.ColorByArrayComponent(0, 0)
        self.mapper.AddObserver("ProgressEvent", lib.messenger.send)
        lib.messenger.connect(self.mapper, 'ProgressEvent',
                              self.updateProgress)
        dataUnit = self.getInputDataUnit(1)
        if not dataUnit:
            dataUnit = self.dataUnit
        dataCtf = dataUnit.getColorTransferFunction()
        if self.parameters["SolidColor"]:
            minval, maxval = dataCtf.GetRange()
            ctf = vtk.vtkColorTransferFunction()
            ctf.AddRGBPoint(int(minval), 0, 0, 0)
            r, g, b = dataCtf.GetColor(maxval)
            ctf.AddRGBPoint(int(minval) + 1, r, g, b)
            ctf.AddRGBPoint(maxval, r, g, b)
        else:
            ctf = dataCtf
        self.mapper.SetLookupTable(ctf)
        self.mapper.ScalarVisibilityOn()

        minVal, maxVal = self.data.GetScalarRange()
        self.setScalarRange(minVal, maxVal)

        self.mapper.SetScalarRange(minVal, maxVal)
        self.mapper.SetColorModeToMapScalars()

        opacity = self.parameters["Transparency"]
        opacity = (100 - opacity) / 100.0
        Logging.info("Using opacity ", opacity, kw="visualizer")
        if opacity != 1:
            cullers = self.parent.getRenderer().GetCullers()
            cullers.InitTraversal()
            culler = cullers.GetNextItem()
            culler.SetSortingStyleToBackToFront()
            #print cullers, culler
            #self.parent.getRenderer().GetRenderWindow().SetAlphaBitPlanes(1)
            #self.parent.getRenderer().GetRenderWindow().SetMultiSamples(0)
            #self.parent.getRenderer().SetUseDepthPeeling(1)
            #self.parent.getRenderer().SetMaximumNumberOfPeels(100)
            #self.parent.getRenderer().SetOcclusionRatio(1.0)
            #print self.parent.getRenderer().GetLastRenderingUsedDepthPeeling()

        self.actor.GetProperty().SetOpacity(opacity)

        polyinput = self.getPolyDataInput(1)
        if polyinput:
            Logging.info("Using polydata input", kw="visualizer")
            self.mapper.SetInput(polyinput)
            VisualizationModule.updateRendering(self, polyinput)
            self.parent.Render()
            return

        x, y, z = self.dataUnit.getDimensions()
        input = self.getInput(1)
        input = optimize.optimize(image=input,
                                  updateExtent=(0, x - 1, 0, y - 1, 0, z - 1))

        if self.parameters["Gaussian"]:
            Logging.info("Doing gaussian smoothing", kw="visualizer")
            if not self.smooth:
                self.smooth = vtk.vtkImageGaussianSmooth()
            self.smooth.SetInput(input)
            input = self.smooth.GetOutput()

        self.contour.SetInput(input)
        input = self.contour.GetOutput()

        multi = self.parameters["MultipleSurfaces"]

        if not multi:
            Logging.info("Using single isovalue=%d" %
                         int(self.parameters["IsoValue"]),
                         kw="visualizer")
            self.contour.SetValue(0, self.parameters["IsoValue"])
        else:
            begin = self.parameters["SurfaceRangeBegin"]
            end = self.parameters["SurfaceRangeEnd"]
            n = self.parameters["SurfaceAmnt"]
            Logging.info("Generating %d values in range %d-%d" %
                         (n, begin, end),
                         kw="visualizer")
            self.contour.GenerateValues(n, begin, end)
            n = self.contour.GetNumberOfContours()
            for i in range(0, n):
                self.contour.SetValue(i, int(self.contour.GetValue(i)))
            #print self.contour

        #TODO: should decimateLevel and preserveTopology be instance variables?
        decimateLevel = self.parameters["Simplify"]
        preserveTopology = self.parameters["PreserveTopology"]
        if decimateLevel != 0:
            self.decimate.SetPreserveTopology(preserveTopology)
            if not preserveTopology:
                self.decimate.SplittingOn()
                self.decimate.BoundaryVertexDeletionOn()
            else:
                self.decimate.SplittingOff()
                self.decimate.BoundaryVertexDeletionOff()
            self.decimate.SetTargetReduction(decimateLevel / 100.0)

            Logging.info("Decimating %.2f%%, preserve topology: %s" \
               % (decimateLevel, preserveTopology), kw = "visualizer")
            self.decimate.SetInput(input)
            input = self.decimate.GetOutput()

        if self.parameters["Normals"]:
            angle = self.parameters["FeatureAngle"]
            Logging.info("Generating normals at angle", angle, kw="visualizer")
            self.normals.SetFeatureAngle(angle)
            self.normals.SetInput(input)
            input = self.normals.GetOutput()

        self.mapper.SetInput(input)
        VisualizationModule.updateRendering(self, input)
        self.parent.Render()
Пример #5
0
def RenderCubeInVTK(filename = 'test.cube', mindatum = 0.0, maxdatum = 0.0):
    global renWin

    ren = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    #######################
    # Read in Gaussian cube
    #######################

    CubeData = vtk.vtkGaussianCubeReader()
    CubeData.SetFileName(filename)

    CubeData.Update()

    #Get intrinsic scale from data
    scale = sum([x**2 for x in CubeData.GetTransform().GetScale()])

    CubeData.SetHBScale(scale) #scaling factor to compute bonds with hydrogens
    CubeData.SetBScale(scale)  #scaling factor for other bonds

    CubeData.Update()

    ###################
    #Calculate scalings

    #VTK only knows how to render integer data in the interval [0,255] or [0,65535]
    #Here, we calculate scaling factors to map the cube data to the interval.

    if mindatum == maxdatum == 0.0:
        if DEBUG:
            print "Autodetecting range"
            mindatum, maxdatum = CubeData.GetGridOutput().GetPointData().GetScalars().GetRange()

    # Find the remapped value that corresponds to zero
    zeropoint = int(2**ColorDepth*(-mindatum)/(maxdatum-mindatum))
    absmaxdatum = max(-mindatum, maxdatum)

    maxnegativeintensity = min(1.0, 1.0 - (absmaxdatum - abs(mindatum))/absmaxdatum)
    minnegativeintensity = 0.0
    if zeropoint < 0:
        minpositiveintensity = - zeropoint/(2**ColorDepth*absmaxdatum)
    else:
        minpositiveintensity = 0.0
        maxpositiveintensity = min(1.0, 1.0 - (absmaxdatum - abs(maxdatum))/absmaxdatum)
    if DEBUG:
        print "Range plotted = [%f,%f]" % (mindatum, maxdatum)
        print "Negative colors = [0,%d)" % max(0,zeropoint)
        print "Negative intensities = [%f,%f]" % (maxnegativeintensity,minnegativeintensity)
        print "Positive colors = (%d,%d)" % (max(0,zeropoint), 2**ColorDepth)
        print "Positive intensities = [%f,%f]" % (minpositiveintensity,maxpositiveintensity)
        print "On this scale, zero = %d" % zeropoint

    ################################
    # Calculate opacity transfer map

    #The code here differentiates between two cases:
    #1. the scalar data are all positive, so it's just a simple linear ramp
    #2. the scalar data are signed, so do two linear ramps

    opacityTransferFunction = vtk.vtkPiecewiseFunction()

    if zeropoint < 0:
        opacityTransferFunction.AddPoint(        0, minpositiveintensity)
    else:
        opacityTransferFunction.AddPoint(        0, maxnegativeintensity)
        opacityTransferFunction.AddPoint(zeropoint, 0.0)

    opacityTransferFunction.AddPoint(2**ColorDepth-1, maxpositiveintensity)
    opacityTransferFunction.ClampingOn()

    ###########################
    # Create color transfer map

    colorTransferFunction = vtk.vtkColorTransferFunction()

    r1, g1, b1 = NegativeColor
    r2, g2, b2 = PositiveColor
    r0, g0, b0 = BackgroundColor

    if zeropoint < 0:
        colorTransferFunction.AddRGBPoint(          0, r1, g1, b1)
    else:
        colorTransferFunction.AddRGBPoint(          0, r1, g1, b1)
        colorTransferFunction.AddRGBPoint(zeropoint-1, r1, g1, b1)
        colorTransferFunction.AddRGBPoint(zeropoint  , r0, g0, b0)
        colorTransferFunction.AddRGBPoint(zeropoint+1, r2, g2, b2)
    colorTransferFunction.AddRGBPoint(2**ColorDepth-1, r2, g2, b2)

    ########################
    # Now apply the scalings

    ScaledData = vtk.vtkImageShiftScale()
    ScaledData.SetInput(CubeData.GetGridOutput())
    ScaledData.SetShift(-mindatum)
    ScaledData.SetScale((2**ColorDepth-1)/(maxdatum-mindatum))

    if ColorDepth == 16:
        ScaledData.SetOutputScalarTypeToUnsignedShort()
    elif ColorDepth == 8:
        ScaledData.SetOutputScalarTypeToUnsignedChar()
    else:
        print
        print "Error! Unsupported color depth given"
        print
        print "valid values are 8 or 16"
        print
        raise ValueError

    ###############################
    # Form combined coloring scheme

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

    # The mapper / ray cast function know how to render the data
    compositeFunction = vtk.vtkVolumeRayCastCompositeFunction()

    volumeMapper = vtk.vtkVolumeRayCastMapper()
    volumeMapper.SetVolumeRayCastFunction(compositeFunction)
    volumeMapper.SetInput(ScaledData.GetOutput())

    #Create a coarse representation
    #Actually a fake - won't display anything

    compositeFunction2 = vtk.vtkVolumeRayCastIsosurfaceFunction()
    compositeFunction2.SetIsoValue(2**ColorDepth-1)

    volumeMapperCoarse = vtk.vtkVolumeRayCastMapper()
    volumeMapperCoarse.SetVolumeRayCastFunction(compositeFunction2)
    volumeMapperCoarse.SetInput(ScaledData.GetOutput())

    # Create volumetric object to be rendered
    # Use level of detail prop so that it won't take forever to look around

    volume = vtk.vtkLODProp3D()
    id1 = volume.AddLOD(volumeMapper, volumeProperty, 0.)
    volume.SetLODProperty(id1, volumeProperty)
    id2 = volume.AddLOD(volumeMapperCoarse, volumeProperty, 0.)
    volume.SetLODProperty(id2, volumeProperty)

    # At this point, we can position and orient the volume

    #################################
    # End of volumetric data pipeline
    #################################

    #########
    #Contours
    #########

    contour = vtk.vtkContourFilter()
    contour.SetInput(CubeData.GetGridOutput())
    contour.SetNumberOfContours(1)
    contour.SetValue(0, 0.0)

    contourMapper = vtk.vtkPolyDataMapper()
    contourMapper.SetInput(contour.GetOutput())
    contourMapper.SetScalarRange(0,0)
    contourMapper.GetLookupTable().SetNumberOfTableValues(1)
    r0, g0, b0 = NodeColor
    contourMapper.GetLookupTable().SetTableValue(0, r0, g0, b0, NodeAlpha)

    contourActor = vtk.vtkLODActor()
    contourActor.SetMapper(contourMapper)
    contourActor.GetProperty().SetOpacity(NodeAlpha)

    ##########################################
    # Create a wireframe outline of the volume
    ##########################################

    frame = vtk.vtkOutlineFilter()
    frame.SetInput(CubeData.GetGridOutput())

    frameMapper = vtk.vtkPolyDataMapper()
    frameMapper.SetInput(frame.GetOutput())

    frameActor = vtk.vtkLODActor()
    frameActor.SetMapper(frameMapper)
    frameActor.GetProperty().SetColor(FrameColor)
    frameActor.GetProperty().SetOpacity(FrameAlpha)

    ######################
    # Draw balls for atoms
    ######################

    Sphere = vtk.vtkSphereSource()
    Sphere.SetThetaResolution(16)
    Sphere.SetPhiResolution(16)
    Sphere.SetRadius(0.4)

    Glyph = vtk.vtkGlyph3D()
    Glyph.SetInput(CubeData.GetOutput())
    Glyph.SetColorMode(1)
    Glyph.SetColorModeToColorByScalar()
    Glyph.SetScaleModeToScaleByVectorComponents()
    Glyph.SetSource(Sphere.GetOutput())

    AtomsMapper = vtk.vtkPolyDataMapper()
    AtomsMapper.SetInput(Glyph.GetOutput())
    AtomsMapper.SetImmediateModeRendering(1)
    AtomsMapper.UseLookupTableScalarRangeOff()
    AtomsMapper.SetScalarVisibility(1)
    AtomsMapper.SetScalarModeToDefault()

    Atoms = vtk.vtkLODActor()
    Atoms.SetMapper(AtomsMapper)

    ############
    # Draw bonds
    ############

    Tube = vtk.vtkTubeFilter()
    Tube.SetInput(CubeData.GetOutput())

    BondsMapper = vtk.vtkPolyDataMapper()
    BondsMapper.SetInput(Tube.GetOutput())

    Bonds = vtk.vtkLODActor()
    Bonds.SetMapper(BondsMapper)

    #######################
    # Now compose the image
    #######################
    if DrawVolume:
        ren.AddVolume(volume)

    if DrawNodes:
        ren.AddActor(contourActor)

    if DrawFrame:
        ren.AddActor(frameActor)

    if DrawAtoms:
        ren.AddActor(Atoms)

    if DrawBonds:
        ren.AddActor(Bonds)

    ren.SetBackground(BackgroundColor)
    renWin.SetSize(OutputHeight, OutputWidth)


    ######################################
    # Let VTK do its magic and render away
    ######################################

    renWin.Render()

    ###################################
    # Now allow user to play with image
    ###################################

    def Keypress(obj, event):
        #This function handles keyboard interaction

        key = obj.GetKeySym()

        if key == 'd' or key == 'F13':
            WriteToPNG()
        elif key == 'h' or key == 'question' or key =='?':
            PrintHelp()
        elif key == 'c':
            camera = ren.GetActiveCamera()
            print "Camera info:"
            print "------------"
            print "Position is: ", camera.GetPosition()
            print "Focal point is:", camera.GetFocalPoint()
            print "Orientation is:", ren.GetActiveCamera().GetOrientation()
            print "WXYZ", ren.GetActiveCamera().GetOrientationWXYZ()
            print "View up direction is:", camera.GetViewUp()
            print "Direction of projection is:", camera.GetDirectionOfProjection()

        else:
            if DEBUG:
                print 'User pressed key:', key 

    if Interactive:
        iren.SetDesiredUpdateRate(25.0) #25 fps when camera is moving around
        iren.SetStillUpdateRate(0.0) #0 fps when camera is not moving

        iren.Initialize()

        #The default interaction style is joystick, which seems unnatural
        style = vtk.vtkInteractorStyleTrackballCamera()
        iren.SetInteractorStyle(style)

        iren.AddObserver("KeyPressEvent", Keypress)
        iren.Start()
    else:
        WriteToPNG()
 def __init__(self, master):
     global _vtk_lib_present
     if not _vtk_lib_present:
         raise ValueError("no VTK")
 
     # Window creation
     tk.Frame.__init__(self, master)
     self.columnconfigure(0, weight=1)
     self.rowconfigure(0, weight=1)
     
     # Renderer and associated widget
     self.im_ref = None
     self._renWidget = vtkTkRenderWidget(self)
     self._ren = vtk.vtkRenderer()
     self._renWidget.GetRenderWindow().AddRenderer(self._ren)
     self._renWidget.grid(row=0, column=0, sticky=tk.E+tk.W+tk.N+tk.S)
     
     # Transfer functions and volume display options and properties
     self.vtk_im = vtkImageImport()
     self.vtk_im.SetDataScalarType(VTK_UNSIGNED_CHAR)
     self.im_flipy = vtk.vtkImageFlip()
     self.im_flipy.SetFilteredAxis(1)
     self.im_flipy.SetInputConnection(self.vtk_im.GetOutputPort());
     self.im_flipz = vtk.vtkImageFlip()
     self.im_flipz.SetFilteredAxis(2)
     self.im_flipz.SetInputConnection(self.im_flipy.GetOutputPort());
     self.opaTF = vtk.vtkPiecewiseFunction()
     self.colTF = vtk.vtkColorTransferFunction()
     self.volProp = vtk.vtkVolumeProperty()
     self.volProp.SetColor(self.colTF)
     self.volProp.SetScalarOpacity(self.opaTF)
     self.volProp.ShadeOn()
     self.volProp.SetInterpolationTypeToLinear()
     self.compoFun = vtk.vtkVolumeRayCastCompositeFunction()
     self.isosfFun = vtk.vtkVolumeRayCastIsosurfaceFunction()
     self.isosfFun.SetIsoValue(0)
     self.mipFun = vtk.vtkVolumeRayCastMIPFunction()
     self.volMap = vtk.vtkVolumeRayCastMapper()
     self.volMap.SetVolumeRayCastFunction(self.compoFun)
     self.volMap.SetInputConnection(self.im_flipz.GetOutputPort())
     self.volume = vtk.vtkVolume()
     self.volume.SetMapper(self.volMap)
     self.volume.SetProperty(self.volProp)
     self.outlineData = vtk.vtkOutlineFilter()
     self.outlineData.SetInputConnection(self.im_flipz.GetOutputPort())
     self.mapOutline = vtk.vtkPolyDataMapper()
     self.mapOutline.SetInputConnection(self.outlineData.GetOutputPort())
     self.outline = vtk.vtkActor()
     self.outline.SetMapper(self.mapOutline)
     self.outline.GetProperty().SetColor(1, 1, 1)
     self._ren.AddVolume(self.volume)
     self._ren.AddActor(self.outline)
     self._ren.SetBackground(116/255.0,214/255.0,220/255.0)
     
     # Control widget
     self.controlbar = ttk.Frame(self)
     self.controlbar.grid(row=0, column=1,
                          sticky=tk.E+tk.W+tk.N+tk.S)
     self.drawControlBar()
     self.controlbar.grid_remove()
     self.controlbar.state = "hidden"
     self.master = master
     
     # Creates the info status bar.
     statusbar = ttk.Frame(self)
     statusbar.columnconfigure(0, weight=1)
     statusbar.grid(row=1, column=0, columnspan=2, sticky=tk.E+tk.W)
     self.infos = []
     for i in range(3):
         v = tk.StringVar(self)
         ttk.Label(statusbar, anchor=tk.W, textvariable=v).grid(row=0, column=i, sticky=tk.E+tk.W)
         self.infos.append(v)
     self.infos[2].set("Hit Tab for control <-")
         
     # Events bindings
     master.bind("<KeyPress-Tab>", self.displayControlEvent)
Пример #7
0
def RenderCubeInVTK(filename='test.cube', mindatum=0.0, maxdatum=0.0):
    global renWin

    ren = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    #######################
    # Read in Gaussian cube
    #######################

    CubeData = vtk.vtkGaussianCubeReader()
    CubeData.SetFileName(filename)

    CubeData.Update()

    #Get intrinsic scale from data
    scale = sum([x**2 for x in CubeData.GetTransform().GetScale()])

    CubeData.SetHBScale(scale)  #scaling factor to compute bonds with hydrogens
    CubeData.SetBScale(scale)  #scaling factor for other bonds

    CubeData.Update()

    ###################
    #Calculate scalings

    #VTK only knows how to render integer data in the interval [0,255] or [0,65535]
    #Here, we calculate scaling factors to map the cube data to the interval.

    if mindatum == maxdatum == 0.0:
        if DEBUG:
            print "Autodetecting range"
            mindatum, maxdatum = CubeData.GetGridOutput().GetPointData(
            ).GetScalars().GetRange()

    # Find the remapped value that corresponds to zero
    zeropoint = int(2**ColorDepth * (-mindatum) / (maxdatum - mindatum))
    absmaxdatum = max(-mindatum, maxdatum)

    maxnegativeintensity = min(
        1.0, 1.0 - (absmaxdatum - abs(mindatum)) / absmaxdatum)
    minnegativeintensity = 0.0
    if zeropoint < 0:
        minpositiveintensity = -zeropoint / (2**ColorDepth * absmaxdatum)
    else:
        minpositiveintensity = 0.0
        maxpositiveintensity = min(
            1.0, 1.0 - (absmaxdatum - abs(maxdatum)) / absmaxdatum)
    if DEBUG:
        print "Range plotted = [%f,%f]" % (mindatum, maxdatum)
        print "Negative colors = [0,%d)" % max(0, zeropoint)
        print "Negative intensities = [%f,%f]" % (maxnegativeintensity,
                                                  minnegativeintensity)
        print "Positive colors = (%d,%d)" % (max(0, zeropoint), 2**ColorDepth)
        print "Positive intensities = [%f,%f]" % (minpositiveintensity,
                                                  maxpositiveintensity)
        print "On this scale, zero = %d" % zeropoint

    ################################
    # Calculate opacity transfer map

    #The code here differentiates between two cases:
    #1. the scalar data are all positive, so it's just a simple linear ramp
    #2. the scalar data are signed, so do two linear ramps

    opacityTransferFunction = vtk.vtkPiecewiseFunction()

    if zeropoint < 0:
        opacityTransferFunction.AddPoint(0, minpositiveintensity)
    else:
        opacityTransferFunction.AddPoint(0, maxnegativeintensity)
        opacityTransferFunction.AddPoint(zeropoint, 0.0)

    opacityTransferFunction.AddPoint(2**ColorDepth - 1, maxpositiveintensity)
    opacityTransferFunction.ClampingOn()

    ###########################
    # Create color transfer map

    colorTransferFunction = vtk.vtkColorTransferFunction()

    r1, g1, b1 = NegativeColor
    r2, g2, b2 = PositiveColor
    r0, g0, b0 = BackgroundColor

    if zeropoint < 0:
        colorTransferFunction.AddRGBPoint(0, r1, g1, b1)
    else:
        colorTransferFunction.AddRGBPoint(0, r1, g1, b1)
        colorTransferFunction.AddRGBPoint(zeropoint - 1, r1, g1, b1)
        colorTransferFunction.AddRGBPoint(zeropoint, r0, g0, b0)
        colorTransferFunction.AddRGBPoint(zeropoint + 1, r2, g2, b2)
    colorTransferFunction.AddRGBPoint(2**ColorDepth - 1, r2, g2, b2)

    ########################
    # Now apply the scalings

    ScaledData = vtk.vtkImageShiftScale()
    ScaledData.SetInput(CubeData.GetGridOutput())
    ScaledData.SetShift(-mindatum)
    ScaledData.SetScale((2**ColorDepth - 1) / (maxdatum - mindatum))

    if ColorDepth == 16:
        ScaledData.SetOutputScalarTypeToUnsignedShort()
    elif ColorDepth == 8:
        ScaledData.SetOutputScalarTypeToUnsignedChar()
    else:
        print
        print "Error! Unsupported color depth given"
        print
        print "valid values are 8 or 16"
        print
        raise ValueError

    ###############################
    # Form combined coloring scheme

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

    # The mapper / ray cast function know how to render the data
    compositeFunction = vtk.vtkVolumeRayCastCompositeFunction()

    volumeMapper = vtk.vtkVolumeRayCastMapper()
    volumeMapper.SetVolumeRayCastFunction(compositeFunction)
    volumeMapper.SetInput(ScaledData.GetOutput())

    #Create a coarse representation
    #Actually a fake - won't display anything

    compositeFunction2 = vtk.vtkVolumeRayCastIsosurfaceFunction()
    compositeFunction2.SetIsoValue(2**ColorDepth - 1)

    volumeMapperCoarse = vtk.vtkVolumeRayCastMapper()
    volumeMapperCoarse.SetVolumeRayCastFunction(compositeFunction2)
    volumeMapperCoarse.SetInput(ScaledData.GetOutput())

    # Create volumetric object to be rendered
    # Use level of detail prop so that it won't take forever to look around

    volume = vtk.vtkLODProp3D()
    id1 = volume.AddLOD(volumeMapper, volumeProperty, 0.)
    volume.SetLODProperty(id1, volumeProperty)
    id2 = volume.AddLOD(volumeMapperCoarse, volumeProperty, 0.)
    volume.SetLODProperty(id2, volumeProperty)

    # At this point, we can position and orient the volume

    #################################
    # End of volumetric data pipeline
    #################################

    #########
    #Contours
    #########

    contour = vtk.vtkContourFilter()
    contour.SetInput(CubeData.GetGridOutput())
    contour.SetNumberOfContours(1)
    contour.SetValue(0, 0.0)

    contourMapper = vtk.vtkPolyDataMapper()
    contourMapper.SetInput(contour.GetOutput())
    contourMapper.SetScalarRange(0, 0)
    contourMapper.GetLookupTable().SetNumberOfTableValues(1)
    r0, g0, b0 = NodeColor
    contourMapper.GetLookupTable().SetTableValue(0, r0, g0, b0, NodeAlpha)

    contourActor = vtk.vtkLODActor()
    contourActor.SetMapper(contourMapper)
    contourActor.GetProperty().SetOpacity(NodeAlpha)

    ##########################################
    # Create a wireframe outline of the volume
    ##########################################

    frame = vtk.vtkOutlineFilter()
    frame.SetInput(CubeData.GetGridOutput())

    frameMapper = vtk.vtkPolyDataMapper()
    frameMapper.SetInput(frame.GetOutput())

    frameActor = vtk.vtkLODActor()
    frameActor.SetMapper(frameMapper)
    frameActor.GetProperty().SetColor(FrameColor)
    frameActor.GetProperty().SetOpacity(FrameAlpha)

    ######################
    # Draw balls for atoms
    ######################

    Sphere = vtk.vtkSphereSource()
    Sphere.SetThetaResolution(16)
    Sphere.SetPhiResolution(16)
    Sphere.SetRadius(0.4)

    Glyph = vtk.vtkGlyph3D()
    Glyph.SetInput(CubeData.GetOutput())
    Glyph.SetColorMode(1)
    Glyph.SetColorModeToColorByScalar()
    Glyph.SetScaleModeToScaleByVectorComponents()
    Glyph.SetSource(Sphere.GetOutput())

    AtomsMapper = vtk.vtkPolyDataMapper()
    AtomsMapper.SetInput(Glyph.GetOutput())
    AtomsMapper.SetImmediateModeRendering(1)
    AtomsMapper.UseLookupTableScalarRangeOff()
    AtomsMapper.SetScalarVisibility(1)
    AtomsMapper.SetScalarModeToDefault()

    Atoms = vtk.vtkLODActor()
    Atoms.SetMapper(AtomsMapper)

    ############
    # Draw bonds
    ############

    Tube = vtk.vtkTubeFilter()
    Tube.SetInput(CubeData.GetOutput())

    BondsMapper = vtk.vtkPolyDataMapper()
    BondsMapper.SetInput(Tube.GetOutput())

    Bonds = vtk.vtkLODActor()
    Bonds.SetMapper(BondsMapper)

    #######################
    # Now compose the image
    #######################
    if DrawVolume:
        ren.AddVolume(volume)

    if DrawNodes:
        ren.AddActor(contourActor)

    if DrawFrame:
        ren.AddActor(frameActor)

    if DrawAtoms:
        ren.AddActor(Atoms)

    if DrawBonds:
        ren.AddActor(Bonds)

    ren.SetBackground(BackgroundColor)
    renWin.SetSize(OutputHeight, OutputWidth)

    ######################################
    # Let VTK do its magic and render away
    ######################################

    renWin.Render()

    ###################################
    # Now allow user to play with image
    ###################################

    def Keypress(obj, event):
        #This function handles keyboard interaction

        key = obj.GetKeySym()

        if key == 'd' or key == 'F13':
            WriteToPNG()
        elif key == 'h' or key == 'question' or key == '?':
            PrintHelp()
        elif key == 'c':
            camera = ren.GetActiveCamera()
            print "Camera info:"
            print "------------"
            print "Position is: ", camera.GetPosition()
            print "Focal point is:", camera.GetFocalPoint()
            print "Orientation is:", ren.GetActiveCamera().GetOrientation()
            print "WXYZ", ren.GetActiveCamera().GetOrientationWXYZ()
            print "View up direction is:", camera.GetViewUp()
            print "Direction of projection is:", camera.GetDirectionOfProjection(
            )

        else:
            if DEBUG:
                print 'User pressed key:', key

    if Interactive:
        iren.SetDesiredUpdateRate(25.0)  #25 fps when camera is moving around
        iren.SetStillUpdateRate(0.0)  #0 fps when camera is not moving

        iren.Initialize()

        #The default interaction style is joystick, which seems unnatural
        style = vtk.vtkInteractorStyleTrackballCamera()
        iren.SetInteractorStyle(style)

        iren.AddObserver("KeyPressEvent", Keypress)
        iren.Start()
    else:
        WriteToPNG()
Пример #8
0
def Panoramix():
    selectedPlane1 = [0, 0, 0, 0]
    selectedPlane2 = [0, 0, 0, 0]

    def updateClippingPlane(obj, event):
        obj.GetCursorData(selectedPlane1)
        print("plane1: ", selectedPlane1)
        # global clippingPlane
        # Write some codes (ref to what you’ve done in step 2) # no more than two lines
        clippingPlane.SetOrigin(obj.GetOrigin())
        # clippingPlane.SetNormal(obj.GetNormal())
        clippingPlane.Modified()

    def updateClippingPlane2(obj, event):
        obj.GetCursorData(selectedPlane2)
        print("plane2: ", selectedPlane2)
        # global clippingPlane2
        # Write some codes (ref to what you’ve done in step 2) # no more than two lines
        clippingPlane2.SetOrigin(obj.GetOrigin())
        # clippingPlane2.SetNormal(obj.GetNormal())
        clippingPlane2.Modified()

    reader = vtk.vtkXMLImageDataReader()
    reader.SetFileName(r"aneurysm.vti")
    reader.Update()
    data = reader.GetOutput()

    image = vtk.vtkImageMathematics()
    image.SetInput1Data(data)
    image.SetConstantC(1024)
    image.SetOperationToAddConstant()
    image.Update()

    output = image.GetOutput()

    shifter = vtk.vtkImageShiftScale()
    shifter.SetInputConnection(image.GetOutputPort())
    shifter.SetOutputScalarTypeToUnsignedShort()
    shifter.Update()

    shifter2 = vtk.vtkImageShiftScale()
    shifter2.SetInputConnection(image.GetOutputPort())
    shifter2.SetOutputScalarTypeToInt()
    shifter2.Update()

    otf = vtk.vtkPiecewiseFunction()
    ctf = vtk.vtkColorTransferFunction()
    otf.RemoveAllPoints()
    otf.AddPoint(image.GetOutput().GetScalarRange()[0] + 100, 0.0)
    otf.AddPoint((image.GetOutput().GetScalarRange()[0] +
                  image.GetOutput().GetScalarRange()[1]) / 2, 0.3)
    otf.AddPoint(image.GetOutput().GetScalarRange()[1], 1.0)
    ctf.RemoveAllPoints()
    ctf.AddRGBPoint(image.GetOutput().GetScalarRange()[0], 1, 1, 0)
    ctf.AddRGBPoint(1250, 0.65, 0.7, 1.0)
    ctf.AddRGBPoint(image.GetOutput().GetScalarRange()[1], 0, 0, 1)

    propVolume = vtk.vtkVolumeProperty()
    propVolume.ShadeOn()
    propVolume.SetColor(ctf)
    propVolume.SetScalarOpacity(otf)
    propVolume.SetInterpolationTypeToLinear()

    #rayCast = vtk.vtkVolumeRayCastCompositeFunction()
    rayCast = vtk.vtkVolumeRayCastIsosurfaceFunction()
    rayCast.SetIsoValue(1200)
    #ayCast.SetCompositeMethodToInterpolateFirst()
    #rayCast.SetCompositeMethodToClassifyFirst()

    mapperVolume = vtk.vtkVolumeRayCastMapper()
    mapperVolume.SetVolumeRayCastFunction(rayCast)
    mapperVolume.SetInputConnection(shifter.GetOutputPort())

    planeWidget = vtk.vtkImagePlaneWidget()
    planeWidget.SetInputConnection(reader.GetOutputPort())
    planeWidget.SetPlaneOrientationToZAxes()
    planeWidget.SetSliceIndex(int(reader.GetOutput().GetDimensions()[2] / 2))
    planeWidget.AddObserver("InteractionEvent", updateClippingPlane)

    planeWidget2 = vtk.vtkImagePlaneWidget()
    planeWidget2.SetInputConnection(reader.GetOutputPort())
    planeWidget2.SetPlaneOrientationToZAxes()
    planeWidget2.SetSliceIndex(
        int(reader.GetOutput().GetDimensions()[2] - 15.0))
    planeWidget2.AddObserver("InteractionEvent", updateClippingPlane2)

    clippingPlane = vtk.vtkPlane()
    clippingPlane.SetOrigin(planeWidget.GetOrigin())
    clippingPlane.SetNormal(planeWidget.GetNormal())

    clippingPlane2 = vtk.vtkPlane()
    clippingPlane2.SetOrigin(planeWidget2.GetOrigin())
    clippingPlane2.SetNormal([0, 0, -1])  #planeWidget2.GetNormal())

    # mapperVolume.AddClippingPlane(clippingPlane)
    # mapperVolume.AddClippingPlane(clippingPlane2)

    # plane1:  [79.0, 86.0, 59.0, 403.0]
    # plane2:  [123.0, 74.0, 104.0, 334.0]

    pointOnPlane1 = [79.0, 86.0, 59.0, 403.0]
    pointOnPlane2 = [123.0, 74.0, 104.0, 334.0]

    # output = reader.GetOutput()
    # points = output.GetPoints()
    # array = output.GetData()
    # numpy_nodes = vtk_to_numpy(image.GetOutput().GetPointData())
    # print(numpy_nodes.shape)
    # print(output.GetNumberOfPoints())

    gtf = vtk.vtkPiecewiseFunction()
    gtf.RemoveAllPoints()
    gtf.AddPoint(image.GetOutput().GetScalarRange()[0], 0.0)
    gtf.AddPoint((image.GetOutput().GetScalarRange()[0] +
                  image.GetOutput().GetScalarRange()[1]) / 2, 0.8)
    gtf.AddPoint(image.GetOutput().GetScalarRange()[1], 1.0)
    propVolume.SetGradientOpacity(gtf)

    actorVolume = vtk.vtkVolume()
    actorVolume.SetMapper(mapperVolume)
    actorVolume.SetProperty(propVolume)

    renderWindow = vtk.vtkRenderWindow()
    renderer = vtk.vtkRenderer()
    renderWindow.AddRenderer(renderer)
    renderer.AddActor(actorVolume)
    # renderer.SetBackground(1, 1, 1);

    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renderWindow)
    iren.Initialize()

    planeWidget.SetInteractor(
        iren)  #render window interactor planeWidget.PlaceWidget()
    planeWidget.On()  # enable the interaction

    planeWidget2.SetInteractor(
        iren)  #render window interactor planeWidget.PlaceWidget()
    planeWidget2.On()  # enable the interaction

    renderWindow.Render()

    iren.Start()

# Make interactive via callback function

# reader.Update()

# data = reader.GetOutput()
# data_range = data.GetScalarRange()
# print("data_range", data_range)

# imagemath = vtk.vtkImageMathematics()
# imagemath.SetInputConnection(reader.GetOutputPort())
# imagemath.SetConstantC(1024.0)
# imagemath.SetOperationToAddConstant()
# imagemath.Update()

# data = imagemath.GetOutput()
# data_range = data.GetScalarRange()
# print("data_range", data_range)

# #Contour
# #contour = vtk.vtkContourFilter()
# #contour.SetInputConnection(imagemath.GetOutputPort())
# #contour.SetValue(0, 2000)
# #contour.SetValue(1, 800)
# #contour.GenerateValues(3,1400, 2000)

# otf = vtk.vtkPiecewiseFunction()
# ctf = vtk.vtkColorTransferFunction()

# otf.RemoveAllPoints()
# otf.AddPoint(imagemath.GetOutput().GetScalarRange()[0]+100, 0.0)
# otf.AddPoint((imagemath.GetOutput().GetScalarRange()[0]+imagemath.GetOutput().GetScalarRange()[1])/2, 0.3)
# otf.AddPoint(imagemath.GetOutput().GetScalarRange()[1], 1.0)
# ctf.RemoveAllPoints()
# ctf.AddRGBPoint(imagemath.GetOutput().GetScalarRange()[0], 1, 1, 0)
# ctf.AddRGBPoint(1250, 0.65, 0.7, 1.0)
# ctf.AddRGBPoint(imagemath.GetOutput().GetScalarRange()[1], 0, 0, 1)

# propVolume = vtk.vtkVolumeProperty()
# propVolume.ShadeOn()
# propVolume.SetColor(ctf)
# propVolume.SetScalarOpacity(otf)
# propVolume.SetInterpolationTypeToLinear()

# #rayCast = vtk.vtkVolumeRayCastMIPFunction()

# rayCast = vtk.vtkVolumeRayCastIsosurfaceFunction()
# rayCast.SetIsoValue(1200)

# #rayCast = vtk.vtkVolumeRayCastCompositeFunction()
# #rayCast.SetCompositeMethodToInterpolateFirst()
# #rayCast.SetCompositeMethodToClassifyFirst()

# #We will need a mapper and an actor, let`s use the vtkPolyDataMapper and the vtkActor classes.
# #mapper = vtk.vtkPolyDataMapper()
# #mapper.SetInputConnection(contour.GetOutputPort())
# #mapper.ScalarVisibilityOff()

# shift = vtk.vtkImageShiftScale()
# shift.SetInputConnection(imagemath.GetOutputPort())
# shift.SetOutputScalarTypeToUnsignedShort()

# mapperVolume = vtk.vtkVolumeRayCastMapper()
# mapperVolume.SetVolumeRayCastFunction(rayCast)
# mapperVolume.SetInputConnection(shift.GetOutputPort())

# actorVolume = vtk.vtkVolume()
# actorVolume.SetMapper(mapperVolume)
# actorVolume.SetProperty(propVolume)

# gtf = vtk.vtkPiecewiseFunction()
# gtf.RemoveAllPoints()
# gtf.AddPoint(imagemath.GetOutput().GetScalarRange()[0], 0.0)
# gtf.AddPoint((imagemath .GetOutput().GetScalarRange()[0]+ imagemath.GetOutput().GetScalarRange()[1])/2, 0.8)
# gtf.AddPoint(imagemath.GetOutput().GetScalarRange()[1], 1.0)
# propVolume.SetGradientOpacity(gtf)

# # Define FIRST plane and clipping Plane
# planeWidget = vtk.vtkImagePlaneWidget()
# planeWidget.SetInputConnection(reader.GetOutputPort())
# planeWidget.SetPlaneOrientationToZAxes()
# #print("slice pos", planeWidget.GetSlicePosition())
# #print("go to ", planeWidget.GetSlicePosition()+410.0)
# #planeWidget.SetOrigin([-192.00000375, -318.00000375, -300.5])
# #print("slice pos", planeWidget.GetSlicePosition())
# #planeWidget.SetSliceIndex(0) #int(reader.GetOutput().GetDimensions()[2]/2))

# clippingPlane = vtk.vtkPlane()
# # print(planeWidget.GetOrigin())
# #clippingPlane.SetOrigin(planeWidget.GetOrigin())
# origin = [-192.00000375, -318.00000375, -300.5]
# clippingPlane.SetOrigin(origin)
# normal = [planeWidget.GetNormal()[0],planeWidget.GetNormal()[1],planeWidget.GetNormal()[2]]
# print("normal", normal)
# clippingPlane.SetNormal(normal)

# def updateClippingPlane(obj, event):
#   print(obj.GetCurrentImageValue())
#   #clippingPlane.SetOrigin(obj.GetOrigin())
#   #lippingPlane.Modified()

# planeWidget.AddObserver("InteractionEvent", updateClippingPlane)

# # Define SECOND plane and clipping Plane
# ## planeWidget2 = vtk.vtkImagePlaneWidget()
# ## planeWidget2.SetInputConnection(reader.GetOutputPort())
# ## planeWidget2.SetPlaneOrientationToZAxes()
# ## planeWidget2.SetSliceIndex(int(reader.GetOutput().GetDimensions()[2]))

# ## print("normal:", planeWidget2.GetNormal())
# ## clippingPlane2 = vtk.vtkPlane()
# ## clippingPlane2.SetOrigin(planeWidget2.GetOrigin())
# ## normal = [planeWidget2.GetNormal()[0],planeWidget2.GetNormal()[1],-planeWidget2.GetNormal()[2]]
# ## print("normal mod:", normal)
# ## clippingPlane2.SetNormal(normal)

# ## def updateClippingPlane2(obj, event):
# ##   clippingPlane2.SetOrigin(obj.GetOrigin())
# ##   clippingPlane2.Modified()

# #planeWidget2.AddObserver("InteractionEvent", updateClippingPlane2)

# # Add planes to Mapper
# planes = vtk.vtkPlaneCollection()
# planes.AddItem(clippingPlane)
# ## planes.AddItem(clippingPlane2)
# mapperVolume.SetClippingPlanes(planes)

# #Let`s add our render window and an interactor:
# renderWindow = vtk.vtkRenderWindow()
# renderer = vtk.vtkRenderer()

# renderWindow.AddRenderer(renderer)
# renderer.AddActor(actorVolume)

# iren = vtk.vtkRenderWindowInteractor()

# iren.SetRenderWindow(renderWindow)
# iren.Initialize()

# ## planeWidget2.SetInteractor(iren)# render window interactor
# ## planeWidget2.PlaceWidget()
# ## planeWidget2.On() # enable the interaction

# planeWidget.SetInteractor(iren)# render window interactor
# planeWidget.PlaceWidget()
# planeWidget.On() # enable the interaction

# renderWindow.Render()
# iren.Start()
Пример #9
0
def volume_render(field,
                  outfile,
                  maxopacity=1.0,
                  cmap='bone',
                  size=600,
                  elevation=45,
                  azimuth=45,
                  bkg=(0.0, 0.0, 0.0),
                  opacitycut=0.35,
                  offscreen=False,
                  rayfunction='smart'):
    """
    Uses vtk to make render an image of a field, with control over the
    camera angle and colormap.

    Input Parameters
    ----------------
        field : np.ndarray
            3D array of the field to render.
        outfile : string
            The save name of the image.
        maxopacity : Float
            Default is 1.0
        cmap : matplotlib colormap string
            Passed to cmap2colorfunc. Default is bone.
        size : 2-element list-like of ints or Int
            The size of the final rendered image.
        elevation : Numeric
            The elevation of the camera angle, in degrees. Default is 45
        azimuth : Numeric
            The azimuth of the camera angle, in degrees. Default is 45
        bkg : Tuple of floats
            3-element tuple of floats on [0,1] of the background image color.
            Default is (0., 0., 0.).
    """
    sh = field.shape

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

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

    alphaChannelFunc = vtk.vtkPiecewiseFunction()
    alphaChannelFunc.AddPoint(0, 0.0)
    alphaChannelFunc.AddPoint(int(255 * opacitycut), maxopacity)

    volumeProperty = vtk.vtkVolumeProperty()
    colorFunc = cmap2colorfunc(cmap)
    volumeProperty.SetColor(colorFunc)
    volumeProperty.SetScalarOpacity(alphaChannelFunc)

    volumeMapper = vtk.vtkVolumeRayCastMapper()
    if rayfunction == 'mip':
        comp = vtk.vtkVolumeRayCastMIPFunction()
        comp.SetMaximizeMethodToOpacity()
    elif rayfunction == 'avg':
        comp = vtk.vtkVolumeRayCastCompositeFunction()
    elif rayfunction == 'iso':
        comp = vtk.vtkVolumeRayCastIsosurfaceFunction()
        comp.SetIsoValue(maxopacity / 2)
    else:
        comp = vtk.vtkVolumeRayCastIsosurfaceFunction()
    volumeMapper.SetSampleDistance(0.1)
    volumeMapper.SetVolumeRayCastFunction(comp)

    if rayfunction == 'smart':
        volumeMapper = vtk.vtkSmartVolumeMapper()
    volumeMapper.SetInputConnection(dataImporter.GetOutputPort())

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

    light = vtk.vtkLight()
    light.SetLightType(vtk.VTK_LIGHT_TYPE_HEADLIGHT)
    light.SetIntensity(5.5)
    light.SwitchOn()

    renderer = vtk.vtkRenderer()
    renderWin = vtk.vtkRenderWindow()
    renderWin.AddRenderer(renderer)
    renderWin.SetOffScreenRendering(1)

    if not hasattr(size, '__iter__'):
        size = (size, size)

    renderer.AddVolume(volume)
    renderer.AddLight(light)
    renderer.SetBackground(*bkg)
    renderWin.SetSize(*size)

    if offscreen:
        renderWin.SetOffScreenRendering(1)

    def exitCheck(obj, event):
        if obj.GetEventPending() != 0:
            obj.SetAbortRender(1)

    renderWin.AddObserver("AbortCheckEvent", exitCheck)

    renderInteractor = vtk.vtkRenderWindowInteractor()
    renderInteractor.Initialize()
    renderWin.Render()
    renderInteractor.Start()

    #writer = vtk.vtkFFMPEGWriter()
    #writer.SetQuality(2)
    #writer.SetRate(24)
    #w2i = vtk.vtkWindowToImageFilter()
    #w2i.SetInput(renderWin)
    #writer.SetInputConnection(w2i.GetOutputPort())
    #writer.SetFileName('movie.avi')
    #writer.Start()
    #writer.End()

    writer = vtk.vtkPNGWriter()
    w2i = vtk.vtkWindowToImageFilter()
    w2i.SetInput(renderWin)
    writer.SetInputConnection(w2i.GetOutputPort())

    renderWin.Render()
    ac = renderer.GetActiveCamera()
    ac.Elevation(elevation)
    ac.Azimuth(azimuth)
    renderer.ResetCameraClippingRange()
    renderWin.Render()
    w2i.Modified()
    writer.SetFileName(outfile)
    writer.Write()