Esempio n. 1
0
 def createRenderer(self, **args):
     background_color = args.get('background_color', VTK_BACKGROUND_COLOR)
     self.renderer.SetBackground(*background_color)
     self.renderWindowInteractor.AddObserver('RightButtonPressEvent',
                                             self.onRightButtonPress)
     self.textDisplayMgr = TextDisplayMgr(self.renderer)
     self.pointPicker = vtk.vtkPointPicker()
     self.pointPicker.PickFromListOn()
     try:
         self.pointPicker.SetUseCells(True)
     except:
         print >> sys.stderr, "Warning, vtkPointPicker patch not installed, picking will not work properly."
     self.pointPicker.InitializePickList()
     self.renderWindowInteractor.SetPicker(self.pointPicker)
     self.addObserver(self.renderer, 'ModifiedEvent', self.activateEvent)
     self.clipper = vtk.vtkBoxWidget()
     self.clipper.RotationEnabledOff()
     self.clipper.SetPlaceFactor(1.0)
     self.clipper.KeyPressActivationOff()
     self.clipper.SetInteractor(self.renderWindowInteractor)
     self.clipper.SetHandleSize(0.005)
     self.clipper.SetEnabled(True)
     self.clipper.InsideOutOn()
     self.clipper.AddObserver('StartInteractionEvent', self.startClip)
     self.clipper.AddObserver('EndInteractionEvent', self.endClip)
     self.clipper.AddObserver('InteractionEvent', self.executeClip)
     self.clipOff()
Esempio n. 2
0
    def Execute(self):

        if self.Image == None:
            self.PrintError('Error: no Image.')

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

            self.vmtkRenderer.RegisterScript(self)                 

            self.PlaneWidgetX = vtkvmtk.vtkvmtkImagePlaneWidget()
            self.PlaneWidgetX.SetInteractor(self.vmtkRenderer.RenderWindowInteractor)
            self.PlaneWidgetY = vtkvmtk.vtkvmtkImagePlaneWidget()
            self.PlaneWidgetY.SetInteractor(self.vmtkRenderer.RenderWindowInteractor)
            self.PlaneWidgetZ = vtkvmtk.vtkvmtkImagePlaneWidget()
            self.PlaneWidgetZ.SetInteractor(self.vmtkRenderer.RenderWindowInteractor)
            self.BoxWidget = vtk.vtkBoxWidget()
            self.BoxWidget.SetInteractor(self.vmtkRenderer.RenderWindowInteractor)
            self.vmtkRenderer.AddKeyBinding('i','Interact.', self.InteractCallback)

            self.Display()
            while (self.BoxActive == 1):
                self.PaintVOI()
                self.Display()
        else:
            self.PaintVOI()

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

        if self.Image == None:
            self.PrintError('Error: no Image.')

        if self.Interactive == 1:
            
            if not self.vmtkRenderer:
                self.vmtkRenderer = vmtkrenderer.vmtkRenderer()
                self.vmtkRenderer.Initialize()
                self.OwnRenderer = 1
                
            self.PlaneWidgetX = vtk.vtkImagePlaneWidget()
            self.PlaneWidgetX.SetInteractor(self.vmtkRenderer.RenderWindowInteractor)
            self.PlaneWidgetY = vtk.vtkImagePlaneWidget()
            self.PlaneWidgetY.SetInteractor(self.vmtkRenderer.RenderWindowInteractor)
            self.PlaneWidgetZ = vtk.vtkImagePlaneWidget()
            self.PlaneWidgetZ.SetInteractor(self.vmtkRenderer.RenderWindowInteractor)
            self.BoxWidget = vtk.vtkBoxWidget()
            self.BoxWidget.SetInteractor(self.vmtkRenderer.RenderWindowInteractor)

            self.Display()
            while (self.BoxActive == 1):
                self.PaintVOI()
                self.Image = self.PaintedImage
                self.Display()
        else:
            self.PaintVOI()

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

        self.Image = self.PaintedImage
Esempio n. 4
0
 def createRenderer(self, **args ):
     background_color = args.get( 'background_color', VTK_BACKGROUND_COLOR )
     self.renderer.SetBackground(*background_color)   
     self.textDisplayMgr = TextDisplayMgr( self.renderer ) 
     self.renderWindowInitSize = args.get( 'window_size', None ) 
     if self.renderWindowInitSize <> None:
         self.renderWindow.SetSize( self.renderWindowInitSize )                             
     self.pointPicker = vtk.vtkPointPicker()
     self.pointPicker.PickFromListOn()   
     try:        self.pointPicker.SetUseCells(True)  
     except:     print>>sys.stderr,  "Warning, vtkPointPicker patch not installed, picking will not work properly."
     self.pointPicker.InitializePickList()             
     self.renderWindowInteractor.SetPicker(self.pointPicker) 
     self.addObserver( self.renderer, 'ModifiedEvent', self.activateEvent )
     self.clipper = vtk.vtkBoxWidget()
     self.clipper.RotationEnabledOff()
     self.clipper.SetPlaceFactor( 1.0 ) 
     self.clipper.KeyPressActivationOff()
     self.clipper.SetInteractor( self.renderWindowInteractor )    
     self.clipper.SetHandleSize( 0.005 )
     self.clipper.SetEnabled( True )
     self.clipper.InsideOutOn()  
     self.clipper.AddObserver( 'StartInteractionEvent', self.startClip )
     self.clipper.AddObserver( 'EndInteractionEvent', self.endClip )
     self.clipper.AddObserver( 'InteractionEvent', self.executeClip )           
     self.clipOff() 
    def Execute(self):

        if self.Image == None:
            self.PrintError('Error: no Image.')

        self.CroppedImage.DeepCopy(self.Image)

        if self.Interactive == 1:
            
            if not self.vmtkRenderer:
                self.vmtkRenderer = vmtkrenderer.vmtkRenderer()
                self.vmtkRenderer.Initialize()
                self.OwnRenderer = 1
                
            self.PlaneWidgetX = vtk.vtkImagePlaneWidget()
            self.PlaneWidgetX.SetInteractor(self.vmtkRenderer.RenderWindowInteractor)
            self.PlaneWidgetY = vtk.vtkImagePlaneWidget()
            self.PlaneWidgetY.SetInteractor(self.vmtkRenderer.RenderWindowInteractor)
            self.PlaneWidgetZ = vtk.vtkImagePlaneWidget()
            self.PlaneWidgetZ.SetInteractor(self.vmtkRenderer.RenderWindowInteractor)
            self.BoxWidget = vtk.vtkBoxWidget()
            self.BoxWidget.SetInteractor(self.vmtkRenderer.RenderWindowInteractor)

            self.Display()
            while (self.BoxActive == 1):
                self.ExtractVOI()
                self.Image = self.CroppedImage
                self.Display()
        else:
            self.ExtractVOI()

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

        self.Image = self.CroppedImage
Esempio n. 6
0
    def Execute(self):

        if self.Surface == None:
            self.PrintError('Error: no Surface.')

        if self.WidgetType == "box":
            self.ClipFunction = vtk.vtkPlanes()
        elif self.WidgetType == "sphere":
            self.ClipFunction = vtk.vtkSphere()

        self.Clipper = vtk.vtkClipPolyData()
        self.Clipper.SetInput(self.Surface)
        self.Clipper.SetClipFunction(self.ClipFunction)
        self.Clipper.GenerateClippedOutputOn()
        self.Clipper.InsideOutOn()
        
        if not self.vmtkRenderer:
            self.vmtkRenderer = vmtkrenderer.vmtkRenderer()
            self.vmtkRenderer.Initialize()
            self.OwnRenderer = 1

        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInput(self.Surface)
        mapper.ScalarVisibilityOff()
        self.Actor = vtk.vtkActor()
        self.Actor.SetMapper(mapper)
        self.vmtkRenderer.Renderer.AddActor(self.Actor)

        if self.WidgetType == "box":
            self.ClipWidget = vtk.vtkBoxWidget()
            self.ClipWidget.GetFaceProperty().SetColor(0.6,0.6,0.2)
            self.ClipWidget.GetFaceProperty().SetOpacity(0.25)
        elif self.WidgetType == "sphere":
            self.ClipWidget = vtk.vtkSphereWidget()
            self.ClipWidget.GetSphereProperty().SetColor(0.6,0.6,0.2)
            self.ClipWidget.GetSphereProperty().SetOpacity(0.25)
            self.ClipWidget.GetSelectedSphereProperty().SetColor(0.6,0.0,0.0)
            self.ClipWidget.GetSelectedSphereProperty().SetOpacity(0.75)
            self.ClipWidget.SetRepresentationToSurface()
            self.ClipWidget.SetPhiResolution(20)
            self.ClipWidget.SetThetaResolution(20)

        self.ClipWidget.SetInteractor(self.vmtkRenderer.RenderWindowInteractor)
        self.Display()

        self.Transform = vtk.vtkTransform()
        self.ClipWidget.GetTransform(self.Transform)

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

        if self.CleanOutput == 1:
            cleaner = vtk.vtkCleanPolyData()
            cleaner.SetInput(self.Surface)
            cleaner.Update()
            self.Surface = cleaner.GetOutput()

        if self.Surface.GetSource():
            self.Surface.GetSource().UnRegisterAllOutputs()
Esempio n. 7
0
def Execute(Surface, cl):
    if Surface == None:
        print 'Error: no Surface.'
        sys.exit(0)

    # Initialize
    Clipper = vtk.vtkClipPolyData()
    Clipper.SetInput(Surface)
    Clipper.GenerateClippedOutputOn()
    Clipper.SetInsideOut(0)
 
    ClipFunction = vtk.vtkPlanes()
       
    Clipper.SetClipFunction(ClipFunction)

    Cutter = vtk.vtkCutter()
    Cutter.SetInput(Surface)
    Cutter.SetCutFunction(ClipFunction)

    ClippedSurface = vtk.vtkPolyData()
    CutLines = vtk.vtkPolyData()

    ClipWidget = vtk.vtkBoxWidget()
    ClipWidget.GetFaceProperty().SetColor(0.6,0.6,0.2)
    ClipWidget.GetFaceProperty().SetOpacity(0.25)

    Transform = vtk.vtkTransform()
    ClipWidget.GetTransform(Transform)

    for i in range(cl.GetNumberOfLines()):
        # TODO: Implement thing here.

    # Clean surface
    cleaner = vtk.vtkCleanPolyData()
    cleaner.SetInput(Surface)
    cleaner.Update()
    Surface = cleaner.GetOutput()

    cleaner = vtk.vtkCleanPolyData()
    cleaner.SetInput(ClippedSurface)
    cleaner.Update()
    ClippedSurface = cleaner.GetOutput()

    cleaner = vtk.vtkCleanPolyData()
    cleaner.SetInput(CutLines)
    cleaner.Update()
    stripper = vtk.vtkStripper()
    stripper.SetInput(cleaner.GetOutput())
    stripper.Update()
    CutLines = stripper.GetOutput()

    if Surface.GetSource():
        Surface.GetSource().UnRegisterAllOutputs()


if __name__=='__main__':
    surface = read_command_line()
    Execute()
Esempio n. 8
0
    def processVerticalScalingCommand(self, args, config_function):
        #        print "processVerticalScalingCommand: ", str(args)
        verticalScale = config_function.value
        if args and args[0] == "StartConfig":
            ispec = self.inputSpecs[0]
            wbounds = ispec.getDataBounds()
            self.zscaleBoxWidget = vtk.vtkBoxWidget()
            self.zscaleBoxWidget.SetInteractor(self.renderWindowInteractor)
            self.zscaleBoxWidget.SetPlaceFactor(1.0)
            self.zscaleBoxWidget.HandlesOff()
            self.zscaleBoxWidget.SetEnabled(1)
            oprop = self.zscaleBoxWidget.GetOutlineProperty()
            oprop.SetColor(0.0, 0.0, 0.0)
            oprop.SetLineWidth(2.0)
            self.zscaleBoxWidget.On()
            self.zscaleBoxWidget.PlaceWidget(wbounds)
#            print "  >>>>>>>>>>>>>>>>>>>>> Place box widget: ", str( wbounds )
        elif args and args[0] == "Init":
            self.parameter_initializing = True
            ispec = self.inputSpecs[0]
            zsval = config_function.initial_value
            #             plotType = ispec.getMetadata('plotType')
            #             if plotType == 'xyt':
            #                 tval = ispec.getMetadata('time')
            #                 if tval: zsval = 10.0 / len( tval )
            #             else:
            #                 lval = ispec.getMetadata('lev')
            #                 if tval: zsval = 10.0 / len( lval )
            #             verticalScale.setValues( [ zsval ] )
            self.setZScale(zsval)
            verticalScale.setValue('count', 1)
            self.parameter_initializing = False
        elif args and args[0] == "EndConfig":
            vscale = verticalScale.getValues()
            self.setZScale(vscale)
            self.zscaleBoxWidget.Off()
            self.zscaleBoxWidget.SetEnabled(0)
            self.zscaleBoxWidget = None
            self.processConfigParameterChange(verticalScale)
        elif args and args[0] == "InitConfig":
            self.updateTextDisplay(config_function.label)
            bbar = self.getInteractionButtons()
            self.skipIndex = 2
            for islider in range(4):
                bbar.setSliderVisibility(
                    islider, islider < len(config_function.sliderLabels))
        elif args and args[0] == "Open":
            pass
        elif args and args[0] == "Close":
            pass
        elif args and args[0] == "UpdateConfig":
            ispec = self.inputSpecs[0]
            vscale = args[2].GetValue()
            verticalScale.setValues([vscale])
            wbounds = ispec.getDataBounds(zscale=vscale)
            self.zscaleBoxWidget.PlaceWidget(wbounds)
    def Execute(self):

        if (self.Surface == None):
            self.PrintError('Error: no Surface.')

        if self.WidgetType == "box":
            self.ClipFunction = vtk.vtkPlanes()
        elif self.WidgetType == "sphere":
            self.ClipFunction = vtk.vtkSphere()

        self.Clipper = vtk.vtkClipPolyData()
        self.Clipper.SetInput(self.Surface)
        self.Clipper.SetClipFunction(self.ClipFunction)
        self.Clipper.GenerateClippedOutputOn()
        self.Clipper.InsideOutOn()

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

        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInput(self.Surface)
        mapper.ScalarVisibilityOff()
        self.Actor = vtk.vtkActor()
        self.Actor.SetMapper(mapper)
        self.vmtkRenderer.Renderer.AddActor(self.Actor)

        if self.WidgetType == "box":
            self.ClipWidget = vtk.vtkBoxWidget()
            self.ClipWidget.GetFaceProperty().SetColor(0.6, 0.6, 0.2)
            self.ClipWidget.GetFaceProperty().SetOpacity(0.25)
        elif self.WidgetType == "sphere":
            self.ClipWidget = vtk.vtkSphereWidget()
            self.ClipWidget.GetSphereProperty().SetColor(0.6, 0.6, 0.2)
            self.ClipWidget.GetSphereProperty().SetOpacity(0.25)
            self.ClipWidget.GetSelectedSphereProperty().SetColor(0.6, 0.0, 0.0)
            self.ClipWidget.GetSelectedSphereProperty().SetOpacity(0.75)
            self.ClipWidget.SetRepresentationToSurface()
            self.ClipWidget.SetPhiResolution(20)
            self.ClipWidget.SetThetaResolution(20)

        self.ClipWidget.SetInteractor(self.vmtkRenderer.RenderWindowInteractor)
        self.Display()

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

        if self.CleanOutput == 1:
            cleaner = vtk.vtkCleanPolyData()
            cleaner.SetInput(self.Surface)
            cleaner.Update()
            self.Surface = cleaner.GetOutput()

        if self.Surface.GetSource():
            self.Surface.GetSource().UnRegisterAllOutputs()
