def __init__(self, input=None, MinOpacity=0.0, MaxOpacity=0.1): import qt import vtk from vtk.qt.QVTKRenderWindowInteractor import QVTKRenderWindowInteractor self.__MinOpacity__ = MinOpacity self.__MaxOpacity__ = MaxOpacity # every QT app needs an app self.__app__ = qt.QApplication(['itkviewer']) # create the widget self.__widget__ = QVTKRenderWindowInteractor() self.__ren__ = vtk.vtkRenderer() self.__widget__.GetRenderWindow().AddRenderer(self.__ren__) self.__itkvtkConverter__ = None self.__volumeMapper__ = vtk.vtkVolumeTextureMapper2D() self.__volume__ = vtk.vtkVolume() self.__volumeProperty__ = vtk.vtkVolumeProperty() self.__volume__.SetMapper(self.__volumeMapper__) self.__volume__.SetProperty(self.__volumeProperty__) self.__ren__.AddVolume(self.__volume__) self.__outline__ = None self.__outlineMapper__ = None self.__outlineActor__ = None self.AdaptColorAndOpacity(0, 255) if input: self.SetInput(input) self.AdaptColorAndOpacity()
def __init__(self, input=None, MinOpacity=0.0, MaxOpacity=0.1) : import qt import vtk from vtk.qt.QVTKRenderWindowInteractor import QVTKRenderWindowInteractor self.__MinOpacity__ = MinOpacity self.__MaxOpacity__ = MaxOpacity # every QT app needs an app self.__app__ = qt.QApplication(['itkviewer']) # create the widget self.__widget__ = QVTKRenderWindowInteractor() self.__ren__ = vtk.vtkRenderer() self.__widget__.GetRenderWindow().AddRenderer(self.__ren__) self.__itkvtkConverter__ = None self.__volumeMapper__ = vtk.vtkVolumeTextureMapper2D() self.__volume__ = vtk.vtkVolume() self.__volumeProperty__ = vtk.vtkVolumeProperty() self.__volume__.SetMapper(self.__volumeMapper__) self.__volume__.SetProperty(self.__volumeProperty__) self.__ren__.AddVolume(self.__volume__) self.__outline__ = None self.__outlineMapper__ = None self.__outlineActor__ = None self.AdaptColorAndOpacity(0, 255) if input : self.SetInput(input) self.AdaptColorAndOpacity()
def SetupTextureMapper(self): if not self.GetInput(): return mapper3D = vtk.vtkVolumeTextureMapper3D.SafeDownCast(self.__VolumeTextureMapper) if mapper3D and not self.GetRenderWindow().GetNeverRendered(): if not mapper3D.IsRenderSupported(self.__VolumeProperty): # try the ATI fragment program implementation mapper3D.SetPreferredMethodToFragmentProgram() if not mapper3D.IsRenderSupported(self.__VolumeProperty): print "Warning: 3D texture volume rendering is not supported by your hardware, switching to 2D texture rendering." newMapper = vtk.vtkVolumeTextureMapper2D() newMapper.CroppingOn() newMapper.SetCroppingRegionFlags (0x7ffdfff) range = self.GetInput().GetScalarRange() shift = 0 - range[0] scale = 65535.0 / (range[1]-range[0]) scaler = vtk.vtkImageShiftScale() scaler.SetInput(self.GetInput()) scaler.SetShift(shift) scaler.SetScale(scale) scaler.SetOutputScalarTypeToUnsignedShort() scaler.Update() newMapper.SetInput(scaler.GetOutput()) # del scaler self.__Callback.SetVolumeMapper(newMapper) self.__VolumeMapper = newMapper self.__VolumeMapper.SetMapper(newMapper)
def __init__(self, parent): wx.SplitterWindow.__init__(self, parent) # # setup the control panel # self.controlPanel = wx.lib.scrolledpanel.ScrolledPanel( self ) vBox = wx.BoxSizer( wx.VERTICAL ) self.mode = wx.RadioBox( self.controlPanel, label="Mode", choices=["2D", "3D"] ) vBox.Add( self.mode, 0, wx.EXPAND ) self.colorAndOpacityEditor = WrapITKColorAndOpacityEditor( self.controlPanel ) vBox.Add( self.colorAndOpacityEditor, 0, wx.EXPAND ) self.controlPanel.SetSizer( vBox ) self.controlPanel.SetupScrolling() # # setup the render window # from vtk.wx.wxVTKRenderWindowInteractor import wxVTKRenderWindowInteractor from vtk import vtkRenderer, vtkVolumeTextureMapper2D, vtkVolumeProperty, vtkVolume self.rendererWindow = wxVTKRenderWindowInteractor(self, -1) self.renderer = vtkRenderer() self.rendererWindow.GetRenderWindow().AddRenderer(self.renderer) self.volumeMapper = vtkVolumeTextureMapper2D() self.volume = vtkVolume() self.volumeProperty = vtkVolumeProperty() self.volumeProperty.SetScalarOpacity( self.colorAndOpacityEditor.opacityTransferFunction ) self.volumeProperty.SetColor( self.colorAndOpacityEditor.colorTransferFunction ) self.volume.SetMapper( self.volumeMapper ) self.volume.SetProperty( self.volumeProperty ) self.renderer.AddVolume( self.volume ) self.outline = None self.outlineMapper = None self.outlineActor = None # fill the split pane self.SplitVertically( self.controlPanel, self.rendererWindow ) # avoid loosing on panel or the other self.SetMinimumPaneSize( 1 ) # to manage update event correctly self.updateInProgress = False
def createVolume(image): ''' create volume of image - image must be a typical irm image with gray values comprised between 0 and 255 ''' # Create transfer mapping scalar value to opacity opacityTransferFunction = vtk.vtkPiecewiseFunction() opacityTransferFunction.AddPoint(0, 0.0) opacityTransferFunction.AddPoint(10.0, 0.0) opacityTransferFunction.AddPoint(40.0, 1.0) opacityTransferFunction.AddPoint(60, 1.0) opacityTransferFunction.AddPoint(200, 0.0) opacityTransferFunction.AddPoint(255, 0.0) # 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() volumeProperty.SetDiffuse(0.7) volumeProperty.SetSpecular(0.5) volumeProperty.SetSpecularPower(70.0) # mapper volumeMapper=None if 1: compositeFunction = vtk.vtkVolumeRayCastCompositeFunction() volumeMapper = vtk.vtkVolumeRayCastMapper() volumeMapper.SetVolumeRayCastFunction(compositeFunction) volumeMapper.SetInput(image) else: volumeMapper = vtk.vtkVolumeTextureMapper2D() volumeMapper.SetInput(image) # volume volume = vtk.vtkVolume() volume.SetMapper(volumeMapper) volume.SetProperty(volumeProperty) return volume, volumeMapper
def set_map_type(self, map_type): if map_type == self.map_type: return Common.state.busy () if map_type == 0: self.map = vtk.vtkVolumeRayCastMapper () self.map.SetVolumeRayCastFunction (self.ray_cast_func) elif map_type == 1: self.map = vtk.vtkVolumeTextureMapper2D() elif map_type == 2: self.map = vtk.vtkVolumeProMapper() self.renwin.get_active_camera().ParallelProjectionOn() tkMessageBox.showwarning("Notice!","Camera's projection type set to parallel projection!") self.map_type = map_type self.map.SetInput (self.mod_m.GetOutput ()) self.act.SetMapper (self.map) if self.root and self.root.winfo_exists(): self.make_map_gui() self.make_rcf_gui() self.renwin.Render () Common.state.idle ()
volumeProperty.SetColor(colorTransferFunction) volumeProperty.SetScalarOpacity(opacityTransferFunction) volumeProperty.SetInterpolationTypeToLinear() volumeProperty.ShadeOn() ren1 = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren1) renWin.SetSize(600, 300) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) ren1.SetBackground(0.1, 0.2, 0.4) i = 0 while i < 2: j = 0 while j < 4: locals()[get_variable_name("volumeMapper_", i, "_", j, "")] = vtk.vtkVolumeTextureMapper2D() locals()[get_variable_name("volumeMapper_", i, "_", j, "")].SetInputConnection(reader.GetOutputPort()) locals()[get_variable_name("volumeMapper_", i, "_", j, "")].CroppingOn() locals()[get_variable_name("volumeMapper_", i, "_", j, "")].SetCroppingRegionPlanes(17, 33, 17, 33, 17, 33) locals()[get_variable_name("volume_", i, "_", j, "")] = vtk.vtkVolume() locals()[get_variable_name("volume_", i, "_", j, "")].SetMapper( locals()[get_variable_name("volumeMapper_", i, "_", j, "")] ) locals()[get_variable_name("volume_", i, "_", j, "")].SetProperty(volumeProperty) locals()[get_variable_name("userMatrix_", i, "_", j, "")] = vtk.vtkTransform() locals()[get_variable_name("userMatrix_", i, "_", j, "")].PostMultiply() locals()[get_variable_name("userMatrix_", i, "_", j, "")].Identity() locals()[get_variable_name("userMatrix_", i, "_", j, "")].Translate(-25, -25, -25) if i == 0: locals()[get_variable_name("userMatrix_", i, "_", j, "")].RotateX( expr.expr(globals(), locals(), ["j", "*", "90", "+", "20"])
# 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) # The mapper knows how to render the data volumeMapper = vtk.vtkVolumeTextureMapper2D() 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) ren.AddVolume(volume) renWin.Render() def CheckAbort(obj, event): if obj.GetEventPending() != 0: obj.SetAbortRender(1)
def viewvol(arr,voxsz=(1.0,1.0,1.0),maptype=1): print(arr.dtype) arr = arr/arr.max() arr = arr*255 sh.im = vtk.vtkImageData() #sh.im.SetScalarTypeToFloat() sh.im.SetScalarTypeToUnsignedChar() sh.im.SetDimensions(arr.shape[0],arr.shape[1],arr.shape[2]) sh.im.SetOrigin(0,0,0) sh.im.SetSpacing(voxsz[2],voxsz[0],voxsz[1]) sh.im.AllocateScalars() print(sh.im.GetNumberOfScalarComponents()) print(arr.shape) for i in range(arr.shape[0]): for j in range(arr.shape[1]): for k in range(arr.shape[2]): sh.im.SetScalarComponentFromFloat(i,j,k,0,arr[i,j,k]) sh.opacity = vtk.vtkPiecewiseFunction() for i in range(sh.opacityprop.shape[0]): sh.opacity.AddPoint(sh.opacityprop[i,0],sh.opacityprop[i,1]) sh.color = vtk.vtkColorTransferFunction() for i in range(sh.colorprop.shape[0]): sh.color.AddRGBPoint(sh.colorprop[i,0],sh.colorprop[i,1],sh.colorprop[i,2],sh.colorprop[i,3]) if(maptype==0): property = vtk.vtkVolumeProperty() property.SetColor(sh.color) property.SetScalarOpacity(sh.opacity) mapper = vtk.vtkVolumeTextureMapper2D() mapper.SetInput(sh.im) if (maptype==1): property = vtk.vtkVolumeProperty() property.SetColor(sh.color) property.SetScalarOpacity(sh.opacity) property.ShadeOn() property.SetInterpolationTypeToLinear() compositeFunction = vtk.vtkVolumeRayCastCompositeFunction() mapper = vtk.vtkVolumeRayCastMapper() mapper.SetVolumeRayCastFunction(compositeFunction) mapper.SetInput(sh.im) ren=vtk.vtkRenderer() volume = vtk.vtkVolume() volume.SetMapper(mapper) volume.SetProperty(property) ren.AddVolume(volume) #cone = tvtk.ConeSource(resolution=8)#,height=100, radius=50) #coneMapper = tvtk.PolyDataMapper(input=cone.get_output()) #coneActor = tvtk.Actor(mapper=coneMapper) #coneActor.position=sc.array([100.,100.,100.]) #ren.add_actor(coneActor) #try: #simplewx(ren,title=sh.project,width=600,height=400) #except: simpletk(ren,title=sh.project,width=600,height=400) return ren
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
readerOutput.Register(None) # Create transfer functions for opacity and color opacityTransferFunction = vtk.vtkPiecewiseFunction() opacityTransferFunction.AddPoint(600,0.0) opacityTransferFunction.AddPoint(2000,1.0) colorTransferFunction = vtk.vtkColorTransferFunction() colorTransferFunction.ClampingOff() colorTransferFunction.AddHSVPoint(0.0,0.01,1.0,1.0) colorTransferFunction.AddHSVPoint(1000.0,0.50,1.0,1.0) colorTransferFunction.AddHSVPoint(2000.0,0.99,1.0,1.0) colorTransferFunction.SetColorSpaceToHSV() # Create properties, mappers, volume actors, and ray cast function volumeProperty = vtk.vtkVolumeProperty() volumeProperty.SetColor(colorTransferFunction) volumeProperty.SetScalarOpacity(opacityTransferFunction) volumeMapper = vtk.vtkVolumeTextureMapper2D() volumeMapper.SetInputData(readerOutput) volumeMapper.SetMaximumStorageSize(10000000) # The data object is now referenced by the connection. readerOutput.UnRegister(None) # not needed in python volume = vtk.vtkVolume() volume.SetMapper(volumeMapper) volume.SetProperty(volumeProperty) # Create geometric sphere sphereSource = vtk.vtkSphereSource() sphereSource.SetRadius(65) sphereSource.SetThetaResolution(20) sphereSource.SetPhiResolution(40) def colorCells (__vtk__temp0=0,__vtk__temp1=0): randomColorGenerator = vtk.vtkMath() input = randomColors.GetInput()
volumeProperty.SetColor(colorTransferFunction) volumeProperty.SetScalarOpacity(opacityTransferFunction) volumeProperty.SetInterpolationTypeToLinear() volumeProperty.ShadeOn() ren1 = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren1) renWin.SetSize(600,300) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) ren1.SetBackground(0.1,0.2,0.4) i = 0 while i < 2: j = 0 while j < 4: locals()[get_variable_name("volumeMapper_", i, "_", j, "")] = vtk.vtkVolumeTextureMapper2D() locals()[get_variable_name("volumeMapper_", i, "_", j, "")].SetInputConnection(reader.GetOutputPort()) locals()[get_variable_name("volumeMapper_", i, "_", j, "")].CroppingOn() locals()[get_variable_name("volumeMapper_", i, "_", j, "")].SetCroppingRegionPlanes(17,33,17,33,17,33) locals()[get_variable_name("volume_", i, "_", j, "")] = vtk.vtkVolume() locals()[get_variable_name("volume_", i, "_", j, "")].SetMapper(locals()[get_variable_name("volumeMapper_", i, "_", j, "")]) locals()[get_variable_name("volume_", i, "_", j, "")].SetProperty(volumeProperty) locals()[get_variable_name("userMatrix_", i, "_", j, "")] = vtk.vtkTransform() locals()[get_variable_name("userMatrix_", i, "_", j, "")].PostMultiply() locals()[get_variable_name("userMatrix_", i, "_", j, "")].Identity() locals()[get_variable_name("userMatrix_", i, "_", j, "")].Translate(-25,-25,-25) if (i == 0): locals()[get_variable_name("userMatrix_", i, "_", j, "")].RotateX(expr.expr(globals(), locals(),["j","*","90","+","20"])) locals()[get_variable_name("userMatrix_", i, "_", j, "")].RotateY(20) pass else:
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
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
def __init__(self): ActorFactory.ActorFactory.__init__(self) self._LookupTable = None # lookup table is currently not used self._ColorTransferFunction = None self._OpacityTransferFunction = None self._RendererObserverList = {} # create a clipping cube to go with the volume self._ClippingCube = ClippingCubeFactory.ClippingCubeFactory() self.AddChild(self._ClippingCube) self._CubeClippingPlanes = vtk.vtkPlaneCollection() for i in range(6): self._CubeClippingPlanes.AddItem(vtk.vtkPlane()) # corner clipping planes, in pairs with opposite normals self._CornerClippingPlanes = vtk.vtkPlaneCollection() for i in range(6): self._CornerClippingPlanes.AddItem(vtk.vtkPlane()) # clipping planes for the volume, sorted for the # three chunks that will make up the final volume # (these are currently unused) self._ClippingPlanes = [vtk.vtkPlaneCollection(), vtk.vtkPlaneCollection(), vtk.vtkPlaneCollection()] for i in range(3): planes = self._ClippingPlanes[i] cplanes = self._CornerClippingPlanes bplanes = self._CubeClippingPlanes if i == 0: planes.AddItem(cplanes.GetItemAsObject(0)) planes.AddItem(bplanes.GetItemAsObject(1)) planes.AddItem(bplanes.GetItemAsObject(2)) planes.AddItem(bplanes.GetItemAsObject(3)) planes.AddItem(bplanes.GetItemAsObject(4)) planes.AddItem(bplanes.GetItemAsObject(5)) else: planes.AddItem(bplanes.GetItemAsObject(0)) planes.AddItem(cplanes.GetItemAsObject(1)) if i == 1: planes.AddItem(cplanes.GetItemAsObject(2)) planes.AddItem(bplanes.GetItemAsObject(3)) planes.AddItem(bplanes.GetItemAsObject(4)) planes.AddItem(bplanes.GetItemAsObject(5)) else: planes.AddItem(bplanes.GetItemAsObject(2)) planes.AddItem(cplanes.GetItemAsObject(3)) if i == 2: planes.AddItem(cplanes.GetItemAsObject(4)) planes.AddItem(bplanes.GetItemAsObject(5)) else: planes.AddItem(bplanes.GetItemAsObject(4)) planes.AddItem(bplanes.GetItemAsObject(5)) # generate the pipeline pieces self._Input = None # transform the full-resolution volume self._RayCastReslice = vtk.vtkImageReslice() self._RayCastReslice.SetInterpolationModeToLinear() # subsample the volume for low-res rendering self._ImagePrefilter1 = vtk.vtkImageShrink3D() self._ImagePrefilter2 = vtk.vtkImageShrink3D() # transform the subsampled volume self._ImageReslice1 = vtk.vtkImageReslice() self._ImageReslice1.SetInterpolationModeToLinear() self._ImageReslice2 = vtk.vtkImageReslice() self._ImageReslice2.SetInterpolationModeToLinear() # convert to RGBA for rendering (unused) self._ImageMapToColors = vtk.vtkImageMapToColors() self._ImageMapToColors.SetOutputFormatToRGBA() # strictly for VTK 3.2 compatibility self._ImageToStructuredPoints = vtk.vtkImageToStructuredPoints() # a transform to apply to the image self._ImageTransform = None self._TransformToGrid = vtk.vtkTransformToGrid() # the opacity pick threshold for the volume self._PickThreshold = 0.99 # the implicit volume for finding the gradient self._ImplicitVolume = vtk.vtkImplicitVolume() # the texture dimensions (later this will be set automatically # to provide the desired interactive rendering time) self._TextureSize = 128 # the bounds of the volume self._VolumeBounds = None # vtkVolume specific stuff self._VolumeProperty = vtk.vtkVolumeProperty() self._VolumeProperty.SetInterpolationTypeToLinear() rayCastFunction = vtk.vtkVolumeRayCastCompositeFunction() self._VolumeRayCastMapper = vtk.vtkVolumeRayCastMapper() self._VolumeRayCastMapper.SetVolumeRayCastFunction(rayCastFunction) self._VolumeRayCastMapper.SetClippingPlanes( self._ClippingCube.GetClippingPlanes()) try: # vtk 3.2 does not contain this function call: self._VolumeRayCastMapper.AutoAdjustSampleDistancesOff() except: pass self._VolumeTextureMapper1 = vtk.vtkVolumeTextureMapper2D() self._VolumeTextureMapper1.SetTargetTextureSize(old_div(self._TextureSize, 4), old_div(self._TextureSize, 4)) self._VolumeTextureMapper1.SetMaximumNumberOfPlanes( old_div(self._TextureSize, 2)) self._VolumeTextureMapper1.SetClippingPlanes( self._ClippingCube.GetClippingPlanes()) try: # vtk 3.2 does not contain this function call: # set to the amount of available texture memory (24MB is a good # start) self._VolumeTextureMapper1.SetMaximumStorageSize(24 * 1024 * 1024) except: pass self._VolumeTextureMapper2 = vtk.vtkVolumeTextureMapper2D() self._VolumeTextureMapper2.SetTargetTextureSize(self._TextureSize, self._TextureSize) self._VolumeTextureMapper2.SetMaximumNumberOfPlanes(self._TextureSize) self._VolumeTextureMapper2.SetClippingPlanes( self._ClippingCube.GetClippingPlanes()) try: # vtk 3.2 does not contain this function call: # set to the amount of available texture memory (24MB is a good # start) self._VolumeTextureMapper2.SetMaximumStorageSize(24 * 1024 * 1024) except: pass # set two levels of detail: texture and ray-casting self._Volume = vtk.vtkLODProp3D() self._Volume.PickableOff() idT1 = self._Volume.AddLOD(self._VolumeTextureMapper1, self._VolumeProperty, 0.02) idT2 = self._Volume.AddLOD(self._VolumeTextureMapper2, self._VolumeProperty, 0.1) # remember these LOD id numbers self._lod = [idT1, idT2] # idRC = self._Volume.AddLOD(self._VolumeRayCastMapper, # self._VolumeProperty, # 2.0) self._Volume.SetLODLevel(idT1, 2.0) self._Volume.SetLODLevel(idT2, 1.0)
def _setup_for_2d_texture(self): self._volume_mapper = vtk.vtkVolumeTextureMapper2D() module_utils.setup_vtk_object_progress(self, self._volume_mapper, 'Preparing render.')
def __init__(self): #--------------------------------------------------------- # prep the volume for rendering at 128x128x128 self.ShiftScale = vtk.vtkImageShiftScale() self.ShiftScale.SetOutputScalarTypeToUnsignedShort() self.Reslice = vtk.vtkImageReslice() self.Reslice.SetInputConnection(self.ShiftScale.GetOutputPort()) self.Reslice.SetOutputExtent(0, 127, 0, 127, 0, 127) self.Reslice.SetInterpolationModeToCubic() #--------------------------------------------------------- # set up the volume rendering self.Mapper = vtk.vtkVolumeRayCastMapper() self.Mapper.SetInputConnection(self.Reslice.GetOutputPort()) volumeFunction = vtk.vtkVolumeRayCastCompositeFunction() self.Mapper.SetVolumeRayCastFunction(volumeFunction) self.Mapper3D = vtk.vtkVolumeTextureMapper3D() self.Mapper3D.SetInputConnection(self.Reslice.GetOutputPort()) self.Mapper2D = vtk.vtkVolumeTextureMapper2D() self.Mapper2D.SetInputConnection(self.Reslice.GetOutputPort()) self.Color = vtk.vtkColorTransferFunction() self.Color.AddRGBPoint(0, 0.0, 0.0, 0.0) self.Color.AddRGBPoint(180, 0.3, 0.1, 0.2) self.Color.AddRGBPoint(1200, 1.0, 0.7, 0.6) self.Color.AddRGBPoint(2500, 1.0, 1.0, 0.9) self.ScalarOpacity = vtk.vtkPiecewiseFunction() self.ScalarOpacity.AddPoint(0, 0.0) self.ScalarOpacity.AddPoint(180, 0.0) self.ScalarOpacity.AddPoint(1200, 0.2) self.ScalarOpacity.AddPoint(2500, 0.8) self.GradientOpacity = vtk.vtkPiecewiseFunction() self.GradientOpacity.AddPoint(0, 0.0) self.GradientOpacity.AddPoint(90, 0.5) self.GradientOpacity.AddPoint(100, 1.0) self.Property = vtk.vtkVolumeProperty() self.Property.SetColor(self.Color) self.Property.SetScalarOpacity(self.ScalarOpacity) #self.Property.SetGradientOpacity(self.GradientOpacity) self.Property.SetInterpolationTypeToLinear() self.Property.ShadeOff() self.Property.SetAmbient(0.6) self.Property.SetDiffuse(0.6) self.Property.SetSpecular(0.1) self.lod2D = self.AddLOD(self.Mapper2D, self.Property, 0.01) self.lod3D = self.AddLOD(self.Mapper3D, self.Property, 0.1) self.lodRC = self.AddLOD(self.Mapper, self.Property, 1.0) self.SetLODLevel(self.lod2D, 2.0) self.SetLODLevel(self.lod3D, 1.0) self.SetLODLevel(self.lodRC, 0.0) # disable ray casting #self.DisableLOD(self.lod3D) #self.DisableLOD(self.lod2D) self.DisableLOD(self.lodRC)
def __init__(self): #--------------------------------------------------------- # prep the volume for rendering at 128x128x128 self.ShiftScale = vtk.vtkImageShiftScale() self.ShiftScale.SetOutputScalarTypeToUnsignedShort() self.Reslice = vtk.vtkImageReslice() self.Reslice.SetInput(self.ShiftScale.GetOutput()) self.Reslice.SetOutputExtent(0, 127, 0, 127, 0, 127) self.Reslice.SetInterpolationModeToCubic() #--------------------------------------------------------- # set up the volume rendering self.Mapper = vtk.vtkVolumeRayCastMapper() self.Mapper.SetInput(self.Reslice.GetOutput()) volumeFunction = vtk.vtkVolumeRayCastCompositeFunction() self.Mapper.SetVolumeRayCastFunction(volumeFunction) self.Mapper3D = vtk.vtkVolumeTextureMapper3D() self.Mapper3D.SetInput(self.Reslice.GetOutput()) self.Mapper2D = vtk.vtkVolumeTextureMapper2D() self.Mapper2D.SetInput(self.Reslice.GetOutput()) self.Color = vtk.vtkColorTransferFunction() self.Color.AddRGBPoint(0,0.0,0.0,0.0) self.Color.AddRGBPoint(180,0.3,0.1,0.2) self.Color.AddRGBPoint(1200,1.0,0.7,0.6) self.Color.AddRGBPoint(2500,1.0,1.0,0.9) self.ScalarOpacity = vtk.vtkPiecewiseFunction() self.ScalarOpacity.AddPoint(0,0.0) self.ScalarOpacity.AddPoint(180,0.0) self.ScalarOpacity.AddPoint(1200,0.2) self.ScalarOpacity.AddPoint(2500,0.8) self.GradientOpacity = vtk.vtkPiecewiseFunction() self.GradientOpacity.AddPoint(0,0.0) self.GradientOpacity.AddPoint(90,0.5) self.GradientOpacity.AddPoint(100,1.0) self.Property = vtk.vtkVolumeProperty() self.Property.SetColor(self.Color) self.Property.SetScalarOpacity(self.ScalarOpacity) #self.Property.SetGradientOpacity(self.GradientOpacity) self.Property.SetInterpolationTypeToLinear() self.Property.ShadeOff() self.Property.SetAmbient(0.6) self.Property.SetDiffuse(0.6) self.Property.SetSpecular(0.1) self.lod2D = self.AddLOD(self.Mapper2D, self.Property, 0.01) self.lod3D = self.AddLOD(self.Mapper3D, self.Property, 0.1) self.lodRC = self.AddLOD(self.Mapper, self.Property, 1.0) self.SetLODLevel(self.lod2D, 2.0) self.SetLODLevel(self.lod3D, 1.0) self.SetLODLevel(self.lodRC, 0.0) # disable ray casting #self.DisableLOD(self.lod3D) #self.DisableLOD(self.lod2D) self.DisableLOD(self.lodRC)