Esempio n. 10
0
 def createContent( self ):
     input =  self.module.inputModule.getOutput()  
     self.boxWidget = vtk.vtkBoxWidget()
     self.boxWidget.SetRotationEnabled(0)
     self.boxWidget.SetPlaceFactor(1.0)
     self.boxWidget.SetInput( input )
     self.planes = vtk.vtkPlanes()
     self.boxWidget.AddObserver("StartInteractionEvent", self.startConfiguration )
     self.boxWidget.AddObserver("InteractionEvent",      self.updateConfiguration )
     self.boxWidget.AddObserver("EndInteractionEvent",   self.endConfiguration ) 
Esempio n. 11
0
	def __init__(self):
		super(ClippingBox, self).__init__()
		self.widget = None

		self.clippingBox = vtkBoxWidget()
		self.planes = [vtkImagePlaneWidget() for _ in range(6)]
		self.transform = vtkTransform()  # For future functionality

		self._clippingBoxState = False
		self._clippingPlanesState = False
Esempio n. 12
0
    def __init__( self, parent, imode_callback, rmode_callback, ppos_callback, ao, **kwargs ):
        # initialize Panel
        if 'id' not in kwargs:
            kwargs['id'] = wx.ID_ANY
        wx.Panel.__init__( self, parent, **kwargs )

        self.setInteractionMode = imode_callback
        self.setInteractionMode(True)
        
        self.recordingMode = False
        self.setRecordingMode = rmode_callback
        self.setRecordingMode(False)
        
        self.setPickerPos = ppos_callback
        
        self.ao = ao
        self.aa = False
        self.firstRender = True

        self.vtkWidget = wxVTKRenderWindowInteractor(self, wx.ID_ANY)
        self.iren = self.vtkWidget._Iren
        self.iren.SetInteractorStyle(vtk.vtkInteractorStyleTrackballCamera())
        
        self.renderer = vtk.vtkRenderer()
        self.renderer.SetBackground(0,0,0)
        self.imageLayer = {}
        self.CISID = -1  # Current Image Set ID
        self.imageLayer[self.CISID] = IBCRenderer(self.renderer, self.iren.Render)
        self.bacteriaLayer = BacteriaLayer(self.renderer, self.iren.Render)
        
        self.viewCamActive = True
        
        # for interactive clipping
        self.planes = vtk.vtkPlanes()
        
        self.ellipsoid = None
        self.ellipsoidTextActor = None
        
        # The SetInteractor method is how 3D widgets are associated with the
        # render window interactor. Internally, SetInteractor sets up a bunch
        # of callbacks using the Command/Observer mechanism (AddObserver()).
        self.boxWidget = vtk.vtkBoxWidget()
        self.boxWidget.SetInteractor(self.iren)
        self.boxWidget.SetPlaceFactor(1.0)

        # init vtk window
        self.vtkWidget.Enable(1)
        self.vtkWidget.AddObserver("ExitEvent", lambda o,e,f=parent: f.Close())
        self.vtkWidget.GetRenderWindow().AddRenderer(self.renderer)
        
        # Bind VTK events
        self.iren.AddObserver("KeyPressEvent", self.OnKeyDown)
        
        self.Sizer = wx.BoxSizer()
        self.Sizer.Add(self.vtkWidget, 1, wx.EXPAND)
Esempio n. 13
0
    def processVerticalScalingCommand( self, args, config_function ):
#        print "processVerticalScalingCommand: ", str(args)
        verticalScale = config_function.value
        if args and args[0] == "StartConfig":
            ispec = self.inputSpecs[ 0 ]
            wbounds = ispec.getDataBounds()
            self.zscaleBoxWidget = vtk.vtkBoxWidget()
            self.zscaleBoxWidget.SetInteractor( self.renderWindowInteractor )
            self.zscaleBoxWidget.SetPlaceFactor(1.0)
            self.zscaleBoxWidget.HandlesOff()
            self.zscaleBoxWidget.SetEnabled(1)
            oprop = self.zscaleBoxWidget.GetOutlineProperty()
            oprop.SetColor( 0.0, 0.0, 0.0 )
            oprop.SetLineWidth( 2.0 )
            self.zscaleBoxWidget.On()
            self.zscaleBoxWidget.PlaceWidget(wbounds)
#            print "  >>>>>>>>>>>>>>>>>>>>> Place box widget: ", str( wbounds )
        elif args and args[0] == "Init":
            self.parameter_initializing = True
            ispec = self.inputSpecs[ 0 ]
            zsval = config_function.initial_value
#             plotType = ispec.getMetadata('plotType')
#             if plotType == 'xyt':
#                 tval = ispec.getMetadata('time')
#                 if tval: zsval = 10.0 / len( tval )
#             else:
#                 lval = ispec.getMetadata('lev')
#                 if tval: zsval = 10.0 / len( lval )
#             verticalScale.setValues( [ zsval ] )
            self.setZScale( zsval  )
            verticalScale.setValue( 'count', 1 )
            self.parameter_initializing = False
        elif args and args[0] == "EndConfig":
            vscale = verticalScale.getValues()
            self.setZScale( vscale )
            self.zscaleBoxWidget.Off()
            self.zscaleBoxWidget.SetEnabled(0)
            self.zscaleBoxWidget = None
            self.processConfigParameterChange( verticalScale )
        elif args and args[0] == "InitConfig":
            self.updateTextDisplay( config_function.label )
            bbar = self.getInteractionButtons()
            self.skipIndex = 2
            for islider in range(4): bbar.setSliderVisibility(  islider, islider < len(config_function.sliderLabels)  )
        elif args and args[0] == "Open":
            pass
        elif args and args[0] == "Close":
            pass
        elif args and args[0] == "UpdateConfig":
            ispec = self.inputSpecs[ 0 ]
            vscale = args[2].GetValue()
            verticalScale.setValues( [ vscale ] )
            wbounds = ispec.getDataBounds( zscale=vscale )
            self.zscaleBoxWidget.PlaceWidget( wbounds )
Esempio n. 14
0
File: body.py Progetto: ladisk/DyS
    def vtkCreateBoxWidget(self, interactor):
        """

        :param interactor:
        :return:
        """
        boxWidget = vtk.vtkBoxWidget()
        boxWidget.SetInteractor(interactor)
        boxWidget.SetProp3D(self.vtk_actor)
        boxWidget.SetPlaceFactor(1.) # Make the box 1.25x larger than the actor
        boxWidget.PlaceWidget()
        boxWidget.On()
Esempio n. 15
0
	def setImageData(self, imageData):
		self.transformBox = vtkBoxWidget()
		self.transformBox.SetInteractor(self.widget.rwi)
		self.transformBox.SetPlaceFactor(1.01)
		self.transformBox.SetInputData(imageData)
		self.transformBox.SetDefaultRenderer(self.widget.rendererOverlay)
		self.transformBox.InsideOutOn()
		self.transformBox.PlaceWidget()

		self.AddObserver(self.transformBox, "InteractionEvent", self.transformCallback)
		self.transformBox.GetSelectedFaceProperty().SetOpacity(0.3)
		self.transformBox.EnabledOn()
Esempio n. 16
0
    def __init__(self, data_dir, reader):

        tfun = vtk.vtkPiecewiseFunction()
        tfun.AddPoint(2440.0, 0.0)
        tfun.AddPoint(2800.0, 0.85)

        ctfun = vtk.vtkColorTransferFunction()
        ctfun.AddRGBPoint(0.0, 0.5, 0.0, 0.0)
        ctfun.AddRGBPoint(600.0, 1.0, 0.5, 0.5)
        ctfun.AddRGBPoint(1280.0, 0.9, 0.2, 0.3)
        ctfun.AddRGBPoint(1960.0, 0.81, 0.27, 0.1)
        ctfun.AddRGBPoint(4095.0, 0.5, 0.5, 0.5)

        volumeMapper = vtk.vtkGPUVolumeRayCastMapper()
        volumeMapper.SetInputConnection(reader.GetOutputPort())
        volumeMapper.SetBlendModeToComposite()

        volumeProperty = vtk.vtkVolumeProperty()
        #volumeProperty.SetColor(ctfun)
        volumeProperty.SetScalarOpacity(tfun)
        volumeProperty.SetInterpolationTypeToLinear()
        #volumeProperty.ShadeOn()

        newvol = vtk.vtkVolume()
        newvol.SetMapper(volumeMapper)
        newvol.SetProperty(volumeProperty)
        # The SetInteractor method is how 3D widgets are associated with the
        # render window interactor. Internally, SetInteractor sets up a bunch
        # of callbacks using the Command/Observer mechanism (AddObserver()).
        boxWidget = vtk.vtkBoxWidget()
        #boxWidget.SetInteractor(iren)
        boxWidget.SetPlaceFactor(1.0)

        # The implicit function vtkPlanes is used in conjunction with the
        # volume ray cast mapper to limit which portion of the volume is
        # volume rendered.
        planes = vtk.vtkPlanes()
        self.planes = planes

        def ClipVolumeRender(obj, event):
            #global self.planes, volumeMapper
            obj.GetPlanes(self.planes)
            volumeMapper.SetClippingPlanes(self.planes)

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

        boxWidget.AddObserver("InteractionEvent", ClipVolumeRender)
        self.boxWidget = boxWidget
Esempio n. 17
0
    def move_stl2(self):
        if self.move_button.isChecked():
            self.state_moving()

            # self.interactor.SetInteractorStyle(self.actor_interactor_style)

            self.axesWidget.SetEnabled(False)
            if self.boxWidget is None:
                self.boxWidget = vtk.vtkBoxWidget()
                self.boxWidget.SetInteractor(self.interactor)
                # self.boxWidget.SetProp3D(self.stlActor)
                self.boxWidget.SetPlaceFactor(1.25)
                self.boxWidget.SetHandleSize(0.005)
                self.boxWidget.SetEnabled(True)
                self.boxWidget.SetScalingEnabled(False)

                # hack for boxWidget - 1. reset actor transform
                # 2. place boxWidget
                # 3. apply transform to actor and boxWidget
                tf = self.stlActor.GetUserTransform()
                self.stlActor.SetUserTransform(vtk.vtkTransform())
                self.boxWidget.SetProp3D(self.stlActor)
                self.boxWidget.PlaceWidget()
                self.boxWidget.SetTransform(tf)
                self.stlActor.SetUserTransform(tf)

                def TransformActor(obj, event):
                    tf = vtk.vtkTransform()
                    obj.GetTransform(tf)
                    # print(tf.GetScale())
                    self.stlActor.SetUserTransform(tf)
                    self.updateTransform()

                self.boxWidget.AddObserver("InteractionEvent", TransformActor)
            else:
                self.boxWidget.SetEnabled(True)
            # self.interactor.GetInteractorStyle().SetCurrentStyleToTrackballActor()
        else:
            self.state_stl()  # TODO: might be not stl but both or gcode
            # self.interactor.SetInteractorStyle(self.camera_interactor_style)
            self.boxWidget.SetEnabled(False)
            self.axesWidget.SetEnabled(True)
            xc, yc, zmin = gui_utils.findStlOrigin(self.stlActor)
            tf = self.stlActor.GetUserTransform()
            tf.PostMultiply()
            tf.Translate(0, 0, -zmin)
            self.stlActor.SetUserTransform(tf)
            self.boxWidget.SetTransform(tf)
            self.updateTransform()
            # self.interactor.GetInteractorStyle().SetCurrentStyleToTrackballCamera()
        self.reload_scene()
Esempio n. 18
0
 def __init__(self, actorlist, volumelist):
     self.render = vtk.vtkRenderer()
     self.renWindow = vtk.vtkRenderWindow()
     self.renWindow.AddRenderer(self.render)
     self.interactor = vtk.vtkRenderWindowInteractor()
     self.interactor.SetRenderWindow(self.renWindow)
     self.actorstoadd = actorlist
     self.volumestoadd = volumelist
     self.t = vtk.vtkTransform()
     self.box = vtk.vtkBoxWidget()
     self.planes = vtk.vtkPlanes()
     self.clipper = vtk.vtkClipPolyData()
     self.selectMapper = vtk.vtkPolyDataMapper()
     self.selectActor = vtk.vtkLODActor()
    def __init__(self):
        '''
        Constructor
        '''
        vtkPythonViewImage.__init__(self)
        
#        texture mapper in 3D: vtkVolumeMapper
        self.__VolumeMapper = None
#        texture mapper in 3D: vtkVolumeTextureMapper3D
        self.__VolumeTextureMapper = vtk.vtkVolumeTextureMapper3D()
#        volume ray cast mapper vtkFixedPointVolumeRayCastMapper
        self.__VolumeRayCastMapper = vtk.vtkFixedPointVolumeRayCastMapper()
#        volume property: vtkVolumeProperty
        self.__VolumeProperty = vtk.vtkVolumeProperty()
#        volume actor: vtkVolume
        self.__VolumeActor = vtk.vtkVolume()
#        opacity transfer function: vtkPiecewiseFunction
        self.__OpacityFunction = vtk.vtkPiecewiseFunction()
#        color transfer function: vtkColorTransferFunction
        self.__ColorFunction = vtk.vtkColorTransferFunction()
        
#        vtkProp3DCollection
        self.__PhantomCollection = vtk.vtkProp3DCollection()
#        blender: vtkImageBlend
        self.__Blender = None
        
#        image 3D cropping box callback: vtkImage3DCroppingBoxCallback
        self.__Callback = vtkPythonImage3DCroppingBoxCallback()
#        box widget: vtkOrientedBoxWidget
#        self.__BoxWidget = vtkOrientedBoxWidget()    # Now I could not wrap vtkOrientedBoxWidget
        self.__BoxWidget = vtk.vtkBoxWidget()
#        vtkPlane widget: vtkPlaneWidget
        self.__PlaneWidget = vtk.vtkPlaneWidget()
#        annotated cube actor: vtkAnnotatedCubeActor, vtkOrientationMarkerWidget
        self.__Cube = vtk.vtkAnnotatedCubeActor()
        self.__Marker = vtk.vtkOrientationMarkerWidget()
        
        self.SetupVolumeRendering()
        self.SetupWidgets()
        
        self.ShowAnnotationsOn()
        self.getTextProperty().SetColor(0, 0, 0)
        self.SetBackground(0.9, 0.9, 0.9) # white
        
        self.__FirstRender = 1
        self.__RenderingMode = self.PLANAR_RENDERING
        self.__VRQuality = 1
        
        self.__InteractorStyleSwitcher = None
    def initBoxWidget(self):
        self.boxWidget = vtk.vtkBoxWidget()
        self.boxWidget.SetInteractor(self.iren)
        self.boxWidget.SetProp3D(self.volume)
        self.boxWidget.SetPlaceFactor(1.25)
        self.boxWidget.PlaceWidget(self.boxWidget.GetProp3D().GetBounds())
        self.boxWidget.SetRotationEnabled(0)
        self.boxWidget.AddObserver("InteractionEvent", self.sliceCubevolum)
        self.boxWidget.GetOutlineProperty().SetOpacity(0.1)
        self.boxWidget.GetOutlineProperty().SetColor(0, 0, 0.3)
        self.boxWidget.On()
        self.volumMapper.SetCropping(1)  # 开启3D剪切模式
        self.volumMapper.SetCroppingRegionPlanes(
            self.boxWidget.GetProp3D().GetBounds())

        pass
Esempio n. 21
0
def box():
    colors = vtk.vtkNamedColors()

    # Create a Cone
    cone = vtk.vtkConeSource()
    cone.SetResolution(20)
    coneMapper = vtk.vtkPolyDataMapper()
    coneMapper.SetInputConnection(cone.GetOutputPort())
    coneActor = vtk.vtkActor()
    coneActor.SetMapper(coneMapper)
    coneActor.GetProperty().SetColor(colors.GetColor3d('BurlyWood'))

    # A renderer and render window
    renderer = vtk.vtkRenderer()
    renderer.SetBackground(colors.GetColor3d('Blue'))
    renderer.AddActor(coneActor)

    renwin = vtk.vtkRenderWindow()
    renwin.AddRenderer(renderer)
    

    # An interactor
    interactor = vtk.vtkRenderWindowInteractor()
    #interactor = vtk.vtkGenericRenderWindowInteractor()
    interactor.SetRenderWindow(renwin)

    # A Box widget
    boxWidget = vtk.vtkBoxWidget()
    boxWidget.SetInteractor(interactor)
    boxWidget.SetProp3D(coneActor)
    boxWidget.SetPlaceFactor(1.25)  # Make the box 1.25x larger than the actor
    boxWidget.PlaceWidget()
    boxWidget.On()

    # Connect the event to a function
    # This call makes cone move and stretch with the box.
    # See complete list of event at 
    # https://vtk.org/doc/nightly/html/vtkCommand_8h_source.html
    boxWidget.AddObserver('InteractionEvent', boxCallback)

    # Start
    interactor.Initialize()
    renwin.SetWindowName('BoxWidget')
    renwin.Render()
    interactor.Start()
Esempio n. 22
0
def createBoxWidget(image, iren):
    boxWidget = vtk.vtkBoxWidget()
    boxWidget.SetInteractor(iren)
    boxWidget.SetPlaceFactor(1.0)
    boxWidget.SetInput(image)
    boxWidget.PlaceWidget()
    boxWidget.InsideOutOn()
    outlineProperty = boxWidget.GetOutlineProperty()
    outlineProperty.SetRepresentationToWireframe()
    outlineProperty.SetAmbient(1.0)
    outlineProperty.SetAmbientColor(0, 0, 0)
    outlineProperty.SetLineWidth(2)
    selectedOutlineProperty = boxWidget.GetSelectedOutlineProperty()
    selectedOutlineProperty.SetRepresentationToWireframe()
    selectedOutlineProperty.SetAmbient(1.0)
    selectedOutlineProperty.SetAmbientColor(1, 0, 0)
    selectedOutlineProperty.SetLineWidth(3)
    return boxWidget
Esempio n. 23
0
    def Execute(self):

        if self.Image == None:
            self.PrintError('Error: no Image.')

        self.CroppedImage.DeepCopy(self.Image)

        if self.Interactive == 1:

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

            self.vmtkRenderer.RegisterScript(self)
            self.PlaneWidgetX = vtkvmtk.vtkvmtkImagePlaneWidget()
            self.PlaneWidgetX.SetInteractor(
                self.vmtkRenderer.RenderWindowInteractor)
            self.PlaneWidgetY = vtkvmtk.vtkvmtkImagePlaneWidget()
            self.PlaneWidgetY.SetInteractor(
                self.vmtkRenderer.RenderWindowInteractor)
            self.PlaneWidgetZ = vtkvmtk.vtkvmtkImagePlaneWidget()
            self.PlaneWidgetZ.SetInteractor(
                self.vmtkRenderer.RenderWindowInteractor)
            self.BoxWidget = vtk.vtkBoxWidget()
            self.BoxWidget.SetInteractor(
                self.vmtkRenderer.RenderWindowInteractor)

            self.vmtkRenderer.AddKeyBinding('i', 'Interact.',
                                            self.InteractCallback)
            self.InputInfo("Press 'i' to activate interactor")

            self.Display()
            while (self.BoxActive == 1):
                self.ExtractVOI()
                self.Image = self.CroppedImage
                self.Display()
        else:
            self.ExtractVOI()

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

        self.Image = self.CroppedImage
Esempio n. 24
0
    def Execute(self):

        if (self.Mesh == None):
            self.PrintError('Error: no Mesh.')

        self.Planes = vtk.vtkPlanes()
        self.Clipper = vtk.vtkClipDataSet()
        self.Clipper.SetInput(self.Mesh)
        self.Clipper.SetClipFunction(self.Planes)
        self.Clipper.GenerateClippedOutputOn()
        self.Clipper.InsideOutOn()

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

        self.vmtkRenderer.RegisterScript(self)

        mapper = vtk.vtkDataSetMapper()
        mapper.SetInput(self.Mesh)
        mapper.ScalarVisibilityOff()
        self.Actor = vtk.vtkActor()
        self.Actor.SetMapper(mapper)
        self.vmtkRenderer.Renderer.AddActor(self.Actor)

        self.BoxWidget = vtk.vtkBoxWidget()
        self.BoxWidget.SetInteractor(self.vmtkRenderer.RenderWindowInteractor)
        self.BoxWidget.GetFaceProperty().SetColor(0.6, 0.6, 0.2)
        self.BoxWidget.GetFaceProperty().SetOpacity(0.25)

        self.vmtkRenderer.AddKeyBinding('i', 'Interact.',
                                        self.InteractCallback)
        self.vmtkRenderer.AddKeyBinding('space', 'Clip.', self.ClipCallback)

        self.Display()

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

        if self.Mesh.GetSource():
            self.Mesh.GetSource().UnRegisterAllOutputs()
Esempio n. 25
0
    def Execute(self):

        if (self.Mesh == None):
            self.PrintError('Error: no Mesh.')

        self.Planes = vtk.vtkPlanes()
        self.Clipper = vtk.vtkClipDataSet()
        self.Clipper.SetInput(self.Mesh)
        self.Clipper.SetClipFunction(self.Planes)
        self.Clipper.GenerateClippedOutputOn()
        self.Clipper.InsideOutOn()
        
        if not self.vmtkRenderer:
            self.vmtkRenderer = vmtkrenderer.vmtkRenderer()
            self.vmtkRenderer.Initialize()
            self.OwnRenderer = 1

        self.vmtkRenderer.RegisterScript(self) 

        mapper = vtk.vtkDataSetMapper()
        mapper.SetInput(self.Mesh)
        mapper.ScalarVisibilityOff()
        self.Actor = vtk.vtkActor()
        self.Actor.SetMapper(mapper)
        self.vmtkRenderer.Renderer.AddActor(self.Actor)

        self.BoxWidget = vtk.vtkBoxWidget()
        self.BoxWidget.SetInteractor(self.vmtkRenderer.RenderWindowInteractor)
        self.BoxWidget.GetFaceProperty().SetColor(0.6,0.6,0.2)
        self.BoxWidget.GetFaceProperty().SetOpacity(0.25)

        self.vmtkRenderer.AddKeyBinding('i','Interact.', self.InteractCallback)
        self.vmtkRenderer.AddKeyBinding('space','Clip.', self.ClipCallback)

        self.Display()

        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
        
        if self.Mesh.GetSource():
            self.Mesh.GetSource().UnRegisterAllOutputs()
Esempio n. 26
0
File: Main.py Progetto: cliburn/flow
 def OnBox(self, event):
     boxWidget = vtk.vtkBoxWidget()
     # change handle properties
     boxWidget.SetHandleSize(0.005) # default is 0.01
     boxWidget.SetInteractor(self.widget)
     boxWidget.SetPlaceFactor(1.25)
     boxWidget.SetInput(self.normals.GetOutput())
     boxWidget.PlaceWidget()
     boxCallback = self.BoxSelectPolygons()
     boxWidget.AddObserver("EndInteractionEvent", boxCallback)
     boxWidget.KeyPressActivationOff()
     plane = vtk.vtkPlanes()
     self.boxes.append(boxWidget)
     self.planes[boxWidget.GetAddressAsString('')] = plane
     self.region.AddFunction(plane)
     newId = self.GateMenu.AppendCheckItem(-1, "Box #" + str(self.boxCount))
     self.boxCount = self.boxCount + 1
     self.boxIds[newId.GetId()] = boxWidget.GetAddressAsString('')
     newId.Check(True)
     self.Bind(wx.EVT_MENU, self.OnBoxSelect, newId)
     boxWidget.On()
Esempio n. 27
0
def main():
    colors = vtk.vtkNamedColors()

    # Create a Cone
    cone = vtk.vtkConeSource()
    cone.SetResolution(20)
    coneMapper = vtk.vtkPolyDataMapper()
    coneMapper.SetInputConnection(cone.GetOutputPort())
    coneActor = vtk.vtkActor()
    coneActor.SetMapper(coneMapper)
    coneActor.GetProperty().SetColor(colors.GetColor3d('BurlyWood'))

    # A renderer and render window
    renderer = vtk.vtkRenderer()
    renderer.SetBackground(colors.GetColor3d('Blue'))
    renderer.AddActor(coneActor)

    renwin = vtk.vtkRenderWindow()
    renwin.AddRenderer(renderer)
    renwin.SetWindowName('BoxWidget')

    # An interactor
    interactor = vtk.vtkRenderWindowInteractor()
    interactor.SetRenderWindow(renwin)

    # A Box widget
    boxWidget = vtk.vtkBoxWidget()
    boxWidget.SetInteractor(interactor)
    boxWidget.SetProp3D(coneActor)
    boxWidget.SetPlaceFactor(1.25)  # Make the box 1.25x larger than the actor
    boxWidget.PlaceWidget()
    boxWidget.On()

    # Connect the event to a function
    boxWidget.AddObserver('InteractionEvent', boxCallback)

    # Start
    interactor.Initialize()
    renwin.Render()
    interactor.Start()
Esempio n. 28
0
def _addVolumeCutterTool(vol):
    vp = settings.plotter_instance
    if not vp.renderer:
        save_int = vp.interactive
        vp.show(interactive=0)
        vp.interactive = save_int

    boxWidget = vtk.vtkBoxWidget()
    boxWidget.SetInteractor(vp.interactor)
    boxWidget.SetPlaceFactor(1.0)

    vp.cutterWidget = boxWidget

    planes = vtk.vtkPlanes()

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

    boxWidget.SetInputData(vol.image)
    boxWidget.OutlineCursorWiresOn()
    boxWidget.GetSelectedOutlineProperty().SetColor(1, 0, 1)
    boxWidget.GetOutlineProperty().SetColor(0.1, 0.1, 0.1)
    boxWidget.GetOutlineProperty().SetOpacity(0.7)
    boxWidget.SetPlaceFactor(1.05)
    boxWidget.PlaceWidget()
    boxWidget.InsideOutOn()
    boxWidget.AddObserver("InteractionEvent", ClipVolumeRender)

    colors.printc("Mesh Cutter Tool:", c="m", invert=1)
    colors.printc("  Move gray handles to cut away parts of the mesh", c="m")
    colors.printc("  Press X to save file to: clipped.vtk", c="m")

    vp.renderer.ResetCamera()
    boxWidget.On()

    vp.interactor.Start()
    boxWidget.Off()
    vp.widgets.append(boxWidget)
Esempio n. 29
0
    def __init__(self, parent, visualizer, **kws):
        """
		Initialization
		"""
        self.boxWidget = None
        VisualizationModule.__init__(self, parent, visualizer, **kws)

        self.descs = {
            "ShowControls": "Show controls",
            "ClippedModule": "Module to clip",
            "AllModules": "Clip all modules",
            "InsideOut": "Clip from outside"
        }
        boxWidget = self.boxWidget = vtk.vtkBoxWidget()
        self.cut = 0

        self.clippedMappers = []

        self.renderer = self.parent.getRenderer()
        iactor = parent.wxrenwin.GetRenderWindow().GetInteractor()
        self.boxWidget.SetInteractor(iactor)
        self.boxWidget.SetPlaceFactor(1.0)

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

        selectedOutlineProperty = boxWidget.GetSelectedOutlineProperty()
        selectedOutlineProperty.SetRepresentationToWireframe()
        selectedOutlineProperty.SetAmbient(1.0)
        selectedOutlineProperty.SetAmbientColor(1, 0, 0)
        selectedOutlineProperty.SetLineWidth(3)
        #        iactor = self.wxrenwin.GetRenderWindow().GetInteractor()
        boxWidget.AddObserver("InteractionEvent", self.clipVolumeRender)
        self.renew = 0
        self.filterDesc = "Clip rendering using a box"
	def __init__(self, parent, visualizer, **kws):
		"""
		Initialization
		"""
		self.boxWidget = None
		VisualizationModule.__init__(self, parent, visualizer, **kws)   

		self.descs = {"ShowControls": "Show controls",
					  "ClippedModule": "Module to clip",
					  "AllModules": "Clip all modules",
					  "InsideOut": "Clip from outside"}
		boxWidget = self.boxWidget = vtk.vtkBoxWidget()
		self.cut = 0
	  
		self.clippedMappers = []

		self.renderer = self.parent.getRenderer()
		iactor = parent.wxrenwin.GetRenderWindow().GetInteractor()
		self.boxWidget.SetInteractor(iactor)
		self.boxWidget.SetPlaceFactor(1.0)
		
		outlineProperty = boxWidget.GetOutlineProperty()
		outlineProperty.SetRepresentationToWireframe()
		outlineProperty.SetAmbient(1.0)
		outlineProperty.SetAmbientColor(1, 1, 1)
		outlineProperty.SetLineWidth(3)
		
		selectedOutlineProperty = boxWidget.GetSelectedOutlineProperty()
		selectedOutlineProperty.SetRepresentationToWireframe()
		selectedOutlineProperty.SetAmbient(1.0)
		selectedOutlineProperty.SetAmbientColor(1, 0, 0)
		selectedOutlineProperty.SetLineWidth(3)
#        iactor = self.wxrenwin.GetRenderWindow().GetInteractor()
		boxWidget.AddObserver("InteractionEvent", self.clipVolumeRender)
		self.renew = 0
		self.filterDesc = "Clip rendering using a box"
Esempio n. 31
0
    def Execute(self):

        if self.Mesh == None:
            self.PrintError("Error: no Mesh.")

        self.Clipper = vtk.vtkClipDataSet()
        self.Clipper.SetInput(self.Mesh)
        self.Clipper.GenerateClippedOutputOn()
        self.Clipper.SetInsideOut(self.InsideOut)

        if self.Interactive:

            self.Planes = vtk.vtkPlanes()
            self.Clipper.SetClipFunction(self.Planes)

            self.Cutter = vtk.vtkCutter()
            self.Cutter.SetInput(self.Mesh)
            self.Cutter.SetCutFunction(self.Planes)

            self.ClippedMesh = vtk.vtkUnstructuredGrid()
            self.Surface = vtk.vtkPolyData()

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

            self.vmtkRenderer.RegisterScript(self)

            mapper = vtk.vtkDataSetMapper()
            mapper.SetInput(self.Mesh)
            mapper.ScalarVisibilityOff()
            self.Actor = vtk.vtkActor()
            self.Actor.SetMapper(mapper)
            self.vmtkRenderer.Renderer.AddActor(self.Actor)

            self.BoxWidget = vtk.vtkBoxWidget()
            self.BoxWidget.SetInteractor(self.vmtkRenderer.RenderWindowInteractor)
            self.BoxWidget.GetFaceProperty().SetColor(0.6, 0.6, 0.2)
            self.BoxWidget.GetFaceProperty().SetOpacity(0.25)

            self.vmtkRenderer.AddKeyBinding("i", "Interact.", self.InteractCallback)
            self.vmtkRenderer.AddKeyBinding("space", "Clip.", self.ClipCallback)

            self.Display()

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

        else:

            self.Mesh.GetPointData().SetActiveScalars(self.ClipArrayName)

            self.Clipper.GenerateClipScalarsOff()
            self.Clipper.SetValue(self.ClipValue)
            self.Clipper.Update()

            self.Cutter = vtk.vtkContourFilter()
            self.Cutter.SetInput(self.Mesh)
            self.Cutter.SetValue(0, self.ClipValue)
            self.Cutter.Update()

            self.Mesh = self.Clipper.GetOutput()
            self.Surface = self.Cutter.GetOutput()
            self.ClippedMesh = self.Clipper.GetClippedOutput()

        if self.Mesh.GetSource():
            self.Mesh.GetSource().UnRegisterAllOutputs()
    def __init__(self, file_list,spacing_list,feature_type,irad = 1.2, h_th=-200,
                 glyph_type='sphere', glyph_scale_factor=1,use_field_data=True, opacity_list=[],
                 color_list=[], lung=[]):

        assert feature_type == "ridge_line" or feature_type == "valley_line" \
        or feature_type == "ridge_surface" or feature_type == "valley_surface" \
        or feature_type == "vessel" or feature_type == "airway" \
        or feature_type == "fissure", "Invalid feature type"

        if feature_type == "airway":
          feature_type = "valley_line"
        elif feature_type == "vessel":
          feature_type = "ridge_line"
        elif feature_type == "fissure":
          feature_type = "ridge_surface"

        self.mapper_list = list()
        self.actor_list  = list()
        self.glyph_list  = list()
        self.glyph_type  = glyph_type
        self.file_list   = file_list
        self.spacing_list = spacing_list
        self.opacity_list = opacity_list
        self.irad = irad
        self.h_th = h_th
        self.color_list = color_list
        self.lung = lung
        self.use_field_data = use_field_data
        self.feature_type = feature_type
        self.normal_map=dict()
        self.normal_map['ridge_line'] = "hevec0"
        self.normal_map['valley_line'] = "hevec2"
        self.normal_map['ridge_surface'] = "hevec2"
        self.normal_map['valley_surface'] = "hevec0"
        self.strength_map=dict()
        self.strength_map['ridge_line'] = "h1"
        self.strength_map['valley_line'] = "h1"
        self.strength_map['ridge_surface'] = "h2"
        self.strength_map['valley_surface'] = "h0"

        if feature_type == 'ridge_line' or feature_type == 'valley_line':
            self.height = irad
            self.radius = 0.5
        elif feature_type == 'ridge_surface' or feature_type == 'valley_surface':
            self.height = 0.5
            self.radius = irad

        self.min_rad = 0.5
        self.max_rad = 6
        self.glyph_scale_factor = glyph_scale_factor

        self.capture_prefix = ""
        self.capture_count = 1
        self.image_count = 1

        # VTK Objects
        self.ren = vtk.vtkOpenGLRenderer()
        self.renWin = vtk.vtkRenderWindow()
        self.iren = vtk.vtkRenderWindowInteractor()

        # Volume rendering objects
        self.volumeActor = vtk.vtkVolume()
        self.volumeMapper = vtk.vtkVolumeRayCastMapper()
        #self.volumeMapper = vtk.vtkGPUVolumeRayCastMapper()

        # Variables for the interaction
        self.volume_loaded = False
        self.volume_added_to_renderer = False
        self.volume_size = [0,0,0]

        self.particles_loaded = False
        self.particles_added_to_renderer = False
        self.planeWidgetX = vtk.vtkImagePlaneWidget()
        self.planeWidgetY = vtk.vtkImagePlaneWidget()
        self.planeWidgetZ = vtk.vtkImagePlaneWidget()
        self.lastPlaneWidget = self.planeWidgetX
        self.lastPlaneWidgetIndex = 0
        self.planeWidgetLayer = [0,0,0]
        self.boxWidgetVolume = vtk.vtkBoxWidget()
        self.boxWidgetParticles = vtk.vtkBoxWidget()

        self.planesParticles = vtk.vtkPlanes()
        self.planesParticles.SetBounds(-10000,10000,-10000,10000,-10000,10000); # For some reason planes needs initializaiton
        self.planesVolume = vtk.vtkPlanes()
        self.planesVolume.SetBounds(-10000,10000,-10000,10000,-10000,10000); # For some reason planes needs initializaiton
Esempio n. 33
0
    def load_muscleSI(self, t_T2image, m_bounds, iren, ren, picker, xplane, yplane, zplane):
        """ load_muscleSI: Place automatically a widget over muscle location from file
        
        INPUTS:
        =======        
        images: (vtkImageData)   list of Input image to Transform
        OUTPUTS:
        =======
        muscleSI (float)    Signal intensity from muscle
        muscleSIcoords (float[3])            cords where Signal intensity from muscle is measured
        
        """
        ## Transform T2 img
#        loadDisplay = Display()
#        
#        # Proceed to build reference frame for display objects based on DICOM coords   
#        [t_T2image, transform_cube] = loadDisplay.dicomTransform(T2image, image_pos_pat, image_ori_pat)
#            
#        # Calculate the center of the volume
#        t_T2image.UpdateInformation() 
               
        print "\nBoxwidget placed..."
        #################################################################
        # The box widget observes the events invoked by the render window
        # interactor.  These events come from user interaction in the render
        # window.
        # Place the interactor initially. The output of the reader is used to
        # place the box widget.
        self.boxWidget = vtk.vtkBoxWidget()
        self.boxWidget.SetInteractor(iren)
        self.boxWidget.SetPlaceFactor(1)
        self.boxWidget.SetInput(t_T2image)
        self.boxWidget.ScalingEnabledOff()
        self.boxWidget.OutlineCursorWiresOn()                
                
        # Construct a bounding box
        bwidg = [0,0,0,0,0,0]     
        bwidg[0] = m_bounds[0]; bwidg[1] = m_bounds[1]; 
        bwidg[2] = m_bounds[2]; bwidg[3] = m_bounds[3];
        bwidg[4] = m_bounds[4]; bwidg[5] = m_bounds[5];
        self.bounds_muscleSI = bwidg
        print "\nbounds_muscleSI "
        print self.bounds_muscleSI

        # add to visualize        
        self.boxWidget.PlaceWidget( self.bounds_muscleSI )
        self.boxWidget.On()
        #iren.Start() 
        
        ############################# Do extract_muscleSI 
        print "\n Re-extract muscle VOI? "
        rexorNot=0
        rexorNot = int(raw_input('type 1 to Re-extract or anykey: '))
        
        if rexorNot == 1:
            # custom interaction
            self.picker = picker
            self.textMapper = vtk.vtkTextMapper()
            tprop = self.textMapper.GetTextProperty()
            tprop.SetFontFamilyToArial()
            tprop.SetFontSize(10)
            tprop.BoldOn()
            tprop.ShadowOn()
            tprop.SetColor(1, 0, 0)
                    
            self.textActor = vtk.vtkActor2D()
            self.textActor.VisibilityOff() 
            self.textActor.SetMapper(self.textMapper)
            ren.AddActor2D(self.textActor)
            picker.AddObserver("EndPickEvent", self.annotatePick)
            iren.Start()        
                    
            # Construct a bounding box
            bwidg = [0,0,0,0,0,0]     
            bwidg[0] = self.pickPos[0]; bwidg[1] = self.pickPos[0]+5; 
            bwidg[2] = self.pickPos[1]; bwidg[3] = self.pickPos[1]+5;
            bwidg[4] = self.pickPos[2]; bwidg[5] = self.pickPos[2]+5;
            self.bounds_muscleSI = bwidg
            print "\nbounds_muscleSI "
            print self.bounds_muscleSI
            
            self.boxWidget.PlaceWidget( self.bounds_muscleSI )
            # turn off planes
            xplane.Off()
            yplane.Off()
            self.boxWidget.On()            
            
        ##########
        ### Set image stencil for muscle
        # create a simple box VOI mask shape using previously found boundsPlane_preselected
        VOIStencil = vtk.vtkROIStencilSource()
        VOIStencil.SetShapeToBox()
        VOIStencil.SetBounds( self.bounds_muscleSI )    
        VOIStencil.SetInformationInput(t_T2image)
        VOIStencil.Update()
                                
        # cut the corresponding VOI region and set the background:
        extractVOI_imgstenc = vtk.vtkImageStencil()
        extractVOI_imgstenc.SetInput(t_T2image)
        extractVOI_imgstenc.SetStencil(VOIStencil.GetOutput())
        extractVOI_imgstenc.ReverseStencilOff()
        extractVOI_imgstenc.SetBackgroundValue(5000)
        extractVOI_imgstenc.Update()
            
        # take out average image
        finalmuscleSIIm = vtk.vtkImageData()
        finalmuscleSIIm = extractVOI_imgstenc.GetOutput()
        finalmuscleSIIm.Update()
                
        ## Display histogram 
        dims = finalmuscleSIIm .GetDimensions()
        scalars = finalmuscleSIIm.GetPointData().GetScalars()
        np_scalars = vtk_to_numpy(scalars)      
        np_scalars = np_scalars.reshape(dims[2], dims[1], dims[0]) 
        np_scalars = np_scalars.transpose(2,1,0)
        muscleSI = np_scalars[np_scalars<5000]
        print "ave. T2_muscleSI: %d" % mean(muscleSI)
        
        muscle_scalar_range = [muscleSI.min(), muscleSI.max()]
        print "\nMuscle scalar Range:"
        print muscle_scalar_range[0], muscle_scalar_range[1]
        
        return muscleSI, muscle_scalar_range, self.bounds_muscleSI
Esempio n. 34
0
coneMapper.SetInputConnection(cone.GetOutputPort())
coneActor = vtk.vtkActor()
coneActor.SetMapper(coneMapper)

# A renderer and render window
renderer = vtk.vtkRenderer()
renderer.SetBackground(0, 0, 1)
renderer.AddActor(coneActor)

renwin = vtk.vtkRenderWindow()
renwin.AddRenderer(renderer)
 
# An interactor
interactor = vtk.vtkRenderWindowInteractor()
interactor.SetRenderWindow(renwin)

# A Box widget
boxWidget = vtk.vtkBoxWidget()
boxWidget.SetInteractor(interactor)
boxWidget.SetProp3D(coneActor)
boxWidget.SetPlaceFactor( 1.25 ) # Make the box 1.25x larger than the actor
boxWidget.PlaceWidget()
boxWidget.On()

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

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

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

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

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

        # The mapper knows how to render the data

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

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

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

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

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

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

        self.volume.SetPosition(self.pos)

        self.renderer.AddVolume(self.volume)
        self.renderer.SetBackground(VTK_BACKGROUND_COLOR[0],
                                    VTK_BACKGROUND_COLOR[1],
                                    VTK_BACKGROUND_COLOR[2])
Esempio n. 36
0
    def add_box_widget(self,
                       callback,
                       bounds=None,
                       factor=1.25,
                       rotation_enabled=True,
                       color=None,
                       use_planes=False,
                       outline_translation=True,
                       pass_widget=False):
        """Add a box widget to the scene.

        This is useless without a callback function. You can pass a callable
        function that takes a single argument, the PolyData box output from
        this widget, and performs a task with that box.

        Parameters
        ----------
        callback : callable
            The method called every time the box is updated. This has two
            options: Take a single argument, the ``PolyData`` box (default) or
            if ``use_planes=True``, then it takes a single argument of the
            plane collection as a ``vtkPlanes`` object.

        bounds : tuple(float)
            Length 6 tuple of the bounding box where the widget is placed.

        factor : float, optional
            An inflation factor to expand on the bounds when placing

        rotation_enabled : bool
            If ``False``, the box widget cannot be rotated and is strictly
            orthogonal to the cartesian axes.

        color : string or 3 item list, optional, defaults to white
            Either a string, rgb list, or hex color string.

        use_planes : bool, optional
            Changes the arguments passed to the callback to the planes that
            make up the box.

        outline_translation : bool
            If ``False``, the box widget cannot be translated and is strictly
            placed at the given bounds.

        pass_widget : bool
            If true, the widget will be passed as the last argument of the
            callback

        """
        if hasattr(self, 'notebook') and self.notebook:
            raise AssertionError(
                'Box widget not available in notebook plotting')
        if not hasattr(self, 'iren'):
            raise AttributeError(
                'Widgets must be used with an intereactive renderer. No off screen plotting.'
            )
        if not hasattr(self, "box_widgets"):
            self.box_widgets = []

        if bounds is None:
            bounds = self.bounds

        if color is None:
            color = rcParams['font']['color']

        def _the_callback(box_widget, event_id):
            the_box = pyvista.PolyData()
            box_widget.GetPolyData(the_box)
            planes = vtk.vtkPlanes()
            box_widget.GetPlanes(planes)
            if hasattr(callback, '__call__'):
                if use_planes:
                    args = [planes]
                else:
                    args = [the_box]
                if pass_widget:
                    args.append(box_widget)
                try_callback(callback, *args)
            return

        box_widget = vtk.vtkBoxWidget()
        box_widget.GetOutlineProperty().SetColor(parse_color(color))
        box_widget.SetInteractor(self.iren)
        box_widget.SetCurrentRenderer(self.renderer)
        box_widget.SetPlaceFactor(factor)
        box_widget.SetRotationEnabled(rotation_enabled)
        box_widget.SetTranslationEnabled(outline_translation)
        box_widget.PlaceWidget(bounds)
        box_widget.On()
        box_widget.AddObserver(vtk.vtkCommand.EndInteractionEvent,
                               _the_callback)
        _the_callback(box_widget, None)

        self.box_widgets.append(box_widget)
        return box_widget
Esempio n. 37
0
    def buildPipeline(self):
        """ execute() -> None
        Dispatch the vtkRenderer to the actual rendering widget
        """  
        extent = self.input().GetExtent() 
        rangeBounds = self.getRangeBounds() 
        self.sliceCenter = [ (extent[2*i+1]-extent[2*i])/2 for i in range(3) ]       
        spacing = self.input().GetSpacing()
        sx, sy, sz = spacing       
        origin = self.input().GetOrigin()
        ox, oy, oz = origin
        self._range = [ rangeBounds[0], rangeBounds[1], rangeBounds[0], 0 ]
        dataType = self.input().GetScalarTypeAsString()
        self.setMaxScalarValue( self.input().GetScalarType() )
        self.pos = [ spacing[i]*extent[2*i] for i in range(3) ]
#        if ( (origin[0] + self.pos[0]) < 0.0): self.pos[0] = self.pos[0] + 360.0
        bounds = [0]*6
        for i in range(6):
            io2 = int(i/2)
            bounds[i] = origin[io2] + spacing[io2]*extent[i] 
            
        print " --VolumeRenderer--   Data Type = %s, range = (%f,%f), max_scalar = %s" % ( dataType, rangeBounds[0], rangeBounds[1], self._max_scalar_value )
        print "Extent: %s " % str( self.input().GetWholeExtent() )
        print "Spacing: %s " % str( spacing )
        print "Origin: %s " % str( origin )
        print "Dimensions: %s " % str( self.input().GetDimensions() )
        print "Bounds: %s " % str( bounds )
        print "Input Bounds: %s " % str( self.input().GetBounds() )
        print "VolumePosition: %s " % str( self.pos )
        
#        self.inputInfo = self.inputPort.GetInformation() 
#        translation = inputInfo.Get( ResampleTranslationKey  )                                     
        
        # Create transfer mapping scalar value to color
        self.colorTransferFunction = vtk.vtkColorTransferFunction()
                
        # Create transfer mapping scalar value to opacity
        self.opacityTransferFunction = vtk.vtkPiecewiseFunction()        
                
        # The property describes how the data will look
        self.volumeProperty = vtk.vtkVolumeProperty()
        self.volumeProperty.SetInterpolationType( vtk.VTK_LINEAR_INTERPOLATION )
        self.volumeProperty.SetColor(self.colorTransferFunction)
        self.volumeProperty.SetScalarOpacity(self.opacityTransferFunction)
#        self.volumeProperty.SetGradientOpacity(self.opacityTransferFunction)
     
        # The mapper knows how to render the data

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

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

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

        self.renderer.AddVolume( self.volume )
        self.renderer.SetBackground( VTK_BACKGROUND_COLOR[0], VTK_BACKGROUND_COLOR[1], VTK_BACKGROUND_COLOR[2] )
        self.setColormap( [ 'jet', 1, 0, 0 ] )
    def Execute(self):
 
        if (self.Surface == None):
            self.PrintError('Error: no Surface.')
 
        #if (self.ReferenceSurface == None):
        #    self.PrintError('Error: no Reference Surface.')
 
        if not self.vmtkRenderer:
            self.vmtkRenderer = vmtkrenderer.vmtkRenderer()
            self.vmtkRenderer.Initialize()
            self.OwnRenderer = 1

        self.vmtkRenderer.RegisterScript(self) 
 
        if self.Transform == None:   
            self.Transform = vtk.vtkTransform()
 
        if self.TransformFilter == None:
            self.TransformFilter= vtk.vtkTransformPolyDataFilter()
 
        self.TransformFilter.SetInput(self.Surface)
        self.TransformFilter.SetTransform(self.Transform)
 
        self.TransformFilter.Update()
        self.TransformFilter.GetOutput().Update()
 
        self.TransformedSurface.ShallowCopy(self.TransformFilter.GetOutput())
        self.TransformedSurface.Update()
 
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInput(self.TransformedSurface)
 
        mapper.ScalarVisibilityOff()
 
        self.Actor = vtk.vtkActor()
        self.Actor.SetMapper(mapper)
        self.Actor.GetProperty().SetColor(1.0, 0.1, 0.1)
        #self.Actor.GetProperty().SetOpacity(0.5)        
        self.vmtkRenderer.Renderer.AddActor(self.Actor)

        if self.ReferenceSurface: 
            mapper2 = vtk.vtkPolyDataMapper()
            mapper2.SetInput(self.ReferenceSurface)
            mapper2.ScalarVisibilityOff()
     
            self.Actor2 = vtk.vtkActor()
            self.Actor2.SetMapper(mapper2)
            self.Actor2.GetProperty().SetColor(1.0, 1.0, 1.0)
            self.Actor2.GetProperty().SetOpacity(0.5)
     
            self.vmtkRenderer.Renderer.AddActor(self.Actor2)        
 
        self.BoxWidget = vtk.vtkBoxWidget()
        self.BoxWidget.SetPlaceFactor(1.0)
        self.BoxWidget.SetInteractor(self.vmtkRenderer.RenderWindowInteractor)
        self.BoxWidget.GetFaceProperty().SetColor(0.6,0.6,0.2)
        self.BoxWidget.GetFaceProperty().SetOpacity(0.25)
        self.BoxWidget.ScalingEnabledOff()
        self.BoxWidget.HandlesOff()
 
        if self.Scaling:
            self.BoxWidget.ScalingEnabledOn()
            self.BoxWidget.HandlesOn()
 	
        self.vmtkRenderer.RegisterScript(self) 
        
        self.InputInfo('Use the left-mousebutton to rotate the box \nUse the middle-mouse-button to move the box \nPress space to move the surface to its new postion')
        #self.OutputText('Press \'i\' to activate the box widget interactor \n')
        #self.OutputText('Use the left-mousebutton to rotate the box \n')
        #self.OutputText('Use the middle-mouse-button to move the box \n')
        #self.OutputText('Press space to move the surface to its new postion \n')
        #self.OutputText('Press \'q\' to quit and apply the transform \n')
	
        self.vmtkRenderer.AddKeyBinding('space','Move the surface.',self.MoveCallback)
        self.vmtkRenderer.AddKeyBinding('i','Interact.',self.InteractCallback)

        self.Display()
 
        self.Surface = self.TransformedSurface
 
        self.Matrix4x4 = self.Transform.GetMatrix()
 
        matrix = self.Matrix4x4
        self.MatrixCoefficients = [
            matrix.GetElement(0,0), matrix.GetElement(0,1), matrix.GetElement(0,2), matrix.GetElement(0,3),
            matrix.GetElement(1,0), matrix.GetElement(1,1), matrix.GetElement(1,2), matrix.GetElement(1,3),
            matrix.GetElement(2,0), matrix.GetElement(2,1), matrix.GetElement(2,2), matrix.GetElement(2,3),
            matrix.GetElement(3,0), matrix.GetElement(3,1), matrix.GetElement(3,2), matrix.GetElement(3,3)]

        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
Esempio n. 39
0
    def __init__(self, module_manager):
        # call base constructor
        ModuleBase.__init__(self, module_manager)
        ColourDialogMixin.__init__(
            self, module_manager.get_module_view_parent_window())
        self._numDataInputs = self.NUM_INPUTS
        # use list comprehension to create list keeping track of inputs
        self._inputs = [{'Connected' : None, 'inputData' : None,
                         'vtkActor' : None, 'ipw' : None}
                       for i in range(self._numDataInputs)]
        # then the window containing the renderwindows
        self.threedFrame = None

        # the renderers corresponding to the render windows
        self._threedRenderer = None

        self._outline_source = vtk.vtkOutlineSource()
        om = vtk.vtkPolyDataMapper()
        om.SetInputConnection(self._outline_source.GetOutputPort())
        self._outline_actor = vtk.vtkActor()
        self._outline_actor.SetMapper(om)
        self._cube_axes_actor2d = vtk.vtkCubeAxesActor2D()
        self._cube_axes_actor2d.SetFlyModeToOuterEdges()
        #self._cube_axes_actor2d.SetFlyModeToClosestTriad()


        # use box widget for VOI selection
        self._voi_widget = vtk.vtkBoxWidget()
        # we want to keep it aligned with the cubic volume, thanks
        self._voi_widget.SetRotationEnabled(0)
        self._voi_widget.AddObserver('InteractionEvent',
                                     self.voiWidgetInteractionCallback)
        self._voi_widget.AddObserver('EndInteractionEvent',
                                     self.voiWidgetEndInteractionCallback)
        self._voi_widget.NeedsPlacement = True

        # also create the VTK construct for actually extracting VOI from data
        #self._extractVOI = vtk.vtkExtractVOI()
        self._currentVOI = 6 * [0]

        # set the whole UI up!
        self._create_window()

        # our interactor styles (we could add joystick or something too)
        self._cInteractorStyle = vtk.vtkInteractorStyleTrackballCamera()


        # set the default
        self.threedFrame.threedRWI.SetInteractorStyle(self._cInteractorStyle)
        
        rwi = self.threedFrame.threedRWI
        rwi.Unbind(wx.EVT_MOUSEWHEEL)
        rwi.Bind(wx.EVT_MOUSEWHEEL, self._handler_mousewheel)        

        # initialise our sliceDirections, this will also setup the grid and
        # bind all slice UI events
        self.sliceDirections = sliceDirections(
            self, self.controlFrame.sliceGrid)

        self.selectedPoints = selectedPoints(
            self, self.controlFrame.pointsGrid)

        # we now have a wx.ListCtrl, let's abuse it
        self._tdObjects = tdObjects(self,
                                    self.controlFrame.objectsListGrid)

        self._implicits = implicits(self,
                                    self.controlFrame.implicitsGrid)


        # setup orientation widget stuff
        # NB NB NB: we switch interaction with this off later
        # (InteractiveOff()), thus disabling direct translation and
        # scaling.  If we DON'T do this, interaction with software 
        # raycasters are greatly slowed down.
        self._orientation_widget = vtk.vtkOrientationMarkerWidget()
        
        self._annotated_cube_actor = aca = vtk.vtkAnnotatedCubeActor()
        #aca.TextEdgesOff()

        aca.GetXMinusFaceProperty().SetColor(1,0,0)
        aca.GetXPlusFaceProperty().SetColor(1,0,0)
        aca.GetYMinusFaceProperty().SetColor(0,1,0)
        aca.GetYPlusFaceProperty().SetColor(0,1,0)
        aca.GetZMinusFaceProperty().SetColor(0,0,1)
        aca.GetZPlusFaceProperty().SetColor(0,0,1)
        
        self._axes_actor = vtk.vtkAxesActor()

        self._orientation_widget.SetInteractor(
            self.threedFrame.threedRWI)
        self._orientation_widget.SetOrientationMarker(
            self._axes_actor)
        self._orientation_widget.On()
       
        # make sure interaction is off; when on, interaction with
        # software raycasters is greatly slowed down!
        self._orientation_widget.InteractiveOff()
Esempio n. 40
0
    def testBoxWidget(self):

        # Demonstrate how to use the vtkBoxWidget.
        # This script uses a 3D box widget to define a "clipping box" to clip some
        # simple geometry (a mace). Make sure that you hit the "W" key to activate the widget.

        # create a sphere source
        #
        sphere = vtk.vtkSphereSource()
        cone = vtk.vtkConeSource()
        glyph = vtk.vtkGlyph3D()
        glyph.SetInputConnection(sphere.GetOutputPort())
        glyph.SetSourceConnection(cone.GetOutputPort())
        glyph.SetVectorModeToUseNormal()
        glyph.SetScaleModeToScaleByVector()
        glyph.SetScaleFactor(0.25)
        apd = vtk.vtkAppendPolyData()
        apd.AddInputConnection(glyph.GetOutputPort())
        apd.AddInputConnection(sphere.GetOutputPort())
        maceMapper = vtk.vtkPolyDataMapper()
        maceMapper.SetInputConnection(apd.GetOutputPort())
        maceActor = vtk.vtkLODActor()
        maceActor.SetMapper(maceMapper)
        maceActor.VisibilityOn()

        planes = vtk.vtkPlanes()
        clipper = vtk.vtkClipPolyData()
        clipper.SetInputConnection(apd.GetOutputPort())
        clipper.SetClipFunction(planes)
        clipper.InsideOutOn()
        selectMapper = vtk.vtkPolyDataMapper()
        selectMapper.SetInputConnection(clipper.GetOutputPort())
        selectActor = vtk.vtkLODActor()
        selectActor.SetMapper(selectMapper)
        selectActor.GetProperty().SetColor(0, 1, 0)
        selectActor.VisibilityOff()
        selectActor.SetScale(1.01, 1.01, 1.01)

        # Create the RenderWindow, Renderer and both Actors
        #
        ren = vtk.vtkRenderer()
        renWin = vtk.vtkRenderWindow()
        renWin.AddRenderer(ren)

        iRen = vtk.vtkRenderWindowInteractor()
        iRen.SetRenderWindow(renWin);
        boxWidget = vtk.vtkBoxWidget()
        boxWidget.SetInteractor(iRen)

        ren.AddActor(maceActor)
        ren.AddActor(selectActor)

        # Add the actors to the renderer, set the background and size
        #
        ren.SetBackground(0.1, 0.2, 0.4)
        renWin.SetSize(300, 300)

        def SelectPolygons(widget, event_string):
            '''
            The callback takes two parameters.
            Parameters:
              widget - the object that generates the event.
              event_string - the event name (which is a string).
            '''
            boxWidget, selectActor
            boxWidget.GetPlanes(planes)
            selectActor.VisibilityOn()

        # place the interactor initially
        boxWidget.SetInputConnection(glyph.GetOutputPort())
        boxWidget.PlaceWidget()
        boxWidget.AddObserver("EndInteractionEvent", SelectPolygons)

        # render and interact with data

        renWin.Render()

        img_file = "TestBoxWidget.png"
        vtk.test.Testing.compareImage(iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25)
        vtk.test.Testing.interact()
Esempio n. 41
0
    def addVol(self, data, header=None):
        pix_diag = 5.0 / 10.0

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

        volMapper = vtk.vtkVolumeRayCastMapper()
        compositeFunction = vtk.vtkVolumeRayCastCompositeFunction()
        compositeFunction.SetCompositeMethodToInterpolateFirst()
        #compositeFunction.SetCompositeMethodToClassifyFirst()
        volMapper.SetVolumeRayCastFunction(compositeFunction)

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

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

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

        self.ren.AddVolume(vol)

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

        planes = vtk.vtkPlanes()

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

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

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

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

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

        self.ren.AddActor(outlineActor)
        self.volnum += 1
Esempio n. 42
0
    def segmentFromSeeds(self, images,  image_pos_pat, image_ori_pat, seeds, iren, xplane, yplane, zplane):
        """ segmentFromSeeds: Extracts VOI from seeds
        
        INPUTS:
        =======        
        images: (vtkImageData)   list of Input image to Transform
        seeds: vtkPoints    list of seeded coordinates from picker
        OUTPUTS:
        =======
        transformed_image (vtkImageData)    Transformed imaged mapped to dicom coords frame
        transform (vtkTransform)            Transform used
        
        """
        for postS in range(1,len(images)):
            print "\n Segmenting image post no : %s " % str(postS)
            
            subimage = self.loadDisplay.subImage(images, postS)            
            
            # Proceed to build reference frame for display objects based on DICOM coords   
            [transformed_image, transform_cube] = self.loadDisplay.dicomTransform(subimage, image_pos_pat, image_ori_pat)
            
            # Calculate the center of the volume
            transformed_image.UpdateInformation() 
                    
            print "\nBoxwidget placed..."
            #################################################################
            # The box widget observes the events invoked by the render window
            # interactor.  These events come from user interaction in the render
            # window.
            # Place the interactor initially. The output of the reader is used to
            # place the box widget.
            self.boxWidget = vtk.vtkBoxWidget()
            self.boxWidget.SetInteractor(iren)
            self.boxWidget.SetPlaceFactor(1)
            self.boxWidget.SetInput(transformed_image)
            if( self.boundsPlane_presel != []):
                self.boxWidget.PlaceWidget( self.boundsPlane_presel )
            
            # Construct a bounding box around the seeds  
            init_seedsBounds = [0,0,0,0,0,0]
            seeds.GetBounds( init_seedsBounds )
            
            if postS == 1:        
                # polygonal data --> image stencil:
                # create a simple box VOI mask shape using previously found boundsPlane_preselected
                VOIStencil = vtk.vtkROIStencilSource()
                VOIStencil.SetShapeToBox()
                VOIStencil.SetBounds( init_seedsBounds )    
                VOIStencil.SetInformationInput(transformed_image)
                VOIStencil.Update()
            
                # cut the corresponding VOI region and set the background:
                extractVOI_imgstenc = vtk.vtkImageStencil()
                extractVOI_imgstenc.SetInput(transformed_image)
                extractVOI_imgstenc.SetStencil(VOIStencil.GetOutput())
                extractVOI_imgstenc.ReverseStencilOff()
                extractVOI_imgstenc.SetBackgroundValue(0.0)
                extractVOI_imgstenc.Update()
                
                allSeededIm = vtk.vtkImageData()
                allSeededIm.DeepCopy( extractVOI_imgstenc.GetOutput() )
        
                # Add some bounding box radius
                self.boxWidget.PlaceWidget( init_seedsBounds )
                self.boundsPlane_presel = init_seedsBounds
                print "seeds.GetBounds"
                print init_seedsBounds
                        
                self.boxWidget.AddObserver("InteractionEvent", self.SelectPolygons)
                self.boxWidget.On()
            
                # turn off planes
                xplane.Off()
                yplane.Off()
                iren.Start()
                self.boxWidget.Off()
            
            # polygonal data --> image stencil:
            print "\n Create vtkPolyDataToImageStencil with bounds:"
            print self.boundsPlane_presel
            
            # create a simple box VOI mask shape using previously found boundsPlane_preselected
            VOIStencil = vtk.vtkROIStencilSource()
            VOIStencil.SetShapeToBox()
            VOIStencil.SetBounds( self.boundsPlane_presel )    
            VOIStencil.SetInformationInput(transformed_image)
            VOIStencil.Update()
                                    
            # cut the corresponding VOI region and set the background:
            extractVOI_imgstenc = vtk.vtkImageStencil()
            extractVOI_imgstenc.SetInput(transformed_image)
            extractVOI_imgstenc.SetStencil(VOIStencil.GetOutput())
            extractVOI_imgstenc.ReverseStencilOff()
            extractVOI_imgstenc.SetBackgroundValue(0.0)
            extractVOI_imgstenc.Update()
                
            # add subsecuent VOI stencils
            addsegROI = vtk.vtkImageMathematics()
            addsegROI.SetInput(0, allSeededIm)
            addsegROI.SetInput(1, extractVOI_imgstenc.GetOutput())
            addsegROI.SetOperationToAdd()
            addsegROI.Update()
      
            # turn off the box
            allSeededIm = addsegROI.GetOutput()

        avegSeededIm = vtk.vtkImageMathematics()
        avegSeededIm.SetInput(0, allSeededIm)
        avegSeededIm.SetOperationToMultiplyByK()
        avegSeededIm.SetConstantK( 0.2 )        
        avegSeededIm.Update()
        
        # take out average image
        finalSeedIm = avegSeededIm.GetOutput()
        xplane.SetInput( finalSeedIm )
        yplane.SetInput( finalSeedIm )
        zplane.SetInput( finalSeedIm )            
        
        image_scalar_range = finalSeedIm.GetScalarRange() 
        lThre = image_scalar_range[0]
        uThre = image_scalar_range[1]
        print "\n Image Scalar Range:"
        print image_scalar_range[0], image_scalar_range[1]
        print "Uper thresholding by"
        print uThre*0.25
        
        ## Display histogram 
        scalars = finalSeedIm.GetPointData().GetScalars()
        np_scalars = vtk_to_numpy(scalars)        
        pylab.figure()
        pylab.hist(np_scalars.flatten(), histtype='bar')
        pylab.show()
                
        # Now performed threshold on initialized VOI        
        # vtkImageThresholdConnectivity will perform a flood fill on an image, given upper and lower pixel intensity 
        # thresholds. It works similarly to vtkImageThreshold, but also allows the user to set seed points to limit
        # the threshold operation to contiguous regions of the image. The filled region, or the "inside", will be passed 
        # through to the output by default, while the "outside" will be replaced with zeros. The scalar type of the output is the same as the input.
        thresh_sub = vtk.vtkImageThresholdConnectivity() 
        thresh_sub.SetSeedPoints(seeds)
        thresh_sub.SetNeighborhoodRadius(3, 3, 2) #The radius of the neighborhood that must be within the threshold values in order for the voxel to be included in the mask. The default radius is zero (one single voxel). The radius is measured in voxels
        thresh_sub.SetNeighborhoodFraction(0.10) #The fraction of the neighborhood that must be within the thresholds. The default value is 0.5.
        thresh_sub.ThresholdBetween(0.25*uThre, uThre); 
        thresh_sub.SetInput( finalSeedIm )
        thresh_sub.Update()
        
        xplane.SetInput( thresh_sub.GetOutput() )
        yplane.SetInput( thresh_sub.GetOutput()  )
        zplane.SetInput( thresh_sub.GetOutput()  )            
        iren.Start()
        
        # Convert VOIlesion into polygonal struct
        VOIlesion_poly = vtk.vtkMarchingCubes() 
        VOIlesion_poly.SetValue(0,255)
        VOIlesion_poly.SetInput(thresh_sub.GetOutput())
        VOIlesion_poly.ComputeNormalsOff()
        VOIlesion_poly.Update()
        
        # Recalculate num_voxels and vol_lesion on VOI
        nvoxels = VOIlesion_poly.GetOutput().GetNumberOfCells()
        print "\n Number of Voxels: %d" % nvoxels # After the filter has executed, use GetNumberOfVoxels() to find out how many voxels were filled.

        return VOIlesion_poly.GetOutput()
Esempio n. 43
0
def clip_polydata_by_box(polydata,
                         point,
                         tangent,
                         normal,
                         binormal,
                         size=[10, 10, 1]):
    """Clip the input polydata with given box shape and direction

	Parameters:
	polydata (polydata): Input polydata
	point (array): Coordinate of clipping box center
	normal (array): Direction tangent of the clipping box (major axis)
	normal (array): Direction normal of the clipping box
	normal (array): Direction binormal of the clipping box
	size (array): Size of the clipping box (default: [10,10,1])

	Returns:
	vtkPolyData: Clipped polydata
	vtkPolyData: Clipping box
	vtkPolyData: Clipping plane
	"""

    # create a clipping box widget
    clipWidget = vtk.vtkBoxWidget()
    transform = vtk.vtkTransform()

    transform.Translate(point)
    w = math.atan(
        math.sqrt(tangent[0]**2 + tangent[1]**2) / tangent[2]) * 180 / 3.14
    transform.RotateWXYZ(w, -tangent[1], tangent[0], 0)
    transform.Scale(size)

    # print(transform.GetMatrix())

    clipBox = vtk.vtkCubeSource()
    transformFilter = vtk.vtkTransformPolyDataFilter()
    transformFilter.SetInputConnection(clipBox.GetOutputPort())
    transformFilter.SetTransform(transform)
    transformFilter.Update()

    clipBoxPolyData = vtk.vtkPolyData()
    clipBoxPolyData.DeepCopy(transformFilter.GetOutput())

    clipWidget.SetTransform(transform)
    clipFunction = vtk.vtkPlanes()
    clipWidget.GetPlanes(clipFunction)

    clipper = vtk.vtkClipPolyData()
    clipper.SetClipFunction(clipFunction)
    clipper.SetInputData(polydata)
    clipper.GenerateClippedOutputOn()
    clipper.SetValue(0.0)
    clipper.Update()

    polydata.DeepCopy(clipper.GetOutput())

    # clipping plane
    point1 = []
    point2 = []
    origin = []

    for i in range(3):
        point1.append(point[i] - normal[i] * math.sqrt(2) / 2 * size[0])
        point2.append(point[i] + normal[i] * math.sqrt(2) / 2 * size[0])
        origin.append(point[i] + binormal[i] * math.sqrt(2) / 2 * size[0])

    planeSource = vtk.vtkPlaneSource()
    planeSource.SetResolution(10, 10)
    planeSource.SetOrigin(origin)
    planeSource.SetPoint1(point1)
    planeSource.SetPoint2(point2)
    planeSource.Update()

    clipPlanePolyData = vtk.vtkPolyData()
    clipPlanePolyData.DeepCopy(planeSource.GetOutput())
    return polydata, clipBoxPolyData, clipPlanePolyData
Esempio n. 44
0
        def addVolumeToRenderer(self,img):

            pix_diag = 5.0

            self.compositeFunction = vtk.vtkVolumeRayCastCompositeFunction()
            self.compositeFunction.SetCompositeMethodToInterpolateFirst()

            self.vtkWidget.Render()
            self.volMapper = vtk.vtkVolumeRayCastMapper()
            self.window.Render()
            self.extensions = vtk.vtkOpenGLExtensionManager()
            self.extensions.SetRenderWindow(self.window)
            self.extensions.Update()


            string = self.extensions.GetExtensionsString()

            print(self.extensions.GetExtensionsString())


            self.volMapper.SetVolumeRayCastFunction(self.compositeFunction)
            self.volMapper.SetSampleDistance(pix_diag / 5.0)

            self.volMapper.SetInputConnection(img.GetOutputPort())


            self.updateColourTransferFunction()
            self.updateOpacityTransferFunction()

            self.plane = vtk.vtkPlanes()

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

            self.boxWidget = vtk.vtkBoxWidget()
            self.boxWidget.SetInteractor(self.vtkWidget)
            self.boxWidget.SetPlaceFactor(1.0)

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

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

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

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

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

            self.ren.AddVolume(self.vol)
            self.ren.AddActor(self.outlineActor)

            self.window.Render()
Esempio n. 45
0
    def buildPipeline(self):
        """ execute() -> None
        Dispatch the vtkRenderer to the actual rendering widget
        """ 
        
        texture_ispec = self.getInputSpec(  1 )                
        xMin, xMax, yMin, yMax, zMin, zMax = self.input().GetWholeExtent()       
        self.sliceCenter = [ (xMax-xMin)/2, (yMax-yMin)/2, (zMax-zMin)/2  ]       
        spacing = self.input().GetSpacing()
        sx, sy, sz = spacing 
#        self.input().SetSpacing( sx, sy, 5*sz )      
        origin = self.input().GetOrigin()
        ox, oy, oz = origin
        dataType = self.input().GetScalarTypeAsString()
        self.setMaxScalarValue( self.input().GetScalarType() )
        self.colorByMappedScalars = False
        rangeBounds = self.getRangeBounds()

        dr = rangeBounds[1] - rangeBounds[0]
        range_offset = .2*dr
        self.range = [ rangeBounds[0] + range_offset, rangeBounds[1] - range_offset ]
        print "Data Type = %s, range = (%f,%f), range bounds = (%f,%f), max_scalar = %s" % ( dataType, self.range[0], self.range[1], rangeBounds[0], rangeBounds[1], self._max_scalar_value )
        self.probeFilter = None
        textureRange = self.range
        if texture_ispec and texture_ispec.input():
            self.probeFilter = vtk.vtkProbeFilter()
            textureRange = texture_ispec.input().GetScalarRange()
            self.probeFilter.SetSource( texture_ispec.input() )
            self.generateTexture = True

        if (self.surfacePicker == None):           
            self.surfacePicker  = vtk.vtkPointPicker()
                    
        self.levelSetFilter = vtk.vtkContourFilter()
        self.inputModule().inputToAlgorithm( self.levelSetFilter )

        self.clipPlanes = vtk.vtkPlanes() 
        self.polyClipper = vtk.vtkClipPolyData()
        self.polyClipper.SetInputConnection( self.levelSetFilter.GetOutputPort() )
        self.polyClipper.SetClipFunction( self.clipPlanes )
        self.polyClipper.InsideOutOn()
                
        self.levelSetMapper = vtk.vtkPolyDataMapper()
        self.levelSetMapper.SetColorModeToMapScalars()
        if ( self.probeFilter == None ):
            imageRange = self.getImageValues( self.range ) 
            self.levelSetMapper.SetInputConnection( self.polyClipper.GetOutputPort() ) 
            self.levelSetMapper.SetScalarRange( imageRange[0], imageRange[1] )
        else: 
            self.probeFilter.SetInputConnection( self.polyClipper.GetOutputPort() )
            self.levelSetMapper.SetInputConnection( self.probeFilter.GetOutputPort() ) 
            self.levelSetMapper.SetScalarRange( textureRange )
            
        colormapManager = self.getColormapManager( index=1 ) if texture_ispec and texture_ispec.input() else self.getColormapManager()                  
        colormapManager.setAlphaRange ( self.opacityRange ) 
        self.levelSetMapper.SetLookupTable( colormapManager.lut ) 
        self.levelSetMapper.UseLookupTableScalarRangeOn()
       
        self.updateLevels()
          
#        levelSetMapper.SetColorModeToMapScalars()  
#        levelSetActor = vtk.vtkLODActor() 
        self.levelSetActor = vtk.vtkLODActor() 
#            levelSetMapper.ScalarVisibilityOff() 
#            levelSetActor.SetProperty( self.levelSetProperty )              
        self.levelSetActor.SetMapper( self.levelSetMapper )

        self.cursorActor     = vtk.vtkActor()
        self.cursorProperty  = None 
        self.cursor = vtk.vtkSphereSource()
        self.cursor.SetRadius(2.0)
        self.cursor.SetThetaResolution(8)
        self.cursor.SetPhiResolution(8)

        self.clipper = vtk.vtkBoxWidget()
        self.clipper.RotationEnabledOff()
        self.clipper.SetPlaceFactor( 1.0 )    
        self.clipper.AddObserver( 'StartInteractionEvent', self.startClip )
        self.clipper.AddObserver( 'EndInteractionEvent', self.executeClip )
        
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInput(self.cursor.GetOutput())
        self.cursorActor.SetMapper(mapper)        
        self.createDefaultProperties() 
                                                            
#        pointData = self.levelSetFilter.GetOutput().GetPointData()
#        pointData.SetScalars( colorLevelData )
        
#        if pd <> None:
#            na = pd.GetNumberOfArrays()
#            print " ** Dataset has %d arrays. ** " % ( pd.GetNumberOfArrays() )
#            for i in range( na ): print "   ---  Array %d: %s " % ( i,  str( pd.GetArrayName(i) ) )
#        else: print " ** No point data. "
           
        self.renderer.AddActor( self.levelSetActor )
        self.surfacePicker.AddPickList( self.levelSetActor )
        self.surfacePicker.PickFromListOn()
        self.renderer.AddViewProp(self.cursorActor)
        self.cursorActor.SetProperty(self.cursorProperty)
        self.renderer.SetBackground( VTK_BACKGROUND_COLOR[0], VTK_BACKGROUND_COLOR[1], VTK_BACKGROUND_COLOR[2] ) 
        self.set3DOutput()                                              
    def Execute(self):

        if (self.Surface == None):
            self.PrintError('Error: no Surface.')

        #if (self.ReferenceSurface == None):
        #    self.PrintError('Error: no Reference Surface.')

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

        self.vmtkRenderer.RegisterScript(self)

        if self.Transform == None:
            self.Transform = vtk.vtkTransform()

        if self.TransformFilter == None:
            self.TransformFilter= vtk.vtkTransformPolyDataFilter()

        self.TransformFilter.SetInputData(self.Surface)
        self.TransformFilter.SetTransform(self.Transform)

        self.TransformFilter.Update()

        self.TransformedSurface.ShallowCopy(self.TransformFilter.GetOutput())

        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputData(self.TransformedSurface)

        mapper.ScalarVisibilityOff()

        self.Actor = vtk.vtkActor()
        self.Actor.SetMapper(mapper)
        self.Actor.GetProperty().SetColor(1.0, 0.1, 0.1)
        #self.Actor.GetProperty().SetOpacity(0.5)
        self.vmtkRenderer.Renderer.AddActor(self.Actor)

        if self.ReferenceSurface:
            mapper2 = vtk.vtkPolyDataMapper()
            mapper2.SetInputData(self.ReferenceSurface)
            mapper2.ScalarVisibilityOff()

            self.Actor2 = vtk.vtkActor()
            self.Actor2.SetMapper(mapper2)
            self.Actor2.GetProperty().SetColor(1.0, 1.0, 1.0)
            self.Actor2.GetProperty().SetOpacity(0.5)

            self.vmtkRenderer.Renderer.AddActor(self.Actor2)

        self.BoxWidget = vtk.vtkBoxWidget()
        self.BoxWidget.SetPlaceFactor(1.0)
        self.BoxWidget.SetInteractor(self.vmtkRenderer.RenderWindowInteractor)
        self.BoxWidget.GetFaceProperty().SetColor(0.6,0.6,0.2)
        self.BoxWidget.GetFaceProperty().SetOpacity(0.25)
        self.BoxWidget.ScalingEnabledOff()
        self.BoxWidget.HandlesOff()

        if self.Scaling:
            self.BoxWidget.ScalingEnabledOn()
            self.BoxWidget.HandlesOn()

        self.vmtkRenderer.RegisterScript(self)

        self.InputInfo('Use the left-mousebutton to rotate the box \nUse the middle-mouse-button to move the box \nPress space to move the surface to its new postion')
        #self.OutputText('Press \'i\' to activate the box widget interactor \n')
        #self.OutputText('Use the left-mousebutton to rotate the box \n')
        #self.OutputText('Use the middle-mouse-button to move the box \n')
        #self.OutputText('Press space to move the surface to its new postion \n')
        #self.OutputText('Press \'q\' to quit and apply the transform \n')

        self.vmtkRenderer.AddKeyBinding('space','Move the surface.',self.MoveCallback)
        self.vmtkRenderer.AddKeyBinding('i','Interact.',self.InteractCallback)

        self.Display()

        self.Surface = self.TransformedSurface

        self.Matrix4x4 = self.Transform.GetMatrix()

        matrix = self.Matrix4x4
        self.MatrixCoefficients = [
            matrix.GetElement(0,0), matrix.GetElement(0,1), matrix.GetElement(0,2), matrix.GetElement(0,3),
            matrix.GetElement(1,0), matrix.GetElement(1,1), matrix.GetElement(1,2), matrix.GetElement(1,3),
            matrix.GetElement(2,0), matrix.GetElement(2,1), matrix.GetElement(2,2), matrix.GetElement(2,3),
            matrix.GetElement(3,0), matrix.GetElement(3,1), matrix.GetElement(3,2), matrix.GetElement(3,3)]

        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
Esempio n. 47
0
	def addVol(self, data, header=None):
		pix_diag = 5.0/10.0

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

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

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

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

		self.ren.AddVolume(vol)

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

		planes = vtk.vtkPlanes()
		def ClipVolumeRender(obj, event):
			obj.GetPlanes(planes)
			volMapper.SetClippingPlanes(planes)
         
		boxWidget.SetInput(img.GetOutput())
		boxWidget.PlaceWidget(img.GetOutput().GetBounds())
		boxWidget.InsideOutOn()
		boxWidget.AddObserver("InteractionEvent", ClipVolumeRender)

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

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

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

		self.ren.AddActor(outlineActor)
		self.volnum += 1
Esempio n. 48
0
    def __init__(self, parent, data_set):
        wxVTKRenderWindowInteractor.__init__(self, parent, -1, size=parent.GetSize())
        
        ren = vtk.vtkRenderer()
        self.GetRenderWindow().AddRenderer(ren)

        # prob should allow a string as data_set also, but for now assume it's a python or numpy array
        #img = self.LoadVolumeData(data_set) # load from filename
        img = vtkImageImportFromArray()
        img.SetArray(data_set)

        pix_diag = 5.0

        # volMapper = vtk.vtkVolumeTextureMapper3D()

        volMapper = vtk.vtkVolumeRayCastMapper()
        compositeFunction = vtk.vtkVolumeRayCastCompositeFunction()
        compositeFunction.SetCompositeMethodToInterpolateFirst()
        volMapper.SetVolumeRayCastFunction(compositeFunction)

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

        # Transfer Functions
        self.opacity_tf = vtk.vtkPiecewiseFunction()
        self.color_tf = vtk.vtkColorTransferFunction()

        # The property describes how the data will look
        self.volProperty = volProperty = vtk.vtkVolumeProperty()
        volProperty.SetColor(self.color_tf)
        volProperty.SetScalarOpacity(self.opacity_tf)
        volProperty.ShadeOn()
        volProperty.SetInterpolationTypeToLinear()
        volProperty.SetScalarOpacityUnitDistance(pix_diag)

        vol = vtk.vtkVolume()
        vol.SetMapper(volMapper)
        vol.SetProperty(volProperty)
        
        ren.AddVolume(vol)
        
        boxWidget = vtk.vtkBoxWidget()
        boxWidget.SetInteractor(self)
        boxWidget.SetPlaceFactor(1.0)
        
        # The implicit function vtkPlanes is used in conjunction with the
        # volume ray cast mapper to limit which portion of the volume is
        # volume rendered.
        planes = vtk.vtkPlanes()
        def ClipVolumeRender(obj, event):
            obj.GetPlanes(planes)
            volMapper.SetClippingPlanes(planes)
        
        # Place the interactor initially. The output of the reader is used to
        # place the box widget.
        boxWidget.SetInput(img.GetOutput())
        boxWidget.PlaceWidget()
        boxWidget.InsideOutOn()
        boxWidget.AddObserver("InteractionEvent", ClipVolumeRender)

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

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

        ren.AddActor(outlineActor)
        
        style = vtk.vtkInteractorStyleTrackballCamera()
        self.SetInteractorStyle(style)
        self.t_graph = TransferGraph(self)
        self.SetFocus()
        
        # So we know when new values are added / changed on the tgraph
        self.t_graph.Connect(-1, -1, wx.wxEVT_COMMAND_SLIDER_UPDATED, 
                             self.OnTGraphUpdate)
       
        self.OnTGraphUpdate(None)
        
        self.lighting = True

        # This is the transfer graph
        self.t_graph.Show()
Esempio n. 49
0
    def load_muscleSI_mha(self, T2image, image_pos_pat, image_ori_pat, m_bounds, iren):
        """ load_muscleSI: Place automatically a widget over muscle location from file
        
        INPUTS:
        =======        
        images: (vtkImageData)   list of Input image to Transform
        OUTPUTS:
        =======
        muscleSI (float)    Signal intensity from muscle
        muscleSIcoords (float[3])            cords where Signal intensity from muscle is measured
        
        """
        ## Transform T2 img
        loadDisplay = Display()
        
        # Proceed to build reference frame for display objects based on DICOM coords   
        t_T2image = loadDisplay.mhaTransform(T2image, image_pos_pat, image_ori_pat)
            
        # Calculate the center of the volume
        t_T2image.UpdateInformation() 
               
        print "\nBoxwidget placed..."
        #################################################################
        # The box widget observes the events invoked by the render window
        # interactor.  These events come from user interaction in the render
        # window.
        # Place the interactor initially. The output of the reader is used to
        # place the box widget.
        self.boxWidget = vtk.vtkBoxWidget()
        self.boxWidget.SetInteractor(iren)
        self.boxWidget.SetPlaceFactor(1)
        self.boxWidget.SetInput(t_T2image)
        self.boxWidget.ScalingEnabledOff()
        self.boxWidget.OutlineCursorWiresOn()                
                
        # Construct a bounding box
        bwidg = [0,0,0,0,0,0]     
        bwidg[0] = m_bounds[0]; bwidg[1] = m_bounds[1]; 
        bwidg[2] = m_bounds[2]; bwidg[3] = m_bounds[3];
        bwidg[4] = m_bounds[4]; bwidg[5] = m_bounds[5];
        self.bounds_muscleSI = bwidg
        print "\nbounds_muscleSI "
        print self.bounds_muscleSI

        # add to visualize        
        self.boxWidget.PlaceWidget( self.bounds_muscleSI )
        self.boxWidget.On()
        
        ##########
        ### Set image stencil for muscle
        # create a simple box VOI mask shape using previously found boundsPlane_preselected
        VOIStencil = vtk.vtkROIStencilSource()
        VOIStencil.SetShapeToBox()
        VOIStencil.SetBounds( self.bounds_muscleSI )    
        VOIStencil.SetInformationInput(t_T2image)
        VOIStencil.Update()
                                
        # cut the corresponding VOI region and set the background:
        extractVOI_imgstenc = vtk.vtkImageStencil()
        extractVOI_imgstenc.SetInput(t_T2image)
        extractVOI_imgstenc.SetStencil(VOIStencil.GetOutput())
        extractVOI_imgstenc.ReverseStencilOff()
        extractVOI_imgstenc.SetBackgroundValue(5000)
        extractVOI_imgstenc.Update()
            
        # take out average image
        finalmuscleSIIm = vtk.vtkImageData()
        finalmuscleSIIm = extractVOI_imgstenc.GetOutput()
        finalmuscleSIIm.Update()
                
        ## Display histogram 
        dims = finalmuscleSIIm .GetDimensions()
        scalars = finalmuscleSIIm.GetPointData().GetScalars()
        np_scalars = vtk_to_numpy(scalars)      
        np_scalars = np_scalars.reshape(dims[2], dims[1], dims[0]) 
        np_scalars = np_scalars.transpose(2,1,0)
        muscleSI = np_scalars[np_scalars<5000]
                
        muscle_scalar_range = [muscleSI.min(), muscleSI.max()]
        print "\nMuscle scalar Range:"
        print muscle_scalar_range[0], muscle_scalar_range[1]
        
        return muscleSI, muscle_scalar_range, self.bounds_muscleSI
Esempio n. 50
0
    def BuildView(self):

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

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

        self.vmtkRenderer.RegisterScript(self)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
Esempio n. 51
0
def cutterWidget(obj,
                 outputname='clipped.vtk',
                 c=(0.2, 0.2, 1),
                 alpha=1,
                 bc=(0.7, 0.8, 1),
                 legend=None):
    '''Pop up a box widget to cut parts of actor. Return largest part.'''

    apd = polydata(obj)

    planes = vtk.vtkPlanes()
    planes.SetBounds(apd.GetBounds())

    clipper = vtk.vtkClipPolyData()
    setInput(clipper, apd)
    clipper.SetClipFunction(planes)
    clipper.InsideOutOn()
    clipper.GenerateClippedOutputOn()

    # check if color string contains a float, in this case ignore alpha
    al = colors.getAlpha(c)
    if al: alpha = al

    act0Mapper = vtk.vtkPolyDataMapper()  # the part which stays
    act0Mapper.SetInputConnection(clipper.GetOutputPort())
    act0 = vtk.vtkActor()
    act0.SetMapper(act0Mapper)
    act0.GetProperty().SetColor(colors.getColor(c))
    act0.GetProperty().SetOpacity(alpha)
    backProp = vtk.vtkProperty()
    backProp.SetDiffuseColor(colors.getColor(bc))
    backProp.SetOpacity(alpha)
    act0.SetBackfaceProperty(backProp)

    act0.GetProperty().SetInterpolationToFlat()
    assignPhysicsMethods(act0)
    assignConvenienceMethods(act0, legend)

    act1Mapper = vtk.vtkPolyDataMapper()  # the part which is cut away
    act1Mapper.SetInputConnection(clipper.GetClippedOutputPort())
    act1 = vtk.vtkActor()
    act1.SetMapper(act1Mapper)
    act1.GetProperty().SetColor(colors.getColor(c))
    act1.GetProperty().SetOpacity(alpha / 10.)
    act1.GetProperty().SetRepresentationToWireframe()
    act1.VisibilityOn()

    ren = vtk.vtkRenderer()
    ren.SetBackground(1, 1, 1)

    ren.AddActor(act0)
    ren.AddActor(act1)

    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren)
    renWin.SetSize(600, 700)

    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)
    istyl = vtk.vtkInteractorStyleSwitch()
    istyl.SetCurrentStyleToTrackballCamera()
    iren.SetInteractorStyle(istyl)

    def SelectPolygons(vobj, event):
        vobj.GetPlanes(planes)

    boxWidget = vtk.vtkBoxWidget()
    boxWidget.OutlineCursorWiresOn()
    boxWidget.GetSelectedOutlineProperty().SetColor(1, 0, 1)
    boxWidget.GetOutlineProperty().SetColor(0.1, 0.1, 0.1)
    boxWidget.GetOutlineProperty().SetOpacity(0.8)
    boxWidget.SetPlaceFactor(1.05)
    boxWidget.SetInteractor(iren)
    setInput(boxWidget, apd)
    boxWidget.PlaceWidget()
    boxWidget.AddObserver("InteractionEvent", SelectPolygons)
    boxWidget.On()

    colors.printc('\nCutterWidget:\n Move handles to cut parts of the actor',
                  'm')
    colors.printc(' Press q to continue, Escape to exit', 'm')
    colors.printc((" Press X to save file to", outputname), 'm')

    def cwkeypress(obj, event):
        key = obj.GetKeySym()
        if key == "q" or key == "space" or key == "Return":
            iren.ExitCallback()
        elif key == "X":
            confilter = vtk.vtkPolyDataConnectivityFilter()
            setInput(confilter, clipper.GetOutput())
            confilter.SetExtractionModeToLargestRegion()
            confilter.Update()
            cpd = vtk.vtkCleanPolyData()
            setInput(cpd, confilter.GetOutput())
            cpd.Update()
            w = vtk.vtkPolyDataWriter()
            setInput(w, cpd.GetOutput())
            w.SetFileName(outputname)
            w.Write()
            colors.printc("Saved file: " + outputname, 'g')
        elif key == "Escape":
            exit(0)

    iren.Initialize()
    iren.AddObserver("KeyPressEvent", cwkeypress)
    iren.Start()
    boxWidget.Off()
    return act0
Esempio n. 52
0
selectActor.GetProperty().SetColor(0, 1, 0)
selectActor.VisibilityOff()
selectActor.SetScale(1.01, 1.01, 1.01)

# Create the RenderWindow, Renderer and both Actors
ren = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren)

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

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

ren.AddActor(maceActor)
ren.AddActor(selectActor)

# Add the actors to the renderer, set the background and size
ren.SetBackground(0.1, 0.2, 0.4)
renWin.SetSize(300, 300)


# This callback funciton does the actual work: updates the vtkPlanes
# implicit function.  This in turn causes the pipeline to update.
def SelectPolygons(object, event):
    # object will be the boxWidget
Esempio n. 53
0
    def Execute(self):

        if self.Surface == None:
            self.PrintError('Error: no Surface.')

        self.Clipper = vtk.vtkClipPolyData()
        self.Clipper.SetInput(self.Surface)
        self.Clipper.GenerateClippedOutputOn()
        self.Clipper.SetInsideOut(self.InsideOut)
 
        if self.Interactive:

            if self.WidgetType == "box":
                self.ClipFunction = vtk.vtkPlanes()
            elif self.WidgetType == "sphere":
                self.ClipFunction = vtk.vtkSphere()
       
            self.Clipper.SetClipFunction(self.ClipFunction)

            self.Cutter = vtk.vtkCutter()
            self.Cutter.SetInput(self.Surface)
            self.Cutter.SetCutFunction(self.ClipFunction)

            self.ClippedSurface = vtk.vtkPolyData()
            self.CutLines = vtk.vtkPolyData()

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

            self.vmtkRenderer.RegisterScript(self) 

            mapper = vtk.vtkPolyDataMapper()
            mapper.SetInput(self.Surface)
            mapper.ScalarVisibilityOff()
            self.Actor = vtk.vtkActor()
            self.Actor.SetMapper(mapper)
            self.vmtkRenderer.Renderer.AddActor(self.Actor)

            if self.WidgetType == "box":
                self.ClipWidget = vtk.vtkBoxWidget()
                self.ClipWidget.GetFaceProperty().SetColor(0.6,0.6,0.2)
                self.ClipWidget.GetFaceProperty().SetOpacity(0.25)
            elif self.WidgetType == "sphere":
                self.ClipWidget = vtk.vtkSphereWidget()
                self.ClipWidget.GetSphereProperty().SetColor(0.6,0.6,0.2)
                self.ClipWidget.GetSphereProperty().SetOpacity(0.25)
                self.ClipWidget.GetSelectedSphereProperty().SetColor(0.6,0.0,0.0)
                self.ClipWidget.GetSelectedSphereProperty().SetOpacity(0.75)
                self.ClipWidget.SetRepresentationToSurface()
                self.ClipWidget.SetPhiResolution(20)
                self.ClipWidget.SetThetaResolution(20)

            self.ClipWidget.SetInteractor(self.vmtkRenderer.RenderWindowInteractor)
            
            self.vmtkRenderer.AddKeyBinding('space','Clip.',self.ClipCallback)
            self.vmtkRenderer.AddKeyBinding('i','Interact.',self.InteractCallback)
            self.Display()

            self.Transform = vtk.vtkTransform()
            self.ClipWidget.GetTransform(self.Transform)

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

        else:

            self.Surface.GetPointData().SetActiveScalars(self.ClipArrayName)

            self.Clipper.GenerateClipScalarsOff()
            self.Clipper.SetValue(self.ClipValue)
            self.Clipper.Update()

            self.Cutter = vtk.vtkContourFilter()
            self.Cutter.SetInput(self.Surface)
            self.Cutter.SetValue(0,self.ClipValue)
            self.Cutter.Update()

            self.Surface = self.Clipper.GetOutput()
            self.ClippedSurface = self.Clipper.GetClippedOutput()

            self.CutLines = self.Cutter.GetOutput()

        if self.CleanOutput == 1:

            cleaner = vtk.vtkCleanPolyData()
            cleaner.SetInput(self.Surface)
            cleaner.Update()
            self.Surface = cleaner.GetOutput()

            cleaner = vtk.vtkCleanPolyData()
            cleaner.SetInput(self.ClippedSurface)
            cleaner.Update()
            self.ClippedSurface = cleaner.GetOutput()

            cleaner = vtk.vtkCleanPolyData()
            cleaner.SetInput(self.CutLines)
            cleaner.Update()
            stripper = vtk.vtkStripper()
            stripper.SetInput(cleaner.GetOutput())
            stripper.Update()
            self.CutLines = stripper.GetOutput()

        if self.Surface.GetSource():
            self.Surface.GetSource().UnRegisterAllOutputs()
Esempio n. 54
0
    def __init__(self, parent=None):
        QtWidgets.QMainWindow.__init__(self, parent)

        self.frame = QtWidgets.QFrame()

        self.vl = QtWidgets.QVBoxLayout()
        self.vtkWidget = QVTKRenderWindowInteractor(self.frame)
        self.vl.addWidget(self.vtkWidget)

        self.ren = vtk.vtkRenderer()
        self.renWin= self.vtkWidget.GetRenderWindow()
        self.renWin.AddRenderer(self.ren)
        self.iren = self.renWin.GetInteractor()
        self.iren.SetRenderWindow(self.renWin)

        dicomReader = vtk.vtk.vtkDICOMImageReader()
        dicomReader.SetDirectoryName(r'G:\PythonTrainFaile\SE2')#G:\PythonTrainFaile\SE2  F:\sliver_07\segmentation-0.nii
        dicomReader.Update()
        srange = dicomReader.GetOutput().GetScalarRange()
        print(dicomReader.GetOutput().GetDimensions())
        min = srange[0]
        max = srange[1]
        diff = max - min
        slope = 4000 / diff
        inter = -slope * min
        shift = inter / slope

        shifter = vtk.vtkImageShiftScale()  # 对偏移和比例参数来对图像数据进行操作  数据转换
        shifter.SetShift(shift)
        shifter.SetScale(slope)
        shifter.SetOutputScalarTypeToUnsignedShort()
        shifter.SetInputData(dicomReader.GetOutput())
        shifter.ReleaseDataFlagOff()
        shifter.Update()
        print(min, max, slope, inter, shift)
        tfun = vtk.vtkPiecewiseFunction()  # 梯度不透明度函数
        tfun.AddPoint(2000, 0)
        tfun.AddPoint(2300.0, 0.3)
        tfun.AddPoint(2501.0, 1)
        tfun.AddPoint(2600.0, 1)
        tfun.AddPoint(2700.0, 1)
        tfun.AddPoint(2900.0, 1)
        tfun.AddPoint(3024.0, 1)

        ctfun = vtk.vtkColorTransferFunction()  # 颜色传输函数
        ctfun.AddRGBPoint(0.0, 0.5, 0.0, 0.0)
        ctfun.AddRGBPoint(600.0, 1.0, 0.5, 0.5)
        ctfun.AddRGBPoint(1280.0, 0.9, 0.2, 0.3)
        ctfun.AddRGBPoint(1960.0, 0.81, 0.27, 0.1)
        ctfun.AddRGBPoint(2200.0, 0.9, 0.2, 0.3)
        ctfun.AddRGBPoint(2500.0, 1, 0.5, 0.5)
        ctfun.AddRGBPoint(3024.0, 0.5, 0.5, 0.5)
        self.volumeMapper = vtk.vtkGPUVolumeRayCastMapper()
        self.volumeMapper.SetInputConnection(shifter.GetOutputPort())
        volumeProperty = vtk.vtkVolumeProperty()
        volumeProperty.SetColor(ctfun)
        volumeProperty.SetScalarOpacity(tfun)
        volumeProperty.SetInterpolationTypeToLinear()
        volumeProperty.ShadeOn()
        newvol = vtk.vtkVolume()
        newvol.SetMapper(self.volumeMapper)
        newvol.SetProperty(volumeProperty)
        outline = vtk.vtkOutlineFilter()
        outline.SetInputConnection(shifter.GetOutputPort())
        outlineMapper = vtk.vtkPolyDataMapper()
        outlineMapper.SetInputConnection(outline.GetOutputPort())
        outlineActor = vtk.vtkActor()
        outlineActor.SetMapper(outlineMapper)

        # Create an actor
        boxWidget = vtk.vtkBoxWidget()
        boxWidget.SetInteractor(self.iren)
        boxWidget.SetPlaceFactor(1.0)

        # Add the actors to the renderer, set the background and size
        self.ren.AddActor(outlineActor)
        self.ren.AddVolume(newvol)

        self.ren.SetBackground(0, 0, 0)
        self.renWin.SetSize(600, 600)

        self.planes = vtk.vtkPlanes()

        boxWidget.PlaceWidget()
        boxWidget.InsideOutOn()
        boxWidget.AddObserver("StartInteractionEvent", self.StartInteraction)
        boxWidget.AddObserver("InteractionEvent",  self.ClipVolumeRender)
        boxWidget.AddObserver("EndInteractionEvent",  self.EndInteraction)

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

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

        self.ren.ResetCamera()
        self.frame.setLayout(self.vl)
        self.setCentralWidget(self.frame)

        self.show()
        self.iren.Initialize()
        self.renWin.Render()
        self.iren.Start()
Esempio n. 55
0
    def BuildView(self):

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

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

        self.vmtkRenderer.RegisterScript(self) 

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

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

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

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

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

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

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

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

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

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