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

        self.vmtkRenderer.RegisterScript(self.Script)

        self.vmtkRenderer.AddKeyBinding('u', 'Undo.', self.UndoCallback)
        self.vmtkRenderer.AddKeyBinding('space', 'Add points.',
                                        self.PickCallback)

        self.InputInfo(
            'Please position the mouse and press space to add target points, \'u\' to undo\n'
        )

        # this is necessary to set up the async watch loop.
        any = 0
        while any == 0:
            self.vmtkRenderer.Render()
            try:
                any = self.CurrentPickedPolyData
            except AttributeError:
                any = None

        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
Esempio n. 2
0
    def Execute(self):

        if (self._Surface == None):
            self.PrintError(
                'vmtkPickPointSeedSelector Error: Surface not set.')
            return

        self._TargetSeedIds.Initialize()

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

        self.vmtkRenderer.RegisterScript(self.Script)

        ##self.vmtkRenderer.RenderWindowInteractor.AddObserver("KeyPressEvent", self.KeyPressed)
        self.vmtkRenderer.AddKeyBinding('u', 'Undo.', self.UndoCallback)
        self.vmtkRenderer.AddKeyBinding('space', 'Add points.',
                                        self.PickCallback)

        self.InputInfo(
            'Please position the mouse and press space to add target points, \'u\' to undo\n'
        )

        any = 0
        while any == 0:
            self.InitializeSeeds()
            self.vmtkRenderer.Render()
            try:
                any = self.PickedScalarData.GetValue(0)
            except AttributeError:
                any = None
        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
Esempio n. 3
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.Surface == None:
            self.PrintError('Error: no Surface.')

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

        self.vmtkRenderer.RegisterScript(self)

        triangleFilter = vtk.vtkTriangleFilter()
        triangleFilter.SetInputData(self.Surface)
        triangleFilter.Update()

        self.Surface = triangleFilter.GetOutput()

        contourScalars = vtk.vtkDoubleArray()
        contourScalars.SetNumberOfComponents(1)
        contourScalars.SetNumberOfTuples(self.Surface.GetNumberOfPoints())
        contourScalars.SetName(self.ContourScalarsArrayName)
        contourScalars.FillComponent(0,self.OutsideValue)

        self.Surface.GetPointData().AddArray(contourScalars)
        self.Surface.GetPointData().SetActiveScalars(self.ContourScalarsArrayName)

        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputData(self.Surface)
        mapper.ScalarVisibilityOn()
        self.Actor = vtk.vtkActor()
        self.Actor.SetMapper(mapper)
        self.Actor.GetMapper().SetScalarRange(-1.0,0.0)
        self.vmtkRenderer.Renderer.AddActor(self.Actor)

        self.ContourWidget = vtk.vtkContourWidget()
        self.ContourWidget.SetInteractor(self.vmtkRenderer.RenderWindowInteractor)

        rep = vtk.vtkOrientedGlyphContourRepresentation.SafeDownCast(self.ContourWidget.GetRepresentation())
        rep.GetLinesProperty().SetColor(1, 0.2, 0)
        rep.GetLinesProperty().SetLineWidth(3.0)

        pointPlacer = vtk.vtkPolygonalSurfacePointPlacer()
        pointPlacer.AddProp(self.Actor)
        pointPlacer.GetPolys().AddItem(self.Surface)
        rep.SetPointPlacer(pointPlacer)

        self.Interpolator = vtk.vtkPolygonalSurfaceContourLineInterpolator()
        self.Interpolator.GetPolys().AddItem(self.Surface)
        rep.SetLineInterpolator(self.Interpolator)

        self.vmtkRenderer.AddKeyBinding('space','Generate scalars',self.ScalarsCallback)
        self.vmtkRenderer.AddKeyBinding('d','Delete contour',self.DeleteContourCallback)
        self.vmtkRenderer.AddKeyBinding('i','Start interaction',self.InteractCallback)
        self.Display()

        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
Esempio n. 5
0
    def Execute(self):

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

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

        self.vmtkRenderer.RegisterScript(self) 

        triangleFilter = vtk.vtkTriangleFilter()
        triangleFilter.SetInputData(self.Surface)
        triangleFilter.Update()

        self.Surface = triangleFilter.GetOutput()

        contourScalars = vtk.vtkDoubleArray()
        contourScalars.SetNumberOfComponents(1)
        contourScalars.SetNumberOfTuples(self.Surface.GetNumberOfPoints())
        contourScalars.SetName(self.ContourScalarsArrayName)
        contourScalars.FillComponent(0,self.OutsideValue)

        self.Surface.GetPointData().AddArray(contourScalars)
        self.Surface.GetPointData().SetActiveScalars(self.ContourScalarsArrayName)

        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputData(self.Surface)
        mapper.ScalarVisibilityOn()
        self.Actor = vtk.vtkActor()
        self.Actor.SetMapper(mapper)
        self.Actor.GetMapper().SetScalarRange(-1.0,0.0)
        self.vmtkRenderer.Renderer.AddActor(self.Actor)

        self.ContourWidget = vtk.vtkContourWidget()
        self.ContourWidget.SetInteractor(self.vmtkRenderer.RenderWindowInteractor)

        rep = vtk.vtkOrientedGlyphContourRepresentation.SafeDownCast(self.ContourWidget.GetRepresentation())
        rep.GetLinesProperty().SetColor(1, 0.2, 0)
        rep.GetLinesProperty().SetLineWidth(3.0)

        pointPlacer = vtk.vtkPolygonalSurfacePointPlacer()
        pointPlacer.AddProp(self.Actor)
        pointPlacer.GetPolys().AddItem(self.Surface)
        rep.SetPointPlacer(pointPlacer)

        self.Interpolator = vtk.vtkPolygonalSurfaceContourLineInterpolator()
        self.Interpolator.GetPolys().AddItem(self.Surface)
        rep.SetLineInterpolator(self.Interpolator)

        self.vmtkRenderer.AddKeyBinding('space','Generate scalars',self.ScalarsCallback)
        self.vmtkRenderer.AddKeyBinding('d','Delete contour',self.DeleteContourCallback)
        self.vmtkRenderer.AddKeyBinding('i','Start interaction',self.InteractCallback)
        self.Display()

        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
    def Execute(self):
        from vmtk import vmtkscripts
        if self.Surface == None:
            self.PrintError('Error: no Surface.')

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

        self.vmtkRenderer.RegisterScript(self)

        triangleFilter = vtk.vtkTriangleFilter()
        triangleFilter.SetInputData(self.Surface)
        triangleFilter.Update()

        self.Surface = triangleFilter.GetOutput()

        self.tagviewer = vmtkscripts.vmtkSurfaceViewer()
        self.tagviewer.Surface = self.Surface
        self.tagviewer.vmtkRenderer = self.vmtkRenderer
        self.tagviewer.Representation = 'edges'
        self.tagviewer.Opacity = self.Opacity
        self.tagviewer.Execute()

        self.ContourWidget = vtk.vtkContourWidget()
        self.ContourWidget.SetInteractor(
            self.vmtkRenderer.RenderWindowInteractor)

        rep = vtk.vtkOrientedGlyphContourRepresentation.SafeDownCast(
            self.ContourWidget.GetRepresentation())
        rep.GetLinesProperty().SetColor(1, 0, 0)
        rep.GetLinesProperty().SetLineWidth(4.0)

        pointPlacer = vtk.vtkPolygonalSurfacePointPlacer()
        pointPlacer.AddProp(self.tagviewer.Actor)
        pointPlacer.GetPolys().AddItem(self.Surface)
        rep.SetPointPlacer(pointPlacer)

        self.Interpolator = vtk.vtkPolygonalSurfaceContourLineInterpolator()
        self.Interpolator.GetPolys().AddItem(self.Surface)
        rep.SetLineInterpolator(self.Interpolator)

        self.InputInfo("Building loop ...\n")

        self.vmtkRenderer.AddKeyBinding('space', 'Generate loop',
                                        self.LoopCallback)
        self.vmtkRenderer.AddKeyBinding('d', 'Delete contour',
                                        self.DeleteContourCallback)
        self.vmtkRenderer.AddKeyBinding('i', 'Start/stop contour drawing',
                                        self.InteractCallback)

        self.Display()

        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
Esempio n. 7
0
    def Execute(self):
        if self._Surface is None:
            self.PrintError(
                'vmtkPickPointSeedSelector Error: Surface not set.')
            return

        self._TargetSeedIds.Initialize()

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

        glyphs = vtk.vtkGlyph3D()
        glyphSource = vtk.vtkSphereSource()
        glyphs.SetInputData(self.PickedSeeds)
        glyphs.SetSourceConnection(glyphSource.GetOutputPort())
        glyphs.SetScaleModeToDataScalingOff()
        glyphs.SetScaleFactor(self._Surface.GetLength() * 0.01)

        glyphMapper = vtk.vtkPolyDataMapper()
        glyphMapper.SetInputData(glyphs.GetOutput())
        glyphMapper.SetInputConnection(glyphs.GetOutputPort())

        self.SeedActor = vtk.vtkActor()
        self.SeedActor.SetMapper(glyphMapper)
        self.SeedActor.GetProperty().SetColor(1.0, 0.0, 0.0)
        self.SeedActor.PickableOff()

        self.vmtkRenderer.Renderer.AddActor(self.SeedActor)
        self.vmtkRenderer.AddKeyBinding('u', 'Undo.', self.UndoCallback)
        self.vmtkRenderer.AddKeyBinding('space', 'Add points.',
                                        self.PickCallback)

        surfaceMapper = vtk.vtkPolyDataMapper()
        surfaceMapper.SetInputData(self._Surface)
        surfaceMapper.ScalarVisibilityOff()

        surfaceActor = vtk.vtkActor()
        surfaceActor.SetMapper(surfaceMapper)
        surfaceActor.GetProperty().SetOpacity(1.0)

        self.vmtkRenderer.Renderer.AddActor(surfaceActor)

        guiText = VtkText(self.text)
        self.vmtkRenderer.Renderer.AddActor(guiText.text)

        any = 0
        while any == 0:
            self.InitializeSeeds()
            self.vmtkRenderer.Render()
            any = self.PickedSeedIds.GetNumberOfIds()
        self._TargetSeedIds.DeepCopy(self.PickedSeedIds)

        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
Esempio n. 8
0
    def Execute(self):

        self._SourceSeedIds.Initialize()

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

        glyphs = vtk.vtkGlyph3D()
        glyphSource = vtk.vtkSphereSource()
        glyphs.SetInputData(self.PickedSeeds)
        glyphs.SetSourceConnection(glyphSource.GetOutputPort())
        glyphs.SetScaleModeToDataScalingOff()
        glyphs.SetScaleFactor(self._Surface.GetLength()*0.01)
        glyphMapper = vtk.vtkPolyDataMapper()
        glyphMapper.SetInputConnection(glyphs.GetOutputPort())
        self.SeedActor = vtk.vtkActor()
        self.SeedActor.SetMapper(glyphMapper)
        self.SeedActor.GetProperty().SetColor(1.0,0.0,0.0)
        self.SeedActor.PickableOff()
        self.vmtkRenderer.Renderer.AddActor(self.SeedActor)

        self.vmtkRenderer.AddKeyBinding('u','Undo.',self.UndoCallback)
        self.vmtkRenderer.AddKeyBinding('space','Add points.',self.PickCallback)
        surfaceMapper = vtk.vtkPolyDataMapper()
        surfaceMapper.SetInputData(self._Surface)
        surfaceMapper.ScalarVisibilityOff()
        surfaceActor = vtk.vtkActor()
        surfaceActor.SetMapper(surfaceMapper)
        surfaceActor.GetProperty().SetOpacity(1)

        self.vmtkRenderer.Renderer.AddActor(surfaceActor)

        # create a text actor
        txt = vtk.vtkTextActor()
        info = "Position mouse and press space. "
        info += "Select seeds in this order: RSpv, RIpv, LIpv, LSpv. "
        info += "Fifth seed requires --use_laa_seed command."
        txt.SetInput(info)
        txtprop=txt.GetTextProperty()
        txtprop.SetFontFamilyToArial()
        txtprop.SetFontSize(13)
        txtprop.SetColor(1, 1, 1)
        txt.SetDisplayPosition(0, 10)
        self.vmtkRenderer.Renderer.AddActor(txt)

        any = 0
        while any == 0:
            self.InitializeSeeds()
            self.vmtkRenderer.Render()
            any = self.PickedSeedIds.GetNumberOfIds()
        self._SourceSeedIds.DeepCopy(self.PickedSeedIds)

        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
Esempio n. 9
0
    def Execute(self):
        from vmtk import vmtkscripts
        if self.Surface == None:
            self.PrintError('Error: no Surface.')

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

        self.vmtkRenderer.RegisterScript(self) 

        triangleFilter = vtk.vtkTriangleFilter()
        triangleFilter.SetInputData(self.Surface)
        triangleFilter.Update()

        self.Surface = triangleFilter.GetOutput()

        self.tagviewer = vmtkscripts.vmtkSurfaceViewer()
        self.tagviewer.Surface = self.Surface
        self.tagviewer.vmtkRenderer = self.vmtkRenderer
        self.tagviewer.Representation = 'edges'
        self.tagviewer.Opacity = self.Opacity
        self.tagviewer.Execute()

        self.ContourWidget = vtk.vtkContourWidget()
        self.ContourWidget.SetInteractor(self.vmtkRenderer.RenderWindowInteractor)

        rep = vtk.vtkOrientedGlyphContourRepresentation.SafeDownCast(self.ContourWidget.GetRepresentation())
        rep.GetLinesProperty().SetColor(1, 0, 0)
        rep.GetLinesProperty().SetLineWidth(4.0)

        pointPlacer = vtk.vtkPolygonalSurfacePointPlacer()
        pointPlacer.AddProp(self.tagviewer.Actor)
        pointPlacer.GetPolys().AddItem(self.Surface)
        rep.SetPointPlacer(pointPlacer)

        self.Interpolator = vtk.vtkPolygonalSurfaceContourLineInterpolator()
        self.Interpolator.GetPolys().AddItem(self.Surface)
        rep.SetLineInterpolator(self.Interpolator)

        self.InputInfo("Building loop ...\n")

        self.vmtkRenderer.AddKeyBinding('space','Generate loop',self.LoopCallback)
        self.vmtkRenderer.AddKeyBinding('d','Delete contour',self.DeleteContourCallback)
        self.vmtkRenderer.AddKeyBinding('i','Start/stop contour drawing',self.InteractCallback)


        self.Display()


        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
Esempio n. 10
0
    def BuildView(self):

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

        self.vmtkRenderer.RegisterScript(self)

        self.PlaneWidget = vtk.vtkImplicitPlaneWidget()

        if self.Actor != None:
            self.vmtkRenderer.Renderer.RemoveActor(self.Actor)

        if self.Mesh != None:

            self.MeshCutFilter = vtk.vtkCutter()
            self.MeshCutFilter.SetInputData(self.Mesh)
            cutPlane = vtk.vtkPlane()
            self.PlaneWidget.GetPlane(cutPlane)
            self.MeshCutFilter.SetCutFunction(cutPlane)
            self.MeshCutFilter.Update()
            self.Surface = self.MeshCutFilter.GetOutput()

            self.PlaneWidget.AddObserver("StartInteractionEvent",
                                         self.StartPlaneCallback)
            self.PlaneWidget.AddObserver("EndInteractionEvent",
                                         self.EndPlaneCallback)

            mapper = vtk.vtkDataSetMapper()
            mapper.SetInputData(self.Mesh)

            self.Actor = vtk.vtkActor()
            self.Actor.SetMapper(mapper)
            self.vmtkRenderer.Renderer.AddActor(self.Actor)
            self.Actor.GetProperty().SetOpacity(self.Opacity)

        self.PlaneWidget.SetInteractor(
            self.vmtkRenderer.RenderWindowInteractor)
        self.PlaneWidget.SetPlaceFactor(1.25)
        self.PlaneWidget.DrawPlaneOn()
        self.PlaneWidget.GetPlaneProperty().SetOpacity(0.1)
        self.PlaneWidget.SetProp3D(self.Actor)
        self.PlaneWidget.PlaceWidget()
        self.PlaneWidget.SetOrigin(self.Actor.GetCenter())
        self.PlaneWidget.On()

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

        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
Esempio n. 11
0
    def BuildView(self):

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

        self.vmtkRenderer.RegisterScript(self) 

        self.PlaneWidget = vtk.vtkImplicitPlaneWidget()
        
        if self.Actor != None:
            self.vmtkRenderer.Renderer.RemoveActor(self.Actor)

        if self.Mesh != None:

            self.MeshCutFilter = vtk.vtkCutter()
            self.MeshCutFilter.SetInputData(self.Mesh)
            cutPlane = vtk.vtkPlane()
            self.PlaneWidget.GetPlane(cutPlane)
            self.MeshCutFilter.SetCutFunction(cutPlane)
            self.MeshCutFilter.Update()
            self.Surface = self.MeshCutFilter.GetOutput()
 
            self.PlaneWidget.AddObserver("StartInteractionEvent",self.StartPlaneCallback)
            self.PlaneWidget.AddObserver("EndInteractionEvent",self.EndPlaneCallback)

            mapper = vtk.vtkDataSetMapper()
            mapper.SetInputData(self.Mesh)
            
            self.Actor = vtk.vtkActor()
            self.Actor.SetMapper(mapper)
            self.vmtkRenderer.Renderer.AddActor(self.Actor)
            self.Actor.GetProperty().SetOpacity(self.Opacity)
            
         
        self.PlaneWidget.SetInteractor(self.vmtkRenderer.RenderWindowInteractor)
        self.PlaneWidget.SetPlaceFactor(1.25)
        self.PlaneWidget.DrawPlaneOn()
        self.PlaneWidget.GetPlaneProperty().SetOpacity(0.1)
        self.PlaneWidget.SetProp3D(self.Actor)
        self.PlaneWidget.PlaceWidget()
        self.PlaneWidget.SetOrigin(self.Actor.GetCenter())
        self.PlaneWidget.On()
        
        if (self.Display == 1):
            self.vmtkRenderer.Render()

        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
Esempio n. 12
0
def surface_smooth():
    '''
    网格表面的平滑
    '''
    input_file = 'id2_model.vtp'
    output_file = 'id2_mode_sm_laplace.vtp'
    surfacereader = sr.vmtkSurfaceReader()
    surfacereader.InputFileName = input_file
    surfacereader.Execute()

    # 没有平滑的网格表面
    originsurface_mapper = vtk.vtkPolyDataMapper()
    originsurface_mapper.SetInputData(surfacereader.Surface)
    originsurface_actor = vtk.vtkActor()
    originsurface_actor.SetMapper(originsurface_mapper)
    color = [0, 1, 0]
    originsurface_actor.GetProperty().SetColor(color)
    originsurface_actor.GetProperty().SetOpacity(0.8)

    surfacesmooth = ss.vmtkSurfaceSmoothing()
    surfacesmooth.Surface = surfacereader.Surface
    surfacesmooth.NumberOfIterations = 30
    surfacesmooth.PassBand = 1.0
    surfacesmooth.RelaxationFactor = 0.01
    surfacesmooth.BoundarySmoothing = 1
    surfacesmooth.NormalizeCoordinates = 1
    surfacesmooth.Method = "laplace"  # ["taubin","laplace"]
    surfacesmooth.Execute()

    renderer = rd.vmtkRenderer()
    renderer.Initialize()
    renderer.Renderer.AddActor(originsurface_actor)

    surface_viewer = sv.vmtkSurfaceViewer()
    surface_viewer.vmtkRenderer = renderer
    surface_viewer.Surface = surfacesmooth.Surface
    surface_viewer.Display = 1
    surface_viewer.Color = [1.0, 0, 0]
    surface_viewer.ColorMap = "cooltowarm"
    surface_viewer.Execute()

    surface_writer = sw.vmtkSurfaceWriter()
    surface_writer.OutputFileName = output_file
    surface_writer.Surface = surfacesmooth.Surface
    surface_writer.Execute()
Esempio n. 13
0
    def Execute(self):
        if (self.Image == None) & (self.Display == 1):
            self.PrintError('Error: no Image.')

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

        self.vmtkRenderer.RegisterScript(self)

        ##self.PrintLog('Ctrl +  left click to add seed.')
        self.Picker = vtk.vtkCellPicker()
        self.Picker.SetTolerance(0.005)

        self.PlaneWidgetX = vtkvmtk.vtkvmtkImagePlaneWidget()
        self.PlaneWidgetX.SetInteractor(
            self.vmtkRenderer.RenderWindowInteractor)
        self.PlaneWidgetX.AddObserver("StartInteractionEvent", self.AddSeed)
        self.PlaneWidgetX.SetPicker(self.Picker)
        self.PlaneWidgetY = vtkvmtk.vtkvmtkImagePlaneWidget()
        self.PlaneWidgetY.SetInteractor(
            self.vmtkRenderer.RenderWindowInteractor)
        self.PlaneWidgetY.AddObserver("StartInteractionEvent", self.AddSeed)
        self.PlaneWidgetY.SetPicker(self.Picker)
        self.PlaneWidgetZ = vtkvmtk.vtkvmtkImagePlaneWidget()
        self.PlaneWidgetZ.SetInteractor(
            self.vmtkRenderer.RenderWindowInteractor)
        self.PlaneWidgetZ.AddObserver("StartInteractionEvent", self.AddSeed)
        self.PlaneWidgetZ.SetPicker(self.Picker)

        self.Seeds = vtk.vtkPolyData()
        self.InitializeSeeds()

        self.BuildView()

        self.WidgetsOff()

        if not self.KeepSeeds:
            self.vmtkRenderer.Renderer.RemoveActor(self.SeedActor)

        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
Esempio n. 14
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. 15
0
def centerlines():
    '''
    显示中心线
    '''
    input_file = "data\\levelSet\\vessellevelset_0.vtp"
    surfacereader = sr.vmtkSurfaceReader()
    surfacereader.InputFileName = input_file
    surfacereader.Execute()

    centerline = cl.vmtkCenterlines()
    centerline.Surface = surfacereader.Surface
    centerline.Execute()
    ''' centerline_mapper = vtk.vtkPolyDataMapper()
    centerline_mapper.SetInputData(centerline.Centerlines)
    centerline_actor = vtk.vtkActor()
    centerline_actor.SetMapper(centerline_mapper)

    centerline.vmtkRenderer.Renderer.AddActor(centerline_actor)
    surface_actor = centerline.vmtkRenderer.Renderer.GetActors().GetLastActor()
    surface_actor.GetProperty().SetOpacity(0)
    surface_actor.GetProperty().SetColor([0.1, 0.2, 0.5])
    centerline.vmtkRenderer.Render()'''

    surface_mapper = vtk.vtkPolyDataMapper()
    surface_mapper.SetInputData(surfacereader.Surface)
    surface_actor = vtk.vtkActor()
    surface_actor.SetMapper(surface_mapper)
    surface_actor.GetProperty().SetOpacity(0.3)
    color = [0.5, 0.6, 0.7]
    surface_actor.GetProperty().SetColor(color)

    renderer = rd.vmtkRenderer()
    renderer.Initialize()
    renderer.Renderer.AddActor(surface_actor)

    surfaceviewer = sv.vmtkSurfaceViewer()
    surfaceviewer.Surface = centerline.Centerlines
    # surfaceviwer.Surface = centerline.VoronoiDiagram
    surfaceviewer.Color = [0.5, 0.6, 0.7]
    surfaceviewer.ColorMap = "rainbow"  # "rainbow","blackbody","cooltowarm","grayscale"
    surfaceviewer.vmtkRenderer = renderer  # centerline中vmtkrenderer在调用结束后,就回收内存了
    surfaceviewer.ArrayName = "MaximumInscribedSphereRadius"
    surfaceviewer.Execute()
Esempio n. 16
0
    def Execute(self):
        if (self.Image == None) & (self.Display == 1):
            self.PrintError('Error: no Image.')

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

        self.vmtkRenderer.RegisterScript(self) 

        ##self.PrintLog('Ctrl +  left click to add seed.')
        self.Picker = vtk.vtkCellPicker()
        self.Picker.SetTolerance(0.005)

        self.PlaneWidgetX = vtkvmtk.vtkvmtkImagePlaneWidget()
        self.PlaneWidgetX.SetInteractor(self.vmtkRenderer.RenderWindowInteractor)
        self.PlaneWidgetX.AddObserver("StartInteractionEvent", self.AddSeed)
        self.PlaneWidgetX.SetPicker(self.Picker)
        self.PlaneWidgetY = vtkvmtk.vtkvmtkImagePlaneWidget()
        self.PlaneWidgetY.SetInteractor(self.vmtkRenderer.RenderWindowInteractor)
        self.PlaneWidgetY.AddObserver("StartInteractionEvent", self.AddSeed)
        self.PlaneWidgetY.SetPicker(self.Picker)
        self.PlaneWidgetZ = vtkvmtk.vtkvmtkImagePlaneWidget()
        self.PlaneWidgetZ.SetInteractor(self.vmtkRenderer.RenderWindowInteractor)
        self.PlaneWidgetZ.AddObserver("StartInteractionEvent", self.AddSeed)
        self.PlaneWidgetZ.SetPicker(self.Picker)

        self.Seeds = vtk.vtkPolyData()
        self.InitializeSeeds()

        self.BuildView()
        
        self.WidgetsOff()

        if not self.KeepSeeds:
            self.vmtkRenderer.Renderer.RemoveActor(self.SeedActor)

        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
Esempio n. 17
0
    def Execute(self):
        if not self.vmtkRenderer:
            self.vmtkRenderer = vmtkrenderer.vmtkRenderer()
            self.vmtkRenderer.Initialize()
            self.OwnRenderer = 1

        self.vmtkRenderer.RegisterScript(self.Script)

        self.vmtkRenderer.AddKeyBinding('u','Undo.',self.UndoCallback)
        self.vmtkRenderer.AddKeyBinding('space','Add points.',self.PickCallback)

        self.InputInfo('Please position the mouse and press space to add target points, \'u\' to undo\n')

        # this is necessary to set up the async watch loop. 
        any = 0
        while any == 0:
            self.vmtkRenderer.Render()
            try:
                any = self.CurrentPickedPolyData
            except AttributeError:
                any = None

        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
Esempio n. 18
0
    def BuildView(self):

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

        if self.Actor != None:
            self.vmtkRenderer.Renderer.RemoveActor(self.Actor)

        if self.ScalarBarActor != None:
            self.vmtkRenderer.Renderer.RemoveActor(self.ScalarBarActor)

        if self.Mesh != None:
            self.InitialMesh = self.Mesh
            self.DisplayMesh = self.Mesh
            mapper = vtk.vtkDataSetMapper()
            mapper.SetInputData(self.DisplayMesh)
            array = None
            if (self.ArrayName != ''):
                if self.DisplayCellData == 0:
                  self.Mesh.GetPointData().SetActiveScalars(self.ArrayName)
                  array = self.Mesh.GetPointData().GetScalars()
                else:
                  self.Mesh.GetCellData().SetActiveScalars(self.ArrayName)
                  array = self.Mesh.GetCellData().GetScalars()
                  mapper.SetScalarModeToUseCellData()
            if (array != None):
                if (self.ScalarRange[1] > self.ScalarRange[0]):
                    mapper.SetScalarRange(self.ScalarRange)
                else:
                    mapper.SetScalarRange(array.GetRange(0))
                if (self.Grayscale == 1):
                    lut = vtk.vtkLookupTable()
                    lut.SetValueRange(0.0,1.0)
                    lut.SetSaturationRange(0.0,0.0)
                    mapper.SetLookupTable(lut)
                
            
            self.Actor = vtk.vtkActor()
            self.Actor.SetMapper(mapper)
            if (self.Color[0] >= 0.0):
                self.Actor.GetProperty().SetColor(self.Color)
            if (self.FlatInterpolation == 1):
                self.Actor.GetProperty().SetInterpolationToFlat()
            self.Actor.GetProperty().SetOpacity(self.Opacity)
            self.vmtkRenderer.Renderer.AddActor(self.Actor)

        if (self.Legend == 1) & (self.Actor != None):
            self.ScalarBarActor = vtk.vtkScalarBarActor()
            self.ScalarBarActor.SetLookupTable(self.Actor.GetMapper().GetLookupTable())
            self.ScalarBarActor.GetLabelTextProperty().ItalicOff()
            self.ScalarBarActor.GetLabelTextProperty().BoldOff()
            self.ScalarBarActor.GetLabelTextProperty().ShadowOff()
##             self.ScalarBarActor.GetLabelTextProperty().SetColor(0.0,0.0,0.0)
            self.ScalarBarActor.SetLabelFormat('%.2f')
            self.vmtkRenderer.Renderer.AddActor(self.ScalarBarActor)

        #self.vmtkRenderer.RenderWindowInteractor.AddObserver("KeyPressEvent", self.KeyPressed)
        self.vmtkRenderer.AddKeyBinding('i','Interact.',self.InteractCallback)
        self.vmtkRenderer.AddKeyBinding('c','Clip.',self.ClipCallback)
        self.vmtkRenderer.AddKeyBinding('e','Extract.',self.ExtractCallback)
        self.vmtkRenderer.AddKeyBinding('n','Show clipped area.',self.NCallback)
        self.vmtkRenderer.AddKeyBinding('d','Switch clipped/unclipped area.',self.DCallback)
        self.vmtkRenderer.AddKeyBinding('t','Redo.',self.TCallback)
        self.vmtkRenderer.AddKeyBinding('u','Undo.',self.UndoCallback)
        self.PlaneWidget = vtk.vtkImplicitPlaneWidget()
        self.PlaneWidget.SetInteractor(self.vmtkRenderer.RenderWindowInteractor)
        self.PlaneWidget.SetPlaceFactor(1.25)
        self.PlaneWidget.DrawPlaneOff()
        self.PlaneWidget.SetProp3D(self.Actor)
        self.PlaneWidget.PlaceWidget()
        #Work around bug/strange behaviour in vtk
        self.PlaneWidget.SetOrigin(self.Actor.GetCenter())
          
        
        if (self.Display == 1):
            self.vmtkRenderer.Render()

        self.Mesh = self.InitialMesh
        
        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
Esempio n. 19
0
    def Execute(self):

        if self.Surface == None:
            self.PrintError('Error: No input surface.')

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

        self.vmtkRenderer.RegisterScript(self)

        glyphs = vtk.vtkGlyph3D()
        glyphSource = vtk.vtkSphereSource()
        glyphSource.SetRadius(1)
        glyphs.SetInputData(self.Spheres)
        glyphs.SetSourceConnection(glyphSource.GetOutputPort())
        glyphs.SetScaleModeToScaleByScalar()
        glyphs.SetScaleFactor(1.)
        glyphMapper = vtk.vtkPolyDataMapper()
        glyphMapper.SetInputConnection(glyphs.GetOutputPort())
        glyphMapper.ScalarVisibilityOff()
        self.SpheresActor = vtk.vtkActor()
        self.SpheresActor.SetMapper(glyphMapper)
        self.SpheresActor.GetProperty().SetColor(1.0, 0.0, 0.0)
        self.SpheresActor.GetProperty().SetOpacity(self.Opacity)
        self.SpheresActor.PickableOff()
        self.vmtkRenderer.Renderer.AddActor(self.SpheresActor)

        examineGlyphs = vtk.vtkGlyph3D()
        examineGlyphSource = vtk.vtkSphereSource()
        examineGlyphSource.SetRadius(1)
        examineGlyphs.SetInputData(self.ExamineSpheres)
        examineGlyphs.SetSourceConnection(examineGlyphSource.GetOutputPort())
        examineGlyphs.SetScaleModeToScaleByScalar()
        examineGlyphs.SetScaleFactor(1.)
        examineGlyphMapper = vtk.vtkPolyDataMapper()
        examineGlyphMapper.SetInputConnection(examineGlyphs.GetOutputPort())
        examineGlyphMapper.ScalarVisibilityOff()
        self.ExamineSpheresActor = vtk.vtkActor()
        self.ExamineSpheresActor.SetMapper(examineGlyphMapper)
        self.ExamineSpheresActor.GetProperty().SetColor(0.0, 1.0, 0.0)
        self.ExamineSpheresActor.GetProperty().SetOpacity(self.Opacity)
        self.ExamineSpheresActor.PickableOff()
        self.ExamineSpheresActor.VisibilityOff()
        self.vmtkRenderer.Renderer.AddActor(self.ExamineSpheresActor)

        #self.vmtkRenderer.RenderWindowInteractor.AddObserver("KeyPressEvent", self.KeyPressed)

        self.vmtkRenderer.AddKeyBinding('u', 'undo', self.UndoCallback)
        self.vmtkRenderer.AddKeyBinding('plus', 'Increase sphere radius',
                                        self.PlusCallback)
        self.vmtkRenderer.AddKeyBinding('minus', 'Decrease sphere radius',
                                        self.MinusCallback)
        self.vmtkRenderer.AddKeyBinding('n', 'Show next sphere',
                                        self.NextSphereCallback)
        self.vmtkRenderer.AddKeyBinding('v', 'Show previous sphere',
                                        self.PreviousSphereCallback)
        self.vmtkRenderer.AddKeyBinding('d', 'Display ', self.DisplayCallback)
        self.vmtkRenderer.AddKeyBinding(
            'w', 'Switch beetween examien and interact mode ',
            self.ExmienModeCallback)
        self.vmtkRenderer.AddKeyBinding('space', 'Pick sphere',
                                        self.PickCallback)

        self.SurfaceMapper = vtk.vtkPolyDataMapper()
        self.SurfaceMapper.SetInputData(self.Surface)
        self.SurfaceMapper.SetScalarVisibility(self.DisplayArray)
        surfaceActor = vtk.vtkActor()
        surfaceActor.SetMapper(self.SurfaceMapper)
        surfaceActor.GetProperty().SetOpacity(self.Opacity)
        self.vmtkRenderer.Renderer.AddActor(surfaceActor)

        self.ScalarBarActor = vtk.vtkScalarBarActor()
        self.ScalarBarActor.SetLookupTable(self.SurfaceMapper.GetLookupTable())
        self.ScalarBarActor.GetLabelTextProperty().ItalicOff()
        self.ScalarBarActor.GetLabelTextProperty().BoldOff()
        self.ScalarBarActor.GetLabelTextProperty().ShadowOff()
        self.ScalarBarActor.SetLabelFormat('%.2f')
        self.ScalarBarActor.SetTitle('distances')
        self.ScalarBarActor.VisibilityOff()
        self.vmtkRenderer.Renderer.AddActor(self.ScalarBarActor)

        self.SphereWidget = vtk.vtkSphereWidget()
        self.SphereWidget.TranslationOff()
        self.SphereWidget.SetInteractor(
            self.vmtkRenderer.RenderWindowInteractor)
        self.SphereWidget.AddObserver("InteractionEvent", self.SphereCallback)

        self.ExamineText = vtk.vtkTextActor()
        self.ExamineText.SetInput("Examine Mode")
        self.ExamineText.GetPositionCoordinate(
        ).SetCoordinateSystemToNormalizedViewport()
        self.ExamineText.SetPosition(0.05, 0.95)
        self.ExamineText.VisibilityOff()
        self.vmtkRenderer.Renderer.AddActor2D(self.ExamineText)

        self.InputInfo(
            'Please position the mouse and press space to add spheres, \'u\' to undo\n'
        )

        any = 0
        while any == 0:
            self.InitializeSpheres()
            self.vmtkRenderer.Render()
            any = (self.Spheres.GetNumberOfPoints() > 1)

        self.Surface = self.ComputeArray()

        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
Esempio n. 20
0
    def Execute(self):

        if (self._Surface == None):
            self.PrintError(
                'vmtkOpenProfilesSeedSelector Error: Surface not set.')
            return

        if (self._SeedIds == None):
            self.PrintError(
                'vmtkOpenProfilesSeedSelector Error: SeedIds not set.')
            return

        self._SourceSeedIds.Initialize()
        self._TargetSeedIds.Initialize()

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

        self.vmtkRenderer.RegisterScript(self.Script)

        seedPoints = vtk.vtkPoints()
        for i in range(self._SeedIds.GetNumberOfIds()):
            seedPoints.InsertNextPoint(
                self._Surface.GetPoint(self._SeedIds.GetId(i)))
        seedPolyData = vtk.vtkPolyData()
        seedPolyData.SetPoints(seedPoints)
        labelsMapper = vtk.vtkLabeledDataMapper()
        labelsMapper.SetInputData(seedPolyData)
        labelsMapper.SetLabelModeToLabelIds()
        labelsActor = vtk.vtkActor2D()
        labelsActor.SetMapper(labelsMapper)

        self.vmtkRenderer.Renderer.AddActor(labelsActor)

        surfaceMapper = vtk.vtkPolyDataMapper()
        surfaceMapper.SetInputData(self._Surface)
        surfaceMapper.ScalarVisibilityOff()
        surfaceActor = vtk.vtkActor()
        surfaceActor.SetMapper(surfaceMapper)
        surfaceActor.GetProperty().SetOpacity(0.25)

        self.vmtkRenderer.Renderer.AddActor(surfaceActor)

        self.vmtkRenderer.Render()

        seedIdString = self.InputText(
            "Please input list of inlet profile ids: ")
        separator = ' '
        if seedIdString.find(',') != -1:
            separator = ','
        seedIdList = seedIdString.split(separator)
        for seedIdString in seedIdList:
            self._SourceSeedIds.InsertNextId(int(seedIdString.strip()))

        seedIdString = self.InputText(
            "Please input list of outlet profile ids (leave empty for all available profiles): "
        )
        if seedIdString.strip() == '':
            self.InputInfo("Selected outlets: ")
            for i in range(seedPoints.GetNumberOfPoints()):
                if self._SourceSeedIds.IsId(i) == -1:
                    self._TargetSeedIds.InsertNextId(i)
                    self.InputInfo("%d " % i)
            self.InputInfo("\n")
        else:
            seedIdList = seedIdString.split(separator)
            for seedIdString in seedIdList:
                self._TargetSeedIds.InsertNextId(int(seedIdString.strip()))

        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
Esempio n. 21
0
    def Execute(self):
            
        if (self.InputTraces == None):
            self.PrintError('Error: no Traces.')
        
        if (self.TimeStep == None):
            self.PrintError('Error: no TimeStep.')
        
        if not self.vmtkRenderer:
            self.vmtkRenderer = vmtkrenderer.vmtkRenderer()
            self.vmtkRenderer.Initialize()
            self.OwnRenderer = 1
        
        surfaceViewer = vmtksurfaceviewer.vmtkSurfaceViewer()
        surfaceViewer.vmtkRenderer = self.vmtkRenderer
        surfaceViewer.Surface = self.InputTraces
        surfaceViewer.ArrayName = self.ArrayName
        surfaceViewer.ColorMap = self.ColorMap
        surfaceViewer.NumberOfColors = self.NumberOfColors
        surfaceViewer.Execute()
        
        if self.ColorMap == 'grayscale':
            lut = surfaceViewer.Actor.GetMapper().GetLookupTable()
            lut.SetNumberOfTableValues(self.NumberOfColors)
            lut.SetValueRange(0.0,1.0)
            lut.SetSaturationRange(0.0,0.0)
            lut.Build()
            surfaceViewer.Actor.GetMapper().SetLookupTable(lut)
            
        if self.ColorMap == 'rainbow':
            lut = surfaceViewer.Actor.GetMapper().GetLookupTable()
            lut.SetHueRange(0.666667,0.0)
            lut.SetSaturationRange(0.75,0.75)
            lut.SetValueRange(1.0,1.0)
            lut.SetAlphaRange(1.0,1.0)
            lut.SetNumberOfColors(self.NumberOfColors)
            lut.Build()
            surfaceViewer.Actor.GetMapper().SetLookupTable(lut)  
         
        if self.ColorMap == 'blackbody': 
           lut = surfaceViewer.Actor.GetMapper().GetLookupTable()
           lut.SetNumberOfTableValues(self.NumberOfColors)
           colorTransferFunction = vtk.vtkColorTransferFunction()
           colorTransferFunction.SetColorSpaceToRGB()
           colorTransferFunction.AddRGBPoint(0,0.0,0.0,0.0)
           colorTransferFunction.AddRGBPoint(0.4,0.901961,0.0,0.0)
           colorTransferFunction.AddRGBPoint(0.8,0.901961,0.901961,0.0)
           colorTransferFunction.AddRGBPoint(1.0,1.0,1.0,1.0)
           for ii,ss in enumerate([float(xx)/float(self.NumberOfColors) for xx in range(self.NumberOfColors)]):
               cc = colorTransferFunction.GetColor(ss)
               lut.SetTableValue(ii,cc[0],cc[1],cc[2],1.0)
           lut.Build()
           surfaceViewer.Actor.GetMapper().SetLookupTable(lut)

        if self.ColorMap == 'cooltowarm':
           lut = surfaceViewer.Actor.GetMapper().GetLookupTable()
           lut.SetNumberOfTableValues(self.NumberOfColors)
           colorTransferFunction = vtk.vtkColorTransferFunction()
           colorTransferFunction.SetColorSpaceToDiverging()
           colorTransferFunction.AddRGBPoint(0,0.231373,0.298039,0.752941)
           colorTransferFunction.AddRGBPoint(0.5,0.865003,0.865003,0.865003)
           colorTransferFunction.AddRGBPoint(1.0,0.705882,0.0156863,0.14902)
           for ii,ss in enumerate([float(xx)/float(self.NumberOfColors) for xx in range(self.NumberOfColors)]):
               cc = colorTransferFunction.GetColor(ss)
               lut.SetTableValue(ii,cc[0],cc[1],cc[2],1.0)
           lut.Build()
           surfaceViewer.Actor.GetMapper().SetLookupTable(lut)
        
        if (self.Legend == 1):
            self.ScalarBarActor = vtk.vtkScalarBarActor()
            self.ScalarBarActor.SetLookupTable(surfaceViewer.Actor.GetMapper().GetLookupTable())
            self.ScalarBarActor.GetLabelTextProperty().ItalicOff()
            self.ScalarBarActor.GetLabelTextProperty().BoldOff()
            self.ScalarBarActor.GetLabelTextProperty().ShadowOff()
            self.ScalarBarActor.SetWidth(0.1)
            self.ScalarBarActor.SetHeight(0.6)
            self.ScalarBarActor.SetNumberOfLabels(4)
            self.ScalarBarActor.SetTitle(self.ArrayName+" ["+self.ArrayUnit+"]")
            self.ScalarBarActor.SetLabelFormat('%.2f')
            self.vmtkRenderer.Renderer.AddActor(self.ScalarBarActor)
       
        self.Traces = vtk.vtkPolyData()
        self.Traces.DeepCopy(self.InputTraces) 
        self.Traces.GetPointData().SetActiveScalars("IntegrationTime")
        timeRange = self.Traces.GetPointData().GetScalars().GetRange(0)
        currentCycle = 0
        minTime = self.MinTime
        currentTime = self.TimeStep 
        maxTime = self.MaxTime
        if (self.ArrayMax == None and self.ArrayName == "Velocity"):
            self.ArrayMax = round(self.Traces.GetPointData().GetArray('Speed').GetRange()[1],0)
        
        if self.Method is 'particles':
            particleTime = minTime
            imageNumber = 0
            while particleTime <= maxTime:
                contour = vtk.vtkContourFilter()
                contour.SetInputData(self.Traces)
                i = 0
                while i <= currentCycle:
                    time = minTime + currentTime + (maxTime - minTime) * i
                    if time < timeRange[0] or time > timeRange[1]:
                        pass
                    else:
                        contour.SetValue(i,time)
                    i+=1
                
                contour.Update()
                surfaceViewer.vmtkRenderer = self.vmtkRenderer
                surfaceViewer.Actor.GetProperty().SetPointSize(self.PointSize)
                vtk.vtkPolyDataMapper.SafeDownCast(surfaceViewer.Actor.GetMapper()).SetInputConnection(contour.GetOutputPort())
                
                surfaceViewer.Actor.GetMapper().GetLookupTable().SetVectorModeToMagnitude() 
                surfaceViewer.Actor.GetMapper().SetScalarModeToUsePointFieldData() 
                surfaceViewer.Actor.GetMapper().SelectColorArray(self.ArrayName) 
                surfaceViewer.Actor.GetMapper().SetScalarRange([0.0,self.ArrayMax]) 
                        
                surfaceViewer.vmtkRenderer.RenderWindow.Render()
                if self.WithScreenshots:
                    self.Screenshot(surfaceViewer,imageNumber)
                
                particleTime+=self.TimeStep
                currentTime+=self.TimeStep
                imageNumber+=1

        elif self.Method is 'streaklines':
            particleTime = minTime
            imageNumber = 0
            while particleTime <= maxTime:
                clip1 = vtk.vtkClipPolyData()
                clip1.SetInputData(self.Traces)
                clip1.GenerateClipScalarsOff()
                clip1.InsideOutOn()
                clip2 = vtk.vtkClipPolyData()
                clip2.SetInputConnection(clip1.GetOutputPort())
                clip2.GenerateClipScalarsOff()
                clip2.InsideOutOff()

                cyclesPerRange = (int((timeRange[1]-timeRange[0])/(maxTime-minTime))) + 1
                cycle = currentCycle % cyclesPerRange
                time = minTime + currentTime + (maxTime - minTime) * cycle
                streakLineTimeLength = self.StreakLineTimeLength

                clip1.SetValue(time)
                clip2.SetValue(time - streakLineTimeLength)
                clip2.Update()
            
                surfaceViewer.Actor.GetProperty().SetLineWidth(self.LineWidth)
                vtk.vtkPolyDataMapper.SafeDownCast(surfaceViewer.Actor.GetMapper()).SetInputConnection(clip2.GetOutputPort())
                
                surfaceViewer.Actor.GetMapper().GetLookupTable().SetVectorModeToMagnitude() 
                surfaceViewer.Actor.GetMapper().SetScalarModeToUsePointFieldData() 
                surfaceViewer.Actor.GetMapper().SelectColorArray(self.ArrayName) 
                surfaceViewer.Actor.GetMapper().SetScalarRange([0.0,self.ArrayMax]) 
                
                surfaceViewer.vmtkRenderer = self.vmtkRenderer
                surfaceViewer.vmtkRenderer.RenderWindow.Render()
                if self.WithScreenshots:
                    self.Screenshot(surfaceViewer,imageNumber)
                
                particleTime+=self.TimeStep
                currentTime+=self.TimeStep
                imageNumber+=1
        else:
            self.PrintError('Error: pathlineanimator  method not supported.')
Esempio n. 22
0
    def Execute(self):

        if self.Surface == None:
            self.PrintError('Error: No input surface.')

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

        self.vmtkRenderer.RegisterScript(self)
          
        glyphs = vtk.vtkGlyph3D()
        glyphSource = vtk.vtkSphereSource()
        glyphSource.SetRadius(1)
        glyphs.SetInputData(self.Spheres)
        glyphs.SetSourceConnection(glyphSource.GetOutputPort())
        glyphs.SetScaleModeToScaleByScalar()
        glyphs.SetScaleFactor(1.)
        glyphMapper = vtk.vtkPolyDataMapper()
        glyphMapper.SetInputConnection(glyphs.GetOutputPort())
        glyphMapper.ScalarVisibilityOff()
        self.SpheresActor = vtk.vtkActor()
        self.SpheresActor.SetMapper(glyphMapper)
        self.SpheresActor.GetProperty().SetColor(1.0,0.0,0.0)
        self.SpheresActor.GetProperty().SetOpacity(self.Opacity)
        self.SpheresActor.PickableOff()
        self.vmtkRenderer.Renderer.AddActor(self.SpheresActor)
        
        examineGlyphs = vtk.vtkGlyph3D()
        examineGlyphSource = vtk.vtkSphereSource()
        examineGlyphSource.SetRadius(1)
        examineGlyphs.SetInputData(self.ExamineSpheres)
        examineGlyphs.SetSourceConnection(examineGlyphSource.GetOutputPort())
        examineGlyphs.SetScaleModeToScaleByScalar()
        examineGlyphs.SetScaleFactor(1.)
        examineGlyphMapper = vtk.vtkPolyDataMapper()
        examineGlyphMapper.SetInputConnection(examineGlyphs.GetOutputPort())
        examineGlyphMapper.ScalarVisibilityOff()
        self.ExamineSpheresActor = vtk.vtkActor()
        self.ExamineSpheresActor.SetMapper(examineGlyphMapper)
        self.ExamineSpheresActor.GetProperty().SetColor(0.0,1.0,0.0)
        self.ExamineSpheresActor.GetProperty().SetOpacity(self.Opacity)
        self.ExamineSpheresActor.PickableOff()
        self.ExamineSpheresActor.VisibilityOff()
        self.vmtkRenderer.Renderer.AddActor(self.ExamineSpheresActor)


        self.vmtkRenderer.AddKeyBinding('u','Undo.',self.UndoCallback)
        self.vmtkRenderer.AddKeyBinding('space','Place picks.',self.PickCallback)
        self.vmtkRenderer.AddKeyBinding('+','Increase sphere radius.',self.IncreaseSphereRadiusCallback)
        self.vmtkRenderer.AddKeyBinding('-','Decrease sphere radius.',self.DecreaseSphereRadiusCallback)
        self.vmtkRenderer.AddKeyBinding('n','Skip to next sphere.',self.NextCallback)
        self.vmtkRenderer.AddKeyBinding('v','Skip to previous sphere.',self.PreviousCallback)
        self.vmtkRenderer.AddKeyBinding('d','Show distances graph.',self.DistancesCallback)
        self.vmtkRenderer.AddKeyBinding('x','Examine mode.',self.ExamineCallback)
        #self.vmtkRenderer.RenderWindowInteractor.AddObserver("KeyPressEvent", self.KeyPressed)
        
        self.SurfaceMapper = vtk.vtkPolyDataMapper()
        self.SurfaceMapper.SetInputData(self.Surface)
        self.SurfaceMapper.SetScalarVisibility(self.DisplayArray)
        surfaceActor = vtk.vtkActor()
        surfaceActor.SetMapper(self.SurfaceMapper)
        surfaceActor.GetProperty().SetOpacity(self.Opacity)
        self.vmtkRenderer.Renderer.AddActor(surfaceActor)
        
        self.ScalarBarActor = vtk.vtkScalarBarActor()
        self.ScalarBarActor.SetLookupTable(self.SurfaceMapper.GetLookupTable())
        self.ScalarBarActor.GetLabelTextProperty().ItalicOff()
        self.ScalarBarActor.GetLabelTextProperty().BoldOff()
        self.ScalarBarActor.GetLabelTextProperty().ShadowOff()
        self.ScalarBarActor.SetLabelFormat('%.2f')
        self.ScalarBarActor.SetTitle('distances')
        self.ScalarBarActor.VisibilityOff()
        self.vmtkRenderer.Renderer.AddActor(self.ScalarBarActor)
        
        
        self.SphereWidget = vtk.vtkSphereWidget()
        self.SphereWidget.SetInteractor(self.vmtkRenderer.RenderWindowInteractor)
        self.SphereWidget.AddObserver("InteractionEvent", self.SphereCallback)
        
        self.ExamineText = vtk.vtkTextActor()
        self.ExamineText.SetInput("Examine Mode")
        self.ExamineText.GetPositionCoordinate().SetCoordinateSystemToNormalizedViewport()
        self.ExamineText.SetPosition(0.05,0.95)
        self.ExamineText.VisibilityOff()
        self.vmtkRenderer.Renderer.AddActor2D(self.ExamineText)
        
        self.InputInfo('Please position the mouse and press space to add spheres, \'u\' to undo\n')
        
        
        any = 0
        while any == 0:
            self.InitializeSpheres()
            self.vmtkRenderer.Render()
            any = (self.Spheres.GetNumberOfPoints()>1)
            self.InputInfo('Please position the mouse and press space to add spheres, \'u\' to undo\nInsert at least 2 spheres.')
        
        self.Surface = self.ComputeArray()

        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
Esempio n. 23
0
    def BuildViewWithTag(self):

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

        self.vmtkRenderer.RegisterScript(self) 

        if self.Actor:
            self.vmtkRenderer.Renderer.RemoveActor(self.Actor)

        if self.ScalarBarActor:
            self.vmtkRenderer.Renderer.RemoveActor(self.ScalarBarActor)


        if self.Surface.GetPointData().GetArray(self.RegionTagArrayName) == None and self.Surface.GetCellData().GetArray(self.RegionTagArrayName) == None:
            self.PrintError('Error: no regiontagarray with name specified')

        elif self.Surface.GetPointData().GetArray(self.RegionTagArrayName) != None:

            regionTagArray = self.Surface.GetPointData().GetArray(self.RegionTagArrayName)
            for j in range (self.Surface.GetNumberOfPoints()):
                if regionTagArray.GetTuple1(j) not in self.TagSet:
                    self.TagSet.append(regionTagArray.GetTuple1(j))
            self.TagSet.sort()
            self.NumberOfRegions = len(self.TagSet)

            tagSetCopy = list(self.TagSet)
            labelPoints = vtk.vtkPoints()
            labelPoints.SetNumberOfPoints(len(self.TagSet))
            point = [0.0,0.0,0.0]
            for j in range (self.Surface.GetNumberOfPoints()):
                item = regionTagArray.GetTuple1(j)
                if item in tagSetCopy:
                    self.Surface.GetPoint(j, point)
                    labelPoints.SetPoint(self.TagSet.index(item), point)
                    tagSetCopy.remove(item)

            self.Surface.GetPointData().SetActiveScalars(self.RegionTagArrayName)

        elif self.Surface.GetCellData().GetArray(self.RegionTagArrayName) != None:

            regionTagArray = self.Surface.GetCellData().GetArray(self.RegionTagArrayName)
            for j in range (self.Surface.GetNumberOfCells()):
                if regionTagArray.GetTuple1(j) not in self.TagSet:
                    self.TagSet.append(regionTagArray.GetTuple1(j))
            self.TagSet.sort()
            self.NumberOfRegions = len(self.TagSet)

            tagSetCopy = list(self.TagSet)
            labelPoints = vtk.vtkPoints()
            labelPoints.SetNumberOfPoints(len(self.TagSet))
            point = [0.0,0.0,0.0]
            
            cellCenters = vtk.vtkCellCenters()
            cellCenters.SetInputData(self.Surface)
            cellCenters.Update()
            
            regionTagArrayCenters = cellCenters.GetOutput().GetPointData().GetArray(self.RegionTagArrayName)
            
            for j in range (cellCenters.GetOutput().GetNumberOfPoints()):
                item = regionTagArrayCenters.GetTuple1(j)
                if item in tagSetCopy:
                    cellCenters.GetOutput().GetPoint(j, point)
                    labelPoints.SetPoint(self.TagSet.index(item), point)
                    tagSetCopy.remove(item)

            self.Surface.GetCellData().SetActiveScalars(self.RegionTagArrayName)

        labelPolyData = vtk.vtkPolyData()
        labelPolyData.SetPoints(labelPoints)

        labelArray = vtk.vtkIntArray()
        labelArray.SetNumberOfComponents(1)
        labelArray.SetNumberOfTuples(self.NumberOfRegions)
        labelArray.SetName('label')
        labelArray.FillComponent(0,0)

        labelPolyData.GetPointData().AddArray(labelArray)

        for item in self.TagSet:
            labelArray.SetTuple1(self.TagSet.index(item), item)

        labelPolyData.GetPointData().SetActiveScalars('label')
        labelsMapper = vtk.vtkLabeledDataMapper()
        labelsMapper.SetInputData(labelPolyData)
        labelsMapper.SetLabelModeToLabelScalars()
        labelsMapper.GetLabelTextProperty().SetColor(1, 1, 1)
        labelsMapper.GetLabelTextProperty().SetFontSize(14)
        self.labelsActor = vtk.vtkActor2D()
        self.labelsActor.SetMapper(labelsMapper)
        self.vmtkRenderer.Renderer.AddActor(self.labelsActor)

        surfaceMapper = vtk.vtkPolyDataMapper()
        surfaceMapper.SetInputData(self.Surface)
        surfaceMapper.ScalarVisibilityOn()
        surfaceMapper.SetScalarRange(self.TagSet[0], self.TagSet[self.NumberOfRegions-1])
        self.Actor = vtk.vtkActor()
        self.Actor.SetMapper(surfaceMapper)
        self.Actor.GetProperty().SetOpacity(self.Opacity)
        self.Actor.GetProperty().SetLineWidth(self.LineWidth)
        if self.FlatInterpolation:
            self.Actor.GetProperty().SetInterpolationToFlat()
        self.SetSurfaceRepresentation(self.Representation)
        self.vmtkRenderer.Renderer.AddActor(self.Actor)
        self.vmtkRenderer.AddKeyBinding('w','Change surface representation.',self.RepresentationCallback)

        if self.Legend and self.Actor:
            self.ScalarBarActor = vtk.vtkScalarBarActor()
            self.ScalarBarActor.SetLookupTable(self.Actor.GetMapper().GetLookupTable())
            self.ScalarBarActor.GetLabelTextProperty().ItalicOff()
            self.ScalarBarActor.GetLabelTextProperty().BoldOff()
            self.ScalarBarActor.GetLabelTextProperty().ShadowOff()
##             self.ScalarBarActor.GetLabelTextProperty().SetColor(0.0,0.0,0.0)
            self.ScalarBarActor.SetLabelFormat('%.2f')
            self.ScalarBarActor.SetTitle(self.LegendTitle)
            self.vmtkRenderer.Renderer.AddActor(self.ScalarBarActor)

        if self.Display:
            self.vmtkRenderer.Render()
##            self.vmtkRenderer.Renderer.RemoveActor(self.Actor)
##            self.vmtkRenderer.Renderer.RemoveActor(self.ScalarBarActor)

        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
Esempio n. 24
0
    def BuildView(self):

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

        self.vmtkRenderer.RegisterScript(self) 

        if self.Actor:
            self.vmtkRenderer.Renderer.RemoveActor(self.Actor)

        if self.ScalarBarActor:
            self.vmtkRenderer.Renderer.RemoveActor(self.ScalarBarActor)

        if self.Mesh:
            mapper = vtk.vtkDataSetMapper()
            mapper.SetInputData(self.Mesh)
            if self.ArrayName:
                self.Mesh.GetPointData().SetActiveScalars(self.ArrayName)
                array = self.Mesh.GetPointData().GetScalars()
                
                if self.ScalarRange[1] > self.ScalarRange[0]:
                    mapper.SetScalarRange(self.ScalarRange)
                else:
                    mapper.SetScalarRange(array.GetRange(0))
                
                if self.ColorMap == 'grayscale':
                    lut = mapper.GetLookupTable()
                    lut.SetNumberOfTableValues(self.NumberOfColors)
                    lut.SetValueRange(0.0,1.0)
                    lut.SetSaturationRange(0.0,0.0)
                    lut.Build()
                    mapper.SetLookupTable(lut)
                
                if self.ColorMap == 'rainbow':
                    lut = mapper.GetLookupTable()
                    lut.SetHueRange(0.666667,0.0)
                    lut.SetSaturationRange(0.75,0.75)
                    lut.SetValueRange(1.0,1.0)
                    lut.SetAlphaRange(1.0,1.0)
                    lut.SetNumberOfColors(self.NumberOfColors)
                    lut.Build()
                    mapper.SetLookupTable(lut)  
                     
                if self.ColorMap == 'blackbody': 
                   lut = mapper.GetLookupTable()
                   lut.SetNumberOfTableValues(self.NumberOfColors)
                   colorTransferFunction = vtk.vtkColorTransferFunction()
                   colorTransferFunction.SetColorSpaceToRGB()
                   colorTransferFunction.AddRGBPoint(0,0.0,0.0,0.0)
                   colorTransferFunction.AddRGBPoint(0.4,0.901961,0.0,0.0)
                   colorTransferFunction.AddRGBPoint(0.8,0.901961,0.901961,0.0)
                   colorTransferFunction.AddRGBPoint(1.0,1.0,1.0,1.0)
                   for ii,ss in enumerate([float(xx)/float(self.NumberOfColors) for xx in range(self.NumberOfColors)]):
                       cc = colorTransferFunction.GetColor(ss)
                       lut.SetTableValue(ii,cc[0],cc[1],cc[2],1.0)
                   lut.Build()
                   mapper.SetLookupTable(lut)
           
                if self.ColorMap == 'cooltowarm':
                   lut = mapper.GetLookupTable()
                   lut.SetNumberOfTableValues(self.NumberOfColors)
                   colorTransferFunction = vtk.vtkColorTransferFunction()
                   colorTransferFunction.SetColorSpaceToDiverging()
                   colorTransferFunction.AddRGBPoint(0,0.231373,0.298039,0.752941)
                   colorTransferFunction.AddRGBPoint(0.5,0.865003,0.865003,0.865003)
                   colorTransferFunction.AddRGBPoint(1.0,0.705882,0.0156863,0.14902)
                   for ii,ss in enumerate([float(xx)/float(self.NumberOfColors) for xx in range(self.NumberOfColors)]):
                       cc = colorTransferFunction.GetColor(ss)
                       lut.SetTableValue(ii,cc[0],cc[1],cc[2],1.0)
                   lut.Build()
                   mapper.SetLookupTable(lut)
            else:
                mapper.ScalarVisibilityOff()
            self.Actor = vtk.vtkActor()
            self.Actor.SetMapper(mapper)
            if (self.Color[0] >= 0.0):
                self.Actor.GetProperty().SetColor(self.Color)
            if self.FlatInterpolation:
                self.Actor.GetProperty().SetInterpolationToFlat()
            self.Actor.GetProperty().SetOpacity(self.Opacity)
            self.vmtkRenderer.Renderer.AddActor(self.Actor)
            self.vmtkRenderer.AddKeyBinding('w','Change surface representation.',self.RepresentationCallback)

        if self.Legend and self.Actor:
            self.ScalarBarActor = vtk.vtkScalarBarActor()
            self.ScalarBarActor.SetLookupTable(self.Actor.GetMapper().GetLookupTable())
            self.ScalarBarActor.GetLabelTextProperty().ItalicOff()
            self.ScalarBarActor.GetLabelTextProperty().BoldOff()
            self.ScalarBarActor.GetLabelTextProperty().ShadowOff()
##             self.ScalarBarActor.GetLabelTextProperty().SetColor(0.0,0.0,0.0)
            self.ScalarBarActor.SetLabelFormat('%.2f')
            self.vmtkRenderer.Renderer.AddActor(self.ScalarBarActor)

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

        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
Esempio n. 25
0
    def Execute(self):

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

        if (self.CenterlineNormals) and (self.Centerlines == None):
            self.PrintError('Error: No input centerlines.')

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

        self.SeedSelector = vmtkPickPointSeedSelector()
        self.SeedSelector.vmtkRenderer = self.vmtkRenderer
        self.SeedSelector.Script = self

        if (self.CenterlineNormals):
            self.SeedSelector.SetOutlets = 1
        self.SeedSelector.SetSurface(self.Surface)
        self.SeedSelector.InputInfo = self.InputInfo
        self.SeedSelector.InputText = self.InputText
        self.SeedSelector.OutputText = self.OutputText
        self.SeedSelector.PrintError = self.PrintError
        self.SeedSelector.PrintLog = self.PrintLog
        self.SeedSelector.Execute()

        mainBodySeedIds = self.SeedSelector.GetMainBodySeedIds()
        mainBodySeedId = mainBodySeedIds.GetId(0)
        mainBodyPoint = self.Surface.GetPoint(mainBodySeedId)

        clipSeedIds = self.SeedSelector.GetSourceSeedIds()

        surfaceCleaner = vtk.vtkCleanPolyData()
        surfaceCleaner.SetInputData(self.Surface)
        surfaceCleaner.Update()

        surfaceTriangulator = vtk.vtkTriangleFilter()
        surfaceTriangulator.SetInputConnection(surfaceCleaner.GetOutputPort())
        surfaceTriangulator.PassLinesOff()
        surfaceTriangulator.PassVertsOff()
        surfaceTriangulator.Update()

        clippedSurface = surfaceTriangulator.GetOutput()

        n_seeds = clipSeedIds.GetNumberOfIds()  # get the number of inlets
        if (self.CenterlineNormals):
            targetSeedIds = self.SeedSelector.GetTargetSeedIds()
            for i in range(targetSeedIds.GetNumberOfIds()):
                clipSeedIds.InsertNextId(targetSeedIds.GetId(i))
            locator_ctr = vtk.vtkPointLocator()
            locator_ctr.SetDataSet(self.Centerlines)
            locator_ctr.BuildLocator()

        for i in range(clipSeedIds.GetNumberOfIds()):

            seedId = clipSeedIds.GetId(i)
            seedPoint = self.Surface.GetPoint(seedId)

            # the frenet tangent must be inverted as it is directed outwards
            # the seam filter requires an inward facing normal
            if (self.CenterlineNormals):
                centerlinePointId = locator_ctr.FindClosestPoint(seedPoint)
                origin = self.Centerlines.GetPoint(centerlinePointId)
                normal = self.Centerlines.GetPointData().GetArray(
                    self.FrenetTangentArrayName).GetTuple(centerlinePointId)
                if (i >= n_seeds):
                    # invert outward facing normals
                    normal = tuple(-p for p in normal)
            else:
                locator = vtk.vtkPointLocator()
                locator.SetDataSet(clippedSurface)
                locator.BuildLocator()
                seedPointId = locator.FindClosestPoint(seedPoint)

                planeEstimator = vtkvmtk.vtkvmtkPolyDataNormalPlaneEstimator()
                planeEstimator.SetInputData(clippedSurface)
                planeEstimator.SetOriginPointId(seedPointId)
                planeEstimator.Update()
                origin = planeEstimator.GetOrigin()
                normal = planeEstimator.GetNormal()

            plane = vtk.vtkPlane()
            plane.SetOrigin(origin)
            plane.SetNormal(normal)

            seamFilter = vtkvmtk.vtkvmtkTopologicalSeamFilter()
            seamFilter.SetInputData(clippedSurface)
            seamFilter.SetClosestPoint(seedPoint)
            seamFilter.SetSeamScalarsArrayName("SeamScalars")
            seamFilter.SetSeamFunction(plane)

            clipper = vtk.vtkClipPolyData()
            clipper.SetInputConnection(seamFilter.GetOutputPort())
            clipper.GenerateClipScalarsOff()
            clipper.GenerateClippedOutputOn()

            connectivity = vtk.vtkPolyDataConnectivityFilter()
            connectivity.SetInputConnection(clipper.GetOutputPort())
            connectivity.SetExtractionModeToClosestPointRegion()
            connectivity.SetClosestPoint(mainBodyPoint)

            surfaceCleaner = vtk.vtkCleanPolyData()
            surfaceCleaner.SetInputConnection(connectivity.GetOutputPort())
            surfaceCleaner.Update()

            surfaceTriangulator = vtk.vtkTriangleFilter()
            surfaceTriangulator.SetInputConnection(
                surfaceCleaner.GetOutputPort())
            surfaceTriangulator.PassLinesOff()
            surfaceTriangulator.PassVertsOff()
            surfaceTriangulator.Update()

            #clippedSurface = vtk.vtkPolyData()
            #clippedSurface.DeepCopy(surfaceTriangulator.GetOutput())
            clippedSurface = surfaceTriangulator.GetOutput()

        self.Surface = clippedSurface

        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
Esempio n. 26
0
    def BuildView(self):

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

        self.vmtkRenderer.RegisterScript(self)

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

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

        scalarRange = [0.0, 0.0]

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

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

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

        opacityFunction = vtk.vtkPiecewiseFunction()
        imageRange = self.Image.GetScalarRange()

        if self.Opacity is not None:
            opacityFunction.AddPoint(imageRange[0], 0)
            opacityFunction.AddPoint(scalarRange[0], self.Opacity[0])
            opacityFunction.AddPoint(scalarRange[0], self.Opacity[1])
            opacityFunction.AddPoint(imageRange[1], 1)

        volumeProperty = vtk.vtkVolumeProperty()
        volumeProperty.ShadeOn()
        volumeProperty.SetInterpolationTypeToLinear()
        volumeProperty.SetColor(colorTransferFunction)
        if self.Opacity is not None:
            volumeProperty.SetScalarOpacity(opacityFunction)

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

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

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

        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
Esempio n. 27
0
    def Execute(self):

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

        self.Clipper = vtk.vtkClipPolyData()
        self.Clipper.SetInputData(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.SetInputData(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.SetInputData(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)
            # Try AutoClip here
            if not self.ClipsIn == None:
                self.AutoClip()

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

            self.Transform = vtk.vtkTransform()
            if self.WidgetType == "box":
                self.ClipWidget.GetTransform(self.Transform)

            # Add items from ClipCollection to MultiBlockDataSet
            self.ClipsOut = vtk.vtkMultiBlockDataSet()
            ClipTotal = self.ClipCollection.GetNumberOfItems() 
            BlockNum = 0
            self.ClipCollection.InitTraversal()
            while BlockNum < ClipTotal:
                blockin = vtk.vtkPolyData()
                blockin.DeepCopy(self.ClipCollection.GetNextItem())
                self.PrintLog('The bounds of blockin are: ' + str(blockin.GetBounds()))
                self.ClipsOut.SetBlock(BlockNum, blockin)
                BlockNum += 1
                

            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.SetInputData(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.SetInputData(self.Surface)
            cleaner.Update()
            self.Surface = cleaner.GetOutput()

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

            cleaner = vtk.vtkCleanPolyData()
            cleaner.SetInputData(self.CutLines)
            cleaner.Update()
            stripper = vtk.vtkStripper()
            stripper.SetInputConnection(cleaner.GetOutputPort())
            stripper.Update()
            self.CutLines = stripper.GetOutput()
Esempio n. 28
0
    def Execute(self):

        if self.Surface == None:
            self.PrintError('Error: No input surface.')

        if self.ExtensionMode == "centerlinedirection" and self.Centerlines == None:
            self.PrintError('Error: No input centerlines.')

        boundaryIds = vtk.vtkIdList()

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

            self.vmtkRenderer.RegisterScript(self)  

            boundaryExtractor = vtkvmtk.vtkvmtkPolyDataBoundaryExtractor()
            boundaryExtractor.SetInputData(self.Surface)
            boundaryExtractor.Update()
            boundaries = boundaryExtractor.GetOutput()
            numberOfBoundaries = boundaries.GetNumberOfCells()
            seedPoints = vtk.vtkPoints()
            for i in range(numberOfBoundaries):
                barycenter = [0.0, 0.0, 0.0]
                vtkvmtk.vtkvmtkBoundaryReferenceSystems.ComputeBoundaryBarycenter(boundaries.GetCell(i).GetPoints(),barycenter)
                seedPoints.InsertNextPoint(barycenter)
            seedPolyData = vtk.vtkPolyData()
            seedPolyData.SetPoints(seedPoints)
            labelsMapper = vtk.vtkLabeledDataMapper();
            labelsMapper.SetInputData(seedPolyData)
            labelsMapper.SetLabelModeToLabelIds()
            labelsActor = vtk.vtkActor2D()
            labelsActor.SetMapper(labelsMapper)
    
            self.vmtkRenderer.Renderer.AddActor(labelsActor)
    
            surfaceMapper = vtk.vtkPolyDataMapper()
            surfaceMapper.SetInputData(self.Surface)
            surfaceMapper.ScalarVisibilityOff()
            surfaceActor = vtk.vtkActor()
            surfaceActor.SetMapper(surfaceMapper)
            surfaceActor.GetProperty().SetOpacity(0.25)
    
            self.vmtkRenderer.Renderer.AddActor(surfaceActor)
    
            #self.vmtkRenderer.Render()
    
            #self.vmtkRenderer.Renderer.RemoveActor(labelsActor)
            #self.vmtkRenderer.Renderer.RemoveActor(surfaceActor)
            
            ok = False
            while not ok:
                if(self.Exclude):
                    labelString = self.InputText("Please input boundary ids to exclude: ",self.LabelValidator)
                else:
                    labelString = self.InputText("Please input boundary ids: ",self.LabelValidator)
                labels = [int(label) for label in labelString.split()]
                ok = True
                for label in labels:
                    if label not in list(range(numberOfBoundaries)):
                        ok = False

            if(self.Exclude):
                for label in list(range(numberOfBoundaries)):
                    if label not in labels:
                        boundaryIds.InsertNextId(label)
            else:
                for label in labels:
                    boundaryIds.InsertNextId(label)

        flowExtensionsFilter = vtkvmtk.vtkvmtkPolyDataFlowExtensionsFilter()
        flowExtensionsFilter.SetInputData(self.Surface)
        flowExtensionsFilter.SetCenterlines(self.Centerlines)
        flowExtensionsFilter.SetSigma(self.Sigma)
        flowExtensionsFilter.SetAdaptiveExtensionLength(self.AdaptiveExtensionLength)
        flowExtensionsFilter.SetAdaptiveExtensionRadius(self.AdaptiveExtensionRadius)
        flowExtensionsFilter.SetAdaptiveNumberOfBoundaryPoints(self.AdaptiveNumberOfBoundaryPoints)
        flowExtensionsFilter.SetExtensionLength(self.ExtensionLength)
        flowExtensionsFilter.SetExtensionRatio(self.ExtensionRatio)
        flowExtensionsFilter.SetExtensionRadius(self.ExtensionRadius)
        flowExtensionsFilter.SetTransitionRatio(self.TransitionRatio)
        flowExtensionsFilter.SetCenterlineNormalEstimationDistanceRatio(self.CenterlineNormalEstimationDistanceRatio)
        flowExtensionsFilter.SetNumberOfBoundaryPoints(self.TargetNumberOfBoundaryPoints)
        if self.ExtensionMode == "centerlinedirection":
            flowExtensionsFilter.SetExtensionModeToUseCenterlineDirection()
        elif self.ExtensionMode == "boundarynormal":
            flowExtensionsFilter.SetExtensionModeToUseNormalToBoundary()
        if self.InterpolationMode == "linear":
            flowExtensionsFilter.SetInterpolationModeToLinear()
        elif self.InterpolationMode == "thinplatespline":
            flowExtensionsFilter.SetInterpolationModeToThinPlateSpline()
        if self.Interactive:
            flowExtensionsFilter.SetBoundaryIds(boundaryIds)
        flowExtensionsFilter.Update()

        self.Surface = flowExtensionsFilter.GetOutput()
Esempio n. 29
0
    def BuildView(self):

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

        self.vmtkRenderer.RegisterScript(self)

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

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

        scalarRange = [0.0, 0.0]

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

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

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

        opacityFunction = vtk.vtkPiecewiseFunction()
        imageRange = self.Image.GetScalarRange()

        if self.Opacity is not None:
            opacityFunction.AddPoint(imageRange[0], 0)
            opacityFunction.AddPoint(scalarRange[0], self.Opacity[0])
            opacityFunction.AddPoint(scalarRange[0], self.Opacity[1])
            opacityFunction.AddPoint(imageRange[1], 1)

        volumeProperty = vtk.vtkVolumeProperty()
        volumeProperty.ShadeOn()
        volumeProperty.SetInterpolationTypeToLinear()
        volumeProperty.SetColor(colorTransferFunction)
        if self.Opacity is not None:
            volumeProperty.SetScalarOpacity(opacityFunction)

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

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

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

        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
Esempio n. 30
0
    def Execute(self):

        if self.Surface == None:
            self.PrintError('Error: No input surface.')

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

        self.vmtkRenderer.RegisterScript(self) 

        glyphs = vtk.vtkGlyph3D()
        glyphSource = vtk.vtkSphereSource()
        glyphSource.SetRadius(1)
        glyphs.SetInputData(self.SeedPoints)
        glyphs.SetSourceConnection(glyphSource.GetOutputPort())
        glyphs.SetScaleModeToDataScalingOff()
        glyphs.SetScaleFactor(self.Surface.GetLength()*0.01)
        glyphMapper = vtk.vtkPolyDataMapper()
        glyphMapper.SetInputConnection(glyphs.GetOutputPort())
        glyphMapper.ScalarVisibilityOff()
        self.PointActor = vtk.vtkActor()
        self.PointActor.SetMapper(glyphMapper)
        self.PointActor.GetProperty().SetColor(1.0,0.0,0.0)
        self.PointActor.GetProperty().SetOpacity(self.Opacity)
        self.PointActor.PickableOff()
        self.vmtkRenderer.Renderer.AddActor(self.PointActor)
        
        examineGlyphs = vtk.vtkGlyph3D()
        examineGlyphSource = vtk.vtkSphereSource()
        examineGlyphSource.SetRadius(1)
        examineGlyphs.SetInputData(self.ExamineSpheres)
        examineGlyphs.SetSourceConnection(examineGlyphSource.GetOutputPort())
        examineGlyphs.SetScaleModeToScaleByScalar()
        examineGlyphs.SetScaleFactor(1.)
        examineGlyphMapper = vtk.vtkPolyDataMapper()
        examineGlyphMapper.SetInputConnection(examineGlyphs.GetOutputPort())
        examineGlyphMapper.ScalarVisibilityOff()
        self.ExamineSpheresActor = vtk.vtkActor()
        self.ExamineSpheresActor.SetMapper(examineGlyphMapper)
        self.ExamineSpheresActor.GetProperty().SetColor(0.0,1.0,0.0)
        self.ExamineSpheresActor.GetProperty().SetOpacity(self.Opacity)
        self.ExamineSpheresActor.PickableOff()
        self.ExamineSpheresActor.VisibilityOff()
        self.vmtkRenderer.Renderer.AddActor(self.ExamineSpheresActor)

        #self.vmtkRenderer.RenderWindowInteractor.AddObserver("KeyPressEvent", self.KeyPressed)
        self.vmtkRenderer.AddKeyBinding('u','Undo.',self.UndoCallback)
        self.vmtkRenderer.AddKeyBinding('space','Pick points.',self.SpaceCallback)
        self.vmtkRenderer.AddKeyBinding('w','Examine mode.',self.ExamineCallback)
        self.vmtkRenderer.AddKeyBinding('d','Display Distance.',self.DisplayDistanceCallback)
        self.vmtkRenderer.AddKeyBinding('a','Add.',self.AddCallback)
        
        self.SurfaceMapper = vtk.vtkPolyDataMapper()
        self.SurfaceMapper.SetInputData(self.Surface)
        self.SurfaceMapper.SetScalarVisibility(self.DisplayArray)
        surfaceActor = vtk.vtkActor()
        surfaceActor.SetMapper(self.SurfaceMapper)
        surfaceActor.GetProperty().SetOpacity(self.Opacity)
        self.vmtkRenderer.Renderer.AddActor(surfaceActor)
        
        self.ScalarBarActor = vtk.vtkScalarBarActor()
        self.ScalarBarActor.SetLookupTable(self.SurfaceMapper.GetLookupTable())
        self.ScalarBarActor.GetLabelTextProperty().ItalicOff()
        self.ScalarBarActor.GetLabelTextProperty().BoldOff()
        self.ScalarBarActor.GetLabelTextProperty().ShadowOff()
        self.ScalarBarActor.SetLabelFormat('%.2f')
        self.ScalarBarActor.SetTitle('distances')
        self.ScalarBarActor.VisibilityOff()
        self.vmtkRenderer.Renderer.AddActor(self.ScalarBarActor)
        
        self.ExamineText = vtk.vtkTextActor()
        self.ExamineText.SetInput("Examine Mode")
        self.ExamineText.GetPositionCoordinate().SetCoordinateSystemToNormalizedViewport()
        self.ExamineText.SetPosition(0.05,0.95)
        self.ExamineText.VisibilityOff()
        self.vmtkRenderer.Renderer.AddActor2D(self.ExamineText)
        
        self.InputInfo('Please position the mouse and press space to add points, \'u\' to undo\n')

        any = 0
        while any == 0:
            self.InitializeSeeds()
            self.vmtkRenderer.Render()
            any = self.SeedIds.GetNumberOfIds()
 
        self.Surface = self.ComputeDistances()

        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
Esempio n. 31
0
    def Execute(self):
 
        if not self.Centerlines:
            self.PrintError('Error: No input centerlines.')
            return
        
        if not self.vmtkRenderer:
            self.vmtkRenderer = vmtkrenderer.vmtkRenderer()
            self.vmtkRenderer.Initialize()
            self.OwnRenderer = 1

        self.vmtkRenderer.RegisterScript(self) 

        if self.CellDataArrayName:
            cellCenters = vtk.vtkCellCenters()
            cellCenters.SetInputData(self.Centerlines)
            cellCenters.Update()
            cellCenters.GetOutput().GetPointData().SetActiveScalars(self.CellDataArrayName)
            labelsMapper = vtk.vtkLabeledDataMapper();
            labelsMapper.SetInputConnection(cellCenters.GetOutputPort())
            labelsMapper.SetLabelModeToLabelScalars()
            labelsActor = vtk.vtkActor2D()
            labelsActor.SetMapper(labelsMapper)
            self.vmtkRenderer.Renderer.AddActor(labelsActor)

        centerlineMapper = vtk.vtkPolyDataMapper()
        centerlineMapper.SetInputData(self.Centerlines)
        if self.CellDataArrayName and not self.PointDataArrayName:
            centerlineMapper.ScalarVisibilityOn()
            centerlineMapper.SetScalarModeToUseCellData()
            self.Centerlines.GetCellData().SetActiveScalars(self.CellDataArrayName)
            centerlineMapper.SetScalarRange(self.Centerlines.GetCellData().GetScalars().GetRange(0))
        elif self.PointDataArrayName:
            centerlineMapper.ScalarVisibilityOn()
            centerlineMapper.SetScalarModeToUsePointData()
            self.Centerlines.GetPointData().SetActiveScalars(self.PointDataArrayName)
            centerlineMapper.SetScalarRange(self.Centerlines.GetPointData().GetScalars().GetRange(0))
        else:
            centerlineMapper.ScalarVisibilityOff()
        
        if self.ColorMap == 'grayscale':
            lut = centerlineMapper.GetLookupTable()
            lut.SetNumberOfTableValues(self.NumberOfColors)
            lut.SetValueRange(0.0,1.0)
            lut.SetSaturationRange(0.0,0.0)
            lut.Build()
            centerlineMapper.SetLookupTable(lut)
        
        if self.ColorMap == 'rainbow':
            lut = centerlineMapper.GetLookupTable()
            lut.SetHueRange(0.666667,0.0)
            lut.SetSaturationRange(0.75,0.75)
            lut.SetValueRange(1.0,1.0)
            lut.SetAlphaRange(1.0,1.0)
            lut.SetNumberOfColors(self.NumberOfColors)
            lut.Build()
            centerlineMapper.SetLookupTable(lut)
           
        if self.ColorMap == 'blackbody':
            lut = centerlineMapper.GetLookupTable()
            lut.SetNumberOfTableValues(self.NumberOfColors)
            colorTransferFunction = vtk.vtkColorTransferFunction()
            colorTransferFunction.SetColorSpaceToRGB()
            colorTransferFunction.AddRGBPoint(0,0.0,0.0,0.0)
            colorTransferFunction.AddRGBPoint(0.4,0.901961,0.0,0.0)
            colorTransferFunction.AddRGBPoint(0.8,0.901961,0.901961,0.0)
            colorTransferFunction.AddRGBPoint(1.0,1.0,1.0,1.0)
            for ii,ss in enumerate([float(xx)/float(self.NumberOfColors) for xx in range(self.NumberOfColors)]):
                cc = colorTransferFunction.GetColor(ss)
                lut.SetTableValue(ii,cc[0],cc[1],cc[2],1.0)
            lut.Build()
            centerlineMapper.SetLookupTable(lut)  
                   
        if self.ColorMap == 'cooltowarm':
            lut = centerlineMapper.GetLookupTable()
            lut.SetNumberOfTableValues(self.NumberOfColors)
            colorTransferFunction = vtk.vtkColorTransferFunction()
            colorTransferFunction.SetColorSpaceToDiverging()
            colorTransferFunction.AddRGBPoint(0,0.231373,0.298039,0.752941)
            colorTransferFunction.AddRGBPoint(0.5,0.865003,0.865003,0.865003)
            colorTransferFunction.AddRGBPoint(1.0,0.705882,0.0156863,0.14902)
            for ii,ss in enumerate([float(xx)/float(self.NumberOfColors) for xx in range(self.NumberOfColors)]):
                cc = colorTransferFunction.GetColor(ss)
                lut.SetTableValue(ii,cc[0],cc[1],cc[2],1.0)
            lut.Build()
            centerlineMapper.SetLookupTable(lut)
        
        centerlineActor = vtk.vtkActor()
        centerlineActor.SetMapper(centerlineMapper)
        self.vmtkRenderer.Renderer.AddActor(centerlineActor)

        scalarBarActor = None
        if self.Legend and centerlineActor and self.PointDataArrayName:
            scalarBarActor = vtk.vtkScalarBarActor()
            scalarBarActor.SetLookupTable(centerlineActor.GetMapper().GetLookupTable())
            scalarBarActor.GetLabelTextProperty().ItalicOff()
            scalarBarActor.GetLabelTextProperty().BoldOff()
            scalarBarActor.GetLabelTextProperty().ShadowOff()
            scalarBarActor.SetLabelFormat('%.2f')
            scalarBarActor.SetTitle(self.PointDataArrayName)
            self.vmtkRenderer.Renderer.AddActor(scalarBarActor)

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

        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
Esempio n. 32
0
    def Execute(self):

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

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

        self.SeedSelector = vmtkPickPointSeedSelector()
        self.SeedSelector.vmtkRenderer = self.vmtkRenderer
        self.SeedSelector.Script = self

        self.SeedSelector.SetSurface(self.Surface)
        self.SeedSelector.InputInfo = self.InputInfo
        self.SeedSelector.InputText = self.InputText
        self.SeedSelector.OutputText = self.OutputText
        self.SeedSelector.PrintError = self.PrintError
        self.SeedSelector.PrintLog = self.PrintLog
        self.SeedSelector.Execute()

        mainBodySeedIds = self.SeedSelector.GetSourceSeedIds()
        mainBodySeedId = mainBodySeedIds.GetId(0)
        mainBodyPoint = self.Surface.GetPoint(mainBodySeedId)

        clipSeedIds = self.SeedSelector.GetTargetSeedIds()

        surfaceCleaner = vtk.vtkCleanPolyData()
        surfaceCleaner.SetInputData(self.Surface)
        surfaceCleaner.Update()

        surfaceTriangulator = vtk.vtkTriangleFilter()
        surfaceTriangulator.SetInputConnection(surfaceCleaner.GetOutputPort())
        surfaceTriangulator.PassLinesOff()
        surfaceTriangulator.PassVertsOff()
        surfaceTriangulator.Update()

        clippedSurface = surfaceTriangulator.GetOutput()

        for i in range(clipSeedIds.GetNumberOfIds()):

            seedId = clipSeedIds.GetId(i)

            locator = vtk.vtkPointLocator()
            locator.SetDataSet(clippedSurface)
            locator.BuildLocator()

            seedPoint = self.Surface.GetPoint(seedId)
            seedPointId = locator.FindClosestPoint(seedPoint)

            planeEstimator = vtkvmtk.vtkvmtkPolyDataNormalPlaneEstimator()
            planeEstimator.SetInputData(clippedSurface)
            planeEstimator.SetOriginPointId(seedPointId)
            planeEstimator.Update()

            plane = vtk.vtkPlane()
            plane.SetOrigin(planeEstimator.GetOrigin())
            plane.SetNormal(planeEstimator.GetNormal())

            seamFilter = vtkvmtk.vtkvmtkTopologicalSeamFilter()
            seamFilter.SetInputData(clippedSurface)
            seamFilter.SetClosestPoint(seedPoint)
            seamFilter.SetSeamScalarsArrayName("SeamScalars")
            seamFilter.SetSeamFunction(plane)

            clipper = vtk.vtkClipPolyData()
            clipper.SetInputConnection(seamFilter.GetOutputPort())
            clipper.GenerateClipScalarsOff()
            clipper.GenerateClippedOutputOn()

            connectivity = vtk.vtkPolyDataConnectivityFilter()
            connectivity.SetInputConnection(clipper.GetOutputPort())
            connectivity.SetExtractionModeToClosestPointRegion()
            connectivity.SetClosestPoint(mainBodyPoint)

            surfaceCleaner = vtk.vtkCleanPolyData()
            surfaceCleaner.SetInputConnection(connectivity.GetOutputPort())
            surfaceCleaner.Update()

            surfaceTriangulator = vtk.vtkTriangleFilter()
            surfaceTriangulator.SetInputConnection(surfaceCleaner.GetOutputPort())
            surfaceTriangulator.PassLinesOff()
            surfaceTriangulator.PassVertsOff()
            surfaceTriangulator.Update()

            #clippedSurface = vtk.vtkPolyData()
            #clippedSurface.DeepCopy(surfaceTriangulator.GetOutput())
            clippedSurface = surfaceTriangulator.GetOutput()

        self.Surface = clippedSurface

        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
Esempio n. 33
0
    def Execute(self):

        if self.Surface == None:
            self.PrintError('Error: No input surface.')

        if self.ExtensionMode == "centerlinedirection" and self.Centerlines == None:
            self.PrintError('Error: No input centerlines.')

        boundaryIds = vtk.vtkIdList()

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

            self.vmtkRenderer.RegisterScript(self)

            boundaryExtractor = vtkvmtk.vtkvmtkPolyDataBoundaryExtractor()
            boundaryExtractor.SetInputData(self.Surface)
            boundaryExtractor.Update()
            boundaries = boundaryExtractor.GetOutput()
            numberOfBoundaries = boundaries.GetNumberOfCells()
            seedPoints = vtk.vtkPoints()
            for i in range(numberOfBoundaries):
                barycenter = [0.0, 0.0, 0.0]
                vtkvmtk.vtkvmtkBoundaryReferenceSystems.ComputeBoundaryBarycenter(
                    boundaries.GetCell(i).GetPoints(), barycenter)
                seedPoints.InsertNextPoint(barycenter)
            seedPolyData = vtk.vtkPolyData()
            seedPolyData.SetPoints(seedPoints)
            labelsMapper = vtk.vtkLabeledDataMapper()
            labelsMapper.SetInputData(seedPolyData)
            labelsMapper.SetLabelModeToLabelIds()
            labelsActor = vtk.vtkActor2D()
            labelsActor.SetMapper(labelsMapper)

            self.vmtkRenderer.Renderer.AddActor(labelsActor)

            surfaceMapper = vtk.vtkPolyDataMapper()
            surfaceMapper.SetInputData(self.Surface)
            surfaceMapper.ScalarVisibilityOff()
            surfaceActor = vtk.vtkActor()
            surfaceActor.SetMapper(surfaceMapper)
            surfaceActor.GetProperty().SetOpacity(0.25)

            self.vmtkRenderer.Renderer.AddActor(surfaceActor)

            #self.vmtkRenderer.Render()

            #self.vmtkRenderer.Renderer.RemoveActor(labelsActor)
            #self.vmtkRenderer.Renderer.RemoveActor(surfaceActor)

            ok = False
            while not ok:
                if (self.Exclude):
                    labelString = self.InputText(
                        "Please input boundary ids to exclude: ",
                        self.LabelValidator)
                else:
                    labelString = self.InputText("Please input boundary ids: ",
                                                 self.LabelValidator)
                labels = [int(label) for label in labelString.split()]
                ok = True
                for label in labels:
                    if label not in list(range(numberOfBoundaries)):
                        ok = False

            if (self.Exclude):
                for label in list(range(numberOfBoundaries)):
                    if label not in labels:
                        boundaryIds.InsertNextId(label)
            else:
                for label in labels:
                    boundaryIds.InsertNextId(label)

        flowExtensionsFilter = vtkvmtk.vtkvmtkPolyDataFlowExtensionsFilter()
        flowExtensionsFilter.SetInputData(self.Surface)
        flowExtensionsFilter.SetCenterlines(self.Centerlines)
        flowExtensionsFilter.SetSigma(self.Sigma)
        flowExtensionsFilter.SetAdaptiveExtensionLength(
            self.AdaptiveExtensionLength)
        flowExtensionsFilter.SetAdaptiveExtensionRadius(
            self.AdaptiveExtensionRadius)
        flowExtensionsFilter.SetAdaptiveNumberOfBoundaryPoints(
            self.AdaptiveNumberOfBoundaryPoints)
        flowExtensionsFilter.SetExtensionLength(self.ExtensionLength)
        flowExtensionsFilter.SetExtensionRatio(self.ExtensionRatio)
        flowExtensionsFilter.SetExtensionRadius(self.ExtensionRadius)
        flowExtensionsFilter.SetTransitionRatio(self.TransitionRatio)
        flowExtensionsFilter.SetCenterlineNormalEstimationDistanceRatio(
            self.CenterlineNormalEstimationDistanceRatio)
        flowExtensionsFilter.SetNumberOfBoundaryPoints(
            self.TargetNumberOfBoundaryPoints)
        if self.ExtensionMode == "centerlinedirection":
            flowExtensionsFilter.SetExtensionModeToUseCenterlineDirection()
        elif self.ExtensionMode == "boundarynormal":
            flowExtensionsFilter.SetExtensionModeToUseNormalToBoundary()
        if self.InterpolationMode == "linear":
            flowExtensionsFilter.SetInterpolationModeToLinear()
        elif self.InterpolationMode == "thinplatespline":
            flowExtensionsFilter.SetInterpolationModeToThinPlateSpline()
        if self.Interactive:
            flowExtensionsFilter.SetBoundaryIds(boundaryIds)
        flowExtensionsFilter.Update()

        self.Surface = flowExtensionsFilter.GetOutput()
Esempio n. 34
0
    def Execute(self):

        if self.Surface == None:
            self.PrintError('Error: No input surface.')
        
        if self.CheckNonManifold:
            self.PrintLog('NonManifold check.')
            nonManifoldChecker = vmtkNonManifoldSurfaceChecker()
            nonManifoldChecker.Surface = self.Surface
            nonManifoldChecker.PrintError = self.PrintError
            nonManifoldChecker.Execute()

            if (nonManifoldChecker.NumberOfNonManifoldEdges > 0):
                self.PrintLog(nonManifoldChecker.Report)
                return

        if not self.vmtkRenderer and self.SeedSelectorName in ['pickpoint','openprofiles']:
            self.vmtkRenderer = vmtkrenderer.vmtkRenderer()
            self.vmtkRenderer.Initialize()
            self.OwnRenderer = 1

        self.PrintLog('Cleaning surface.')
        surfaceCleaner = vtk.vtkCleanPolyData()
        surfaceCleaner.SetInputData(self.Surface)
        surfaceCleaner.Update()

        self.PrintLog('Triangulating surface.')
        surfaceTriangulator = vtk.vtkTriangleFilter()
        surfaceTriangulator.SetInputConnection(surfaceCleaner.GetOutputPort())
        surfaceTriangulator.PassLinesOff()
        surfaceTriangulator.PassVertsOff()
        surfaceTriangulator.Update()

        centerlineInputSurface = surfaceTriangulator.GetOutput()

        capCenterIds = None

        if self.SeedSelectorName in ['openprofiles', 'carotidprofiles', 'pickpoint', 'profileidlist']:
            self.PrintLog('Capping surface.')
            surfaceCapper = vtkvmtk.vtkvmtkCapPolyData()
            surfaceCapper.SetInputConnection(surfaceTriangulator.GetOutputPort())
            surfaceCapper.SetDisplacement(self.CapDisplacement)
            surfaceCapper.SetInPlaneDisplacement(self.CapDisplacement)
            surfaceCapper.Update()
            centerlineInputSurface = surfaceCapper.GetOutput()
            capCenterIds = surfaceCapper.GetCapCenterIds()

        if self.SeedSelector:
            pass
        elif self.SeedSelectorName:
            if self.SeedSelectorName == 'pickpoint':
                self.SeedSelector = vmtkPickPointSeedSelector()
                self.SeedSelector.vmtkRenderer = self.vmtkRenderer
                self.SeedSelector.Script = self
            elif self.SeedSelectorName == 'openprofiles':
                self.SeedSelector = vmtkOpenProfilesSeedSelector()
                self.SeedSelector.vmtkRenderer = self.vmtkRenderer
                self.SeedSelector.Script = self
                self.SeedSelector.SetSeedIds(surfaceCapper.GetCapCenterIds())
            elif self.SeedSelectorName == 'carotidprofiles':
                self.SeedSelector = vmtkCarotidProfilesSeedSelector()
                self.SeedSelector.SetSeedIds(surfaceCapper.GetCapCenterIds())
            elif self.SeedSelectorName == 'idlist':
                self.SeedSelector = vmtkIdListSeedSelector()
                self.SeedSelector.SourceIds = self.SourceIds
                self.SeedSelector.TargetIds = self.TargetIds
            elif self.SeedSelectorName == 'pointlist':
                self.SeedSelector = vmtkPointListSeedSelector()
                self.SeedSelector.SourcePoints = self.SourcePoints
                self.SeedSelector.TargetPoints = self.TargetPoints
            elif self.SeedSelectorName != 'profileidlist':
                self.PrintError("SeedSelectorName unknown (available: pickpoint, openprofiles, carotidprofiles, profileidlist, idlist, pointlist)")
                return
        else:
            self.PrintError('vmtkCenterlines error: either SeedSelector or SeedSelectorName must be specified')
            return

        if self.SeedSelector:
            self.SeedSelector.SetSurface(centerlineInputSurface)
            self.SeedSelector.InputInfo = self.InputInfo
            self.SeedSelector.InputText = self.InputText
            self.SeedSelector.OutputText = self.OutputText
            self.SeedSelector.PrintError = self.PrintError
            self.SeedSelector.PrintLog = self.PrintLog
            self.SeedSelector.Execute()

            inletSeedIds = self.SeedSelector.GetSourceSeedIds()
            outletSeedIds = self.SeedSelector.GetTargetSeedIds()
        else:
            inletSeedIds = vtk.vtkIdList()
            outletSeedIds = vtk.vtkIdList()
            for id in self.SourceIds:
                inletSeedIds.InsertNextId(id)
            if self.TargetIds:
                for id in self.TargetIds:
                    outletSeedIds.InsertNextId(id)
            else:
                for i in range(capCenterIds.GetNumberOfIds()):
                    if i not in self.SourceIds:
                        outletSeedIds.InsertNextId(i)

        self.PrintLog('Computing centerlines.')
        self.InputInfo('Computing centerlines...')

        centerlineFilter = vtkvmtk.vtkvmtkPolyDataCenterlines()
        centerlineFilter.SetInputData(centerlineInputSurface)
        if self.SeedSelectorName in ['openprofiles','carotidprofiles','profileidlist']:
            centerlineFilter.SetCapCenterIds(capCenterIds)
        centerlineFilter.SetSourceSeedIds(inletSeedIds)
        centerlineFilter.SetTargetSeedIds(outletSeedIds)
        centerlineFilter.SetRadiusArrayName(self.RadiusArrayName)
        centerlineFilter.SetCostFunction(self.CostFunction)
        centerlineFilter.SetFlipNormals(self.FlipNormals)
        centerlineFilter.SetAppendEndPointsToCenterlines(self.AppendEndPoints)
        centerlineFilter.SetSimplifyVoronoi(self.SimplifyVoronoi)
        if self.DelaunayTessellation != None:
            centerlineFilter.GenerateDelaunayTessellationOff()
            centerlineFilter.SetDelaunayTessellation(self.DelaunayTessellation)
            centerlineFilter.SetDelaunayTolerance(self.DelaunayTolerance)
        if self.UseTetGen==1:
            self.PrintLog('Running TetGen.')
            from vmtk import vmtkscripts
            surfaceToMesh = vmtkscripts.vmtkSurfaceToMesh()
            surfaceToMesh.Surface = centerlineInputSurface
            surfaceToMesh.Execute()
            tetgen = vmtkscripts.vmtkTetGen()
            tetgen.Mesh = surfaceToMesh.Mesh
            tetgen.PLC = 1
            tetgen.NoMerge = 1
            tetgen.Quality = 0
            if self.TetGenDetectInter == 1:
                tetgen.DetectInter = 1
                tetgen.NoMerge = 0
            tetgen.OutputSurfaceElements = 0
            tetgen.Execute()
            centerlineFilter.GenerateDelaunayTessellationOff()
            centerlineFilter.SetDelaunayTessellation(tetgen.Mesh)
        centerlineFilter.SetCenterlineResampling(self.Resampling)
        centerlineFilter.SetResamplingStepLength(self.ResamplingStepLength)
        centerlineFilter.Update()

        self.Centerlines = centerlineFilter.GetOutput()
        self.VoronoiDiagram = centerlineFilter.GetVoronoiDiagram()
        self.DelaunayTessellation = centerlineFilter.GetDelaunayTessellation()
        self.PoleIds = centerlineFilter.GetPoleIds()

        self.EikonalSolutionArrayName = centerlineFilter.GetEikonalSolutionArrayName()
        self.EdgeArrayName = centerlineFilter.GetEdgeArrayName()
        self.EdgePCoordArrayName = centerlineFilter.GetEdgePCoordArrayName()
        self.CostFunctionArrayName = centerlineFilter.GetCostFunctionArrayName()

        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
Esempio n. 35
0
    def Execute(self):
 
        if not self.Network:
            self.Network = vtk.vtkPolyData()
            networkPoints = vtk.vtkPoints()
            networkLines = vtk.vtkCellArray()
            radiusArray = vtk.vtkDoubleArray()
            radiusArray.SetName(self.RadiusArrayName)
            self.Network.SetPoints(networkPoints)
            self.Network.SetLines(networkLines)
            self.Network.GetPointData().AddArray(radiusArray)
        
        if not self.vmtkRenderer:
            self.vmtkRenderer = vmtkrenderer.vmtkRenderer()
            self.vmtkRenderer.Initialize()
            self.OwnRenderer = 1

        self.vmtkRenderer.ExitAfterTextInputMode = False
        self.vmtkRenderer.RegisterScript(self) 

        if self.Image and (not self.PlaneWidgetX or not self.PlaneWidgetY or not self.PlaneWidgetZ):
            imageViewer = vmtkimageviewer.vmtkImageViewer()
            imageViewer.Image = self.Image
            imageViewer.vmtkRenderer = self.vmtkRenderer
            imageViewer.Display = 0
            imageViewer.Execute()
            self.PlaneWidgetX = imageViewer.PlaneWidgetX
            self.PlaneWidgetY = imageViewer.PlaneWidgetY
            self.PlaneWidgetZ = imageViewer.PlaneWidgetZ

        if self.Image:
            spacing = self.Image.GetSpacing()
            self.CurrentRadius = min(spacing)

        if self.UseActiveTubes and not self.FeatureImage:
            imageFeatures = vmtkimagefeatures.vmtkImageFeatures()
            imageFeatures.Image = self.Image
            imageFeatures.FeatureImageType = 'vtkgradient'
            imageFeatures.Execute()
            self.FeatureImage = imageFeatures.FeatureImage
 
        self.NetworkRadiusArray = self.Network.GetPointData().GetArray(self.RadiusArrayName)

        self.Network.GetPointData().SetActiveScalars(self.RadiusArrayName)

        networkMapper = vtk.vtkPolyDataMapper()
        networkMapper.SetInputData(self.Network)
        networkMapper.SetScalarModeToUseCellData()

        self.NetworkActor = vtk.vtkActor()
        self.NetworkActor.SetMapper(networkMapper)
        self.vmtkRenderer.Renderer.AddActor(self.NetworkActor)

        self.NetworkTube = vtk.vtkTubeFilter()
        self.NetworkTube.SetInputData(self.Network)
        self.NetworkTube.SetVaryRadiusToVaryRadiusByAbsoluteScalar()
        self.NetworkTube.SetNumberOfSides(20)
        networkTubeMapper = vtk.vtkPolyDataMapper()
        networkTubeMapper.SetInputConnection(self.NetworkTube.GetOutputPort())
        networkTubeMapper.ScalarVisibilityOff()
        networkTubeActor = vtk.vtkActor()
        networkTubeActor.SetMapper(networkTubeMapper)
        networkTubeActor.PickableOff()
        networkTubeActor.GetProperty().SetOpacity(0.2)
        self.vmtkRenderer.Renderer.AddActor(networkTubeActor)

        self.Selection = vtk.vtkPolyData()
        self.SelectionPoints = vtk.vtkPoints()
        self.SelectionRadiusArray = vtk.vtkDoubleArray()
        self.SelectionRadiusArray.SetName(self.RadiusArrayName)
        self.Selection.SetPoints(self.SelectionPoints)
        self.Selection.GetPointData().AddArray(self.SelectionRadiusArray)
        self.Selection.GetPointData().SetActiveScalars(self.RadiusArrayName)

        glyphs = vtk.vtkGlyph3D()
        glyphSource = vtk.vtkSphereSource()
        glyphSource.SetRadius(1.0)
        glyphSource.SetThetaResolution(20)
        glyphSource.SetPhiResolution(20)
        glyphs.SetInputData(self.Selection)
        glyphs.SetSourceConnection(glyphSource.GetOutputPort())
        glyphs.SetScaleModeToScaleByScalar()
        glyphs.SetScaleFactor(1.0)

        selectionMapper = vtk.vtkPolyDataMapper()
        selectionMapper.SetInputConnection(glyphs.GetOutputPort())

        self.SelectionActor = vtk.vtkActor()
        self.SelectionActor.SetMapper(selectionMapper)
        self.SelectionActor.GetProperty().SetColor(1.0,0.0,0.0)
        self.SelectionActor.GetProperty().SetOpacity(0.5)
        self.SelectionActor.PickableOff()
        self.vmtkRenderer.Renderer.AddActor(self.SelectionActor)

        self.ActiveSegmentSeeds = vtk.vtkPolyData()
        self.ActiveSegmentSeedsPoints = vtk.vtkPoints()
        self.ActiveSegmentSeedsRadiusArray = vtk.vtkDoubleArray()
        self.ActiveSegmentSeedsRadiusArray.SetName(self.RadiusArrayName)
        self.ActiveSegmentSeeds.SetPoints(self.ActiveSegmentSeedsPoints)
        self.ActiveSegmentSeeds.GetPointData().AddArray(self.ActiveSegmentSeedsRadiusArray)
        self.ActiveSegmentSeeds.GetPointData().SetActiveScalars(self.RadiusArrayName)

        activeSegmentSeedsGlyphs = vtk.vtkGlyph3D()
        activeSegmentSeedsGlyphSource = vtk.vtkSphereSource()
        activeSegmentSeedsGlyphSource.SetRadius(1.0)
        activeSegmentSeedsGlyphSource.SetThetaResolution(20)
        activeSegmentSeedsGlyphSource.SetPhiResolution(20)
        activeSegmentSeedsGlyphs.SetInputData(self.ActiveSegmentSeeds)
        activeSegmentSeedsGlyphs.SetSourceConnection(activeSegmentSeedsGlyphSource.GetOutputPort())
        activeSegmentSeedsGlyphs.SetScaleModeToScaleByScalar()
        activeSegmentSeedsGlyphs.SetScaleFactor(1.0)

        activeSegmentSeedsMapper = vtk.vtkPolyDataMapper()
        activeSegmentSeedsMapper.SetInputConnection(activeSegmentSeedsGlyphs.GetOutputPort())
        activeSegmentSeedsMapper.ScalarVisibilityOff()

        self.ActiveSegmentSeedsActor = vtk.vtkActor()
        self.ActiveSegmentSeedsActor.SetMapper(activeSegmentSeedsMapper)
        self.ActiveSegmentSeedsActor.GetProperty().SetColor(1.0,0.0,0.0)
        self.ActiveSegmentSeedsActor.GetProperty().SetOpacity(0.5)
        self.ActiveSegmentSeedsActor.PickableOff()
        self.vmtkRenderer.Renderer.AddActor(self.ActiveSegmentSeedsActor)

        self.ActiveSegment = vtk.vtkPolyData()
        self.ActiveSegmentPoints = vtk.vtkPoints()
        self.ActiveSegmentCellArray = vtk.vtkCellArray()
        self.ActiveSegmentRadiusArray = vtk.vtkDoubleArray()
        self.ActiveSegmentRadiusArray.SetName(self.RadiusArrayName)
        self.ActiveSegment.SetPoints(self.ActiveSegmentPoints)
        self.ActiveSegment.SetLines(self.ActiveSegmentCellArray)
        self.ActiveSegment.GetPointData().AddArray(self.ActiveSegmentRadiusArray)
        self.ActiveSegment.GetPointData().SetActiveScalars(self.RadiusArrayName)

        activeSegmentMapper = vtk.vtkPolyDataMapper()
        activeSegmentMapper.ScalarVisibilityOff()
        if self.SplineInterpolation and self.Image != None:
            splineFilter = vtk.vtkSplineFilter()
            splineFilter.SetInputData(self.ActiveSegment)
            splineFilter.SetSubdivideToLength()
            splineFilter.SetLength(2.0*min(self.Image.GetSpacing()))
            activeSegmentMapper.SetInputConnection(splineFilter.GetOutputPort())
        else:
            activeSegmentMapper.SetInputData(self.ActiveSegment)

        self.ActiveSegmentActor = vtk.vtkActor()
        self.ActiveSegmentActor.SetMapper(activeSegmentMapper)
        self.ActiveSegmentActor.GetProperty().SetColor(1.0,1.0,1.0)
        self.ActiveSegmentActor.GetProperty().SetLineWidth(3.0)
        self.ActiveSegmentActor.PickableOff()
        self.vmtkRenderer.Renderer.AddActor(self.ActiveSegmentActor)

        activeTube = vtk.vtkTubeFilter()
        activeTube.SetInputConnection(activeSegmentMapper.GetInputPort())
        activeTube.SetVaryRadiusToVaryRadiusByAbsoluteScalar()
        activeTube.SetNumberOfSides(20)
        activeTubeMapper = vtk.vtkPolyDataMapper()
        activeTubeMapper.SetInputConnection(activeTube.GetOutputPort())
        activeTubeMapper.ScalarVisibilityOff()
        activeTubeActor = vtk.vtkActor()
        activeTubeActor.SetMapper(activeTubeMapper)
        activeTubeActor.PickableOff()
        activeTubeActor.GetProperty().SetOpacity(0.6)
        self.vmtkRenderer.Renderer.AddActor(activeTubeActor)

        self.NetworkLabelsArray = vtk.vtkStringArray.SafeDownCast(self.Network.GetCellData().GetAbstractArray(self.LabelsArrayName))
        if not self.NetworkLabelsArray:
            self.NetworkLabelsArray = vtk.vtkStringArray()
            self.NetworkLabelsArray.SetName(self.LabelsArrayName)
            self.NetworkLabelsArray.SetNumberOfValues(self.Network.GetNumberOfCells())
            for i in range(self.Network.GetNumberOfCells()):
                self.NetworkLabelsArray.SetValue(i,'')
            self.Network.GetCellData().AddArray(self.NetworkLabelsArray)
        self.CellCenters = vtk.vtkCellCenters()
        self.CellCenters.SetInputData(self.Network)
        self.CellCenters.VertexCellsOff()
        self.CellCenters.Update()

        labeledMapper = vtk.vtkLabeledDataMapper()
        labeledMapper.SetInputConnection(self.CellCenters.GetOutputPort())
        labeledMapper.SetLabelModeToLabelFieldData()
        labeledMapper.SetFieldDataName(self.LabelsArrayName)
        labeledMapper.GetLabelTextProperty().SetFontFamilyToArial()
        labeledMapper.GetLabelTextProperty().BoldOff()
        labeledMapper.GetLabelTextProperty().ItalicOff()
        labeledMapper.GetLabelTextProperty().ShadowOff()
        
        self.LabelsActor = vtk.vtkActor2D()
        self.LabelsActor.SetMapper(labeledMapper)
        self.LabelsActor.VisibilityOff()
        self.vmtkRenderer.Renderer.AddActor(self.LabelsActor)

        self.CellPicker = vtk.vtkCellPicker()
        self.CellPicker.SetTolerance(1E-2)
        self.CellPicker.InitializePickList()
        self.CellPicker.AddPickList(self.NetworkActor)
        self.CellPicker.PickFromListOn()

        self.vmtkRenderer.AddKeyBinding('a','Add mode.',self.AddCallback)
        self.vmtkRenderer.AddKeyBinding('d','Delete mode.',self.DeleteCallback)
        self.vmtkRenderer.AddKeyBinding('m','Merge mode.',self.MergeCallback)
        self.vmtkRenderer.AddKeyBinding('s','Split mode.',self.SplitCallback)
        self.vmtkRenderer.AddKeyBinding('l','Label mode.',self.LabelCallback)
        self.vmtkRenderer.AddKeyBinding('Tab','Show labels.',self.ShowLabelCallback)
        self.vmtkRenderer.RenderWindowInteractor.AddObserver("KeyReleaseEvent", self.KeyReleaseCallback)
        self.vmtkRenderer.RenderWindowInteractor.AddObserver("LeftButtonPressEvent", self.LeftButtonPressCallback)
        self.vmtkRenderer.RenderWindowInteractor.AddObserver("MouseMoveEvent", self.MouseMoveCallback)

        if self.PlaneWidgetX:
            self.PlaneWidgetX.UseContinuousCursorOn()
            self.PlaneWidgetX.AddObserver("StartInteractionEvent", self.PlaneStartInteractionCallback)
        if self.PlaneWidgetY:
            self.PlaneWidgetY.UseContinuousCursorOn()
            self.PlaneWidgetY.AddObserver("StartInteractionEvent", self.PlaneStartInteractionCallback)
        if self.PlaneWidgetZ:
            self.PlaneWidgetZ.UseContinuousCursorOn()
            self.PlaneWidgetZ.AddObserver("StartInteractionEvent", self.PlaneStartInteractionCallback)

        self.FirstRender()

        self.Surface = self.NetworkTube.GetOutput()

        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
Esempio n. 36
0
    def Execute(self):

        if not self.Centerlines:
            self.PrintError('Error: No input centerlines.')

        if not self.GroupIdsArrayName:
            self.PrintError('Error: GroupIdsArrayName not specified.')

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

        self.vmtkRenderer.RegisterScript(self)

        groupIdsArray = self.Centerlines.GetCellData().GetArray(
            self.GroupIdsArrayName)
        groupIds = []
        for i in range(groupIdsArray.GetNumberOfTuples()):
            groupIds.append(int(groupIdsArray.GetComponent(i, 0)))
        groupIds.sort()
        uniqueGroupIds = []
        for groupId in groupIds:
            if groupId not in uniqueGroupIds:
                uniqueGroupIds.append(groupId)

        labelMap = {}

        if not self.Labeling:

            viewer = vmtkcenterlineviewer.vmtkCenterlineViewer()
            viewer.Centerlines = self.Centerlines
            viewer.CellDataArrayName = self.GroupIdsArrayName
            viewer.vmtkRenderer = self.vmtkRenderer
            viewer.InputStream = self.InputStream
            viewer.OutputStream = self.OutputStream
            #viewer.InputText = self.InputText
            #viewer.OutputText = self.OutputText
            #viewer.PrintError = self.PrintError
            #viewer.PringLog = self.PrintLog
            viewer.Execute()

            ok = False
            while not ok:
                labelString = self.InputText(
                    "Please input labels for the following groupIds:\n%s\n" %
                    " ".join([str(groupId) for groupId in uniqueGroupIds]),
                    self.LabelValidator)
                labels = [int(label) for label in labelString.split()]
                if len(labels) == len(uniqueGroupIds):
                    ok = True

            for groupId in uniqueGroupIds:
                labelMap[groupId] = labels[uniqueGroupIds.index(groupId)]

        else:

            if len(self.Labeling) != 2 * len(uniqueGroupIds):
                self.PrintError('Error: incorrect labeling specified')

            for i in range(len(self.Labeling) / 2):
                groupId = self.Labeling[2 * i]
                labelId = self.Labeling[2 * i + 1]
                if not groupId in uniqueGroupIds:
                    self.PrintError('Error: groupId %d does not exist' %
                                    groupId)
                labelMap[groupId] = labelId

        labelIdsArray = vtk.vtkIntArray()
        labelIdsArray.SetName(self.LabelIdsArrayName)
        labelIdsArray.SetNumberOfComponents(1)
        labelIdsArray.SetNumberOfTuples(self.Centerlines.GetNumberOfCells())

        groupIdsArray = self.Centerlines.GetCellData().GetArray(
            self.GroupIdsArrayName)

        for i in range(groupIdsArray.GetNumberOfTuples()):
            groupId = int(groupIdsArray.GetComponent(i, 0))
            labelIdsArray.SetComponent(i, 0, labelMap[groupId])

        self.Centerlines.GetCellData().AddArray(labelIdsArray)

        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
Esempio n. 37
0
    def Execute(self):
 
        if not self.Mesh:
            self.PrintError('Error: No input mesh.')
            return
 
        if not self.CellEntityIdsArrayName:
            self.PrintError('Error: No input CellEntityIdsArrayName.')
            return
 
        if not self.vmtkRenderer:
            self.vmtkRenderer = vmtkrenderer.vmtkRenderer()
            self.vmtkRenderer.Initialize()
            self.OwnRenderer = 1

        self.vmtkRenderer.RegisterScript(self) 

        threshold = vtk.vtkThreshold()
        threshold.SetInputData(self.Mesh)
        threshold.ThresholdByUpper(self.VolumeCellEntityId+0.5)
        threshold.SetInputArrayToProcess(0,0,0,1,self.CellEntityIdsArrayName)
        threshold.Update()

        boundaryMesh = threshold.GetOutput()
        boundaryMesh.GetCellData().SetActiveScalars(self.CellEntityIdsArrayName)

        boundaryMapper = vtk.vtkDataSetMapper()
        boundaryMapper.SetInputData(boundaryMesh)
        boundaryMapper.ScalarVisibilityOn()
        boundaryMapper.SetScalarModeToUseCellData()
        boundaryMapper.SetScalarRange(boundaryMesh.GetCellData().GetScalars().GetRange())

        boundaryActor = vtk.vtkActor()
        boundaryActor.SetMapper(boundaryMapper)
        self.vmtkRenderer.Renderer.AddActor(boundaryActor)

        wallThreshold = vtk.vtkThreshold()
        wallThreshold.SetInputData(boundaryMesh)
        wallThreshold.ThresholdByLower(self.WallCellEntityId+0.5)
        wallThreshold.SetInputArrayToProcess(0,0,0,1,self.CellEntityIdsArrayName)
        wallThreshold.Update()

        wallMeshToSurface = vtk.vtkGeometryFilter()
        wallMeshToSurface.SetInputConnection(wallThreshold.GetOutputPort())
        wallMeshToSurface.Update()

        boundaryReferenceSystems = vtkvmtk.vtkvmtkBoundaryReferenceSystems()
        boundaryReferenceSystems.SetInputConnection(wallMeshToSurface.GetOutputPort())
        boundaryReferenceSystems.SetBoundaryRadiusArrayName("BoundaryRadius")
        boundaryReferenceSystems.SetBoundaryNormalsArrayName("BoundaryNormals")
        boundaryReferenceSystems.SetPoint1ArrayName("Point1Array")
        boundaryReferenceSystems.SetPoint2ArrayName("Point2Array")
        boundaryReferenceSystems.Update()

        self.ReferenceSystems = boundaryReferenceSystems.GetOutput()

        cellEntityIdsArray = vtk.vtkIntArray()
        cellEntityIdsArray.SetName(self.CellEntityIdsArrayName)
        cellEntityIdsArray.SetNumberOfTuples(self.ReferenceSystems.GetNumberOfPoints())

        self.ReferenceSystems.GetPointData().AddArray(cellEntityIdsArray)

        boundaryThreshold = vtk.vtkThreshold()
        boundaryThreshold.SetInputData(boundaryMesh)
        boundaryThreshold.ThresholdByUpper(self.WallCellEntityId+0.5)
        boundaryThreshold.SetInputArrayToProcess(0,0,0,1,self.CellEntityIdsArrayName)
        boundaryThreshold.Update()

        boundaryMeshToSurface = vtk.vtkGeometryFilter()
        boundaryMeshToSurface.SetInputConnection(boundaryThreshold.GetOutputPort())
        boundaryMeshToSurface.Update()

        boundarySurface = boundaryMeshToSurface.GetOutput()
        pointCells = vtk.vtkIdList()

        surfaceCellEntityIdsArray = vtk.vtkIntArray()
        surfaceCellEntityIdsArray.DeepCopy(boundarySurface.GetCellData().GetArray(self.CellEntityIdsArrayName))

        self.PrintLog('')
        for i in range(self.ReferenceSystems.GetNumberOfPoints()):
            pointId = boundarySurface.FindPoint(self.ReferenceSystems.GetPoint(i))
            boundarySurface.GetPointCells(pointId,pointCells)
            cellId = pointCells.GetId(0)
            cellEntityId = surfaceCellEntityIdsArray.GetValue(cellId)
            cellEntityIdsArray.SetValue(i,cellEntityId)
            origin = self.ReferenceSystems.GetPoint(i)
            normal = self.ReferenceSystems.GetPointData().GetArray("BoundaryNormals").GetTuple3(i)
            radius = self.ReferenceSystems.GetPointData().GetArray("BoundaryRadius").GetTuple1(i)
            logLine = 'CellEntityId: %d\n' % cellEntityId
            logLine += '  Origin: %f, %f, %f\n' % (origin[0],origin[1],origin[2])
            logLine += '  Normal: %f, %f, %f\n' % (normal[0],normal[1],normal[2])
            logLine += '  Radius: %f\n' % radius
            self.PrintLog(logLine)

        self.ReferenceSystems.GetPointData().SetActiveScalars(self.CellEntityIdsArrayName)

        labelsMapper = vtk.vtkLabeledDataMapper();
        labelsMapper.SetInputData(self.ReferenceSystems)
        labelsMapper.SetLabelModeToLabelScalars()
        labelsActor = vtk.vtkActor2D()
        labelsActor.SetMapper(labelsMapper)
        self.vmtkRenderer.Renderer.AddActor(labelsActor)

        self.vmtkRenderer.Render()

        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
    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. 39
0
    def Execute(self):

        if not self.Surface:
            self.PrintError('Error: No input surface.')

        if not self.Centerlines:
            self.PrintError('Error: No input centerlines.')

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

            self.vmtkRenderer.RegisterScript(self) 

            viewer = vmtkcenterlineviewer.vmtkCenterlineViewer()
            viewer.Centerlines = self.Centerlines
            viewer.CellDataArrayName = self.GroupIdsArrayName
            viewer.vmtkRenderer = self.vmtkRenderer
            viewer.InputText = self.InputText
            viewer.OutputText = self.OutputText
            viewer.PrintError = self.PrintError
            viewer.PringLog = self.PrintLog
            viewer.Display = 0
            viewer.Execute()         

            groupIdsString = self.InputText("Please input groupIds to clip:\n",self.GroupIdsValidator)
            self.GroupIds = [int(groupId) for groupId in groupIdsString.split()]

        clipper = vtkvmtk.vtkvmtkPolyDataCenterlineGroupsClipper()
        clipper.SetInputData(self.Surface)
        clipper.SetCenterlines(self.Centerlines)
        clipper.SetCenterlineGroupIdsArrayName(self.GroupIdsArrayName)
        clipper.SetGroupIdsArrayName(self.GroupIdsArrayName)
        clipper.SetCenterlineRadiusArrayName(self.RadiusArrayName)
        clipper.SetBlankingArrayName(self.BlankingArrayName)
        clipper.SetCutoffRadiusFactor(self.CutoffRadiusFactor)
        clipper.SetClipValue(self.ClipValue)
        clipper.SetUseRadiusInformation(self.UseRadiusInformation)
        if self.GroupIds:
            groupIds = vtk.vtkIdList()
            for groupId in self.GroupIds:
                groupIds.InsertNextId(groupId)
            clipper.SetCenterlineGroupIds(groupIds)
            clipper.ClipAllCenterlineGroupIdsOff()
        else:
            clipper.ClipAllCenterlineGroupIdsOn()
        if not self.InsideOut:
            clipper.GenerateClippedOutputOff()
        else:
            clipper.GenerateClippedOutputOn()
        clipper.Update()

        if not self.InsideOut:
            self.Surface = clipper.GetOutput()
        else:
            self.Surface = clipper.GetClippedOutputData()

        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
Esempio n. 40
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.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. 41
0
    def Execute(self):

        if self.Surface == None:
            self.PrintError('Error: No input surface.')

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

        boundaryIds = vtk.vtkIdList()

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

            self.vmtkRenderer.RegisterScript(self)

            boundaryExtractor = vtkvmtk.vtkvmtkPolyDataBoundaryExtractor()
            boundaryExtractor.SetInputData(self.Surface)
            boundaryExtractor.Update()

            boundaries = boundaryExtractor.GetOutput()
            numberOfBoundaries = boundaries.GetNumberOfCells()
            seedPoints = vtk.vtkPoints()
            for i in range(numberOfBoundaries):
                barycenter = [0.0, 0.0, 0.0]
                vtkvmtk.vtkvmtkBoundaryReferenceSystems.ComputeBoundaryBarycenter(boundaries.GetCell(i).GetPoints(),barycenter)
                seedPoints.InsertNextPoint(barycenter)
            seedPolyData = vtk.vtkPolyData()
            seedPolyData.SetPoints(seedPoints)
            labelsMapper = vtk.vtkLabeledDataMapper();
            labelsMapper.SetInputData(seedPolyData)
            labelsMapper.SetLabelModeToLabelIds()
            labelsActor = vtk.vtkActor2D()
            labelsActor.SetMapper(labelsMapper)

            self.vmtkRenderer.Renderer.AddActor(labelsActor)

            surfaceMapper = vtk.vtkPolyDataMapper()
            surfaceMapper.SetInputData(self.Surface)
            surfaceMapper.ScalarVisibilityOff()
            surfaceActor = vtk.vtkActor()
            surfaceActor.SetMapper(surfaceMapper)
            surfaceActor.GetProperty().SetOpacity(0.25)

            self.vmtkRenderer.Renderer.AddActor(surfaceActor)

            #self.vmtkRenderer.Render()
            #self.vmtkRenderer.Renderer.RemoveActor(labelsActor)
            #self.vmtkRenderer.Renderer.RemoveActor(surfaceActor)

            ok = False
            while not ok:
                labelString = self.InputText("Please input boundary ids: ",self.LabelValidator)
                labels = [int(label) for label in labelString.split()]
                ok = True
                for label in labels:
                    if label not in list(range(numberOfBoundaries)):
                        ok = False

            for label in labels:
                boundaryIds.InsertNextId(label)

        if self.Method == 'simple':
            capper = vtkvmtk.vtkvmtkSimpleCapPolyData()
            capper.SetInputData(self.Surface)

        elif self.Method == 'centerpoint':
            capper = vtkvmtk.vtkvmtkCapPolyData()
            capper.SetInputData(self.Surface)
            capper.SetDisplacement(0.0)
            capper.SetInPlaneDisplacement(0.0)

        elif self.Method == 'smooth':
            triangle = vtk.vtkTriangleFilter()
            triangle.SetInputData(self.Surface)
            triangle.PassLinesOff()
            triangle.PassVertsOff()
            triangle.Update()
            capper = vtkvmtk.vtkvmtkSmoothCapPolyData()
            capper.SetInputConnection(triangle.GetOutputPort())
            capper.SetConstraintFactor(self.ConstraintFactor)
            capper.SetNumberOfRings(self.NumberOfRings)

        elif self.Method == 'annular':
            capper = vtkvmtk.vtkvmtkAnnularCapPolyData()
            capper.SetInputData(self.Surface)

        elif self.Method == 'concaveannular':
            from vmtk import vtkvmtkcontrib
            capper = vtkvmtkcontrib.vtkvmtkConcaveAnnularCapPolyData()
            capper.SetInputData(self.Surface)

        if self.Interactive:
            capper.SetBoundaryIds(boundaryIds)
        capper.SetCellEntityIdsArrayName(self.CellEntityIdsArrayName)
        capper.SetCellEntityIdOffset(self.CellEntityIdOffset)
        capper.Update()
        self.Surface = capper.GetOutput()

        if self.TriangleOutput == 1:
            triangle = vtk.vtkTriangleFilter()
            triangle.SetInputData(self.Surface)
            triangle.PassLinesOff()
            triangle.PassVertsOff()
            triangle.Update()
            self.Surface = triangle.GetOutput()

        normals = vtk.vtkPolyDataNormals()
        normals.SetInputData(self.Surface)
        normals.AutoOrientNormalsOn()
        normals.SplittingOff()
        normals.ConsistencyOn()
        normals.Update()
        self.Surface = normals.GetOutput()
Esempio n. 42
0
    def BuildView(self):

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

        if self.Actor != None:
            self.vmtkRenderer.Renderer.RemoveActor(self.Actor)

        if self.ScalarBarActor != None:
            self.vmtkRenderer.Renderer.RemoveActor(self.ScalarBarActor)

        if self.Mesh != None:
            self.InitialMesh = self.Mesh
            self.DisplayMesh = self.Mesh
            mapper = vtk.vtkDataSetMapper()
            mapper.SetInputData(self.DisplayMesh)
            array = None
            if (self.ArrayName != ''):
                if self.DisplayCellData == 0:
                    self.Mesh.GetPointData().SetActiveScalars(self.ArrayName)
                    array = self.Mesh.GetPointData().GetScalars()
                else:
                    self.Mesh.GetCellData().SetActiveScalars(self.ArrayName)
                    array = self.Mesh.GetCellData().GetScalars()
                    mapper.SetScalarModeToUseCellData()
            if (array != None):
                if (self.ScalarRange[1] > self.ScalarRange[0]):
                    mapper.SetScalarRange(self.ScalarRange)
                else:
                    mapper.SetScalarRange(array.GetRange(0))
                if (self.Grayscale == 1):
                    lut = vtk.vtkLookupTable()
                    lut.SetValueRange(0.0, 1.0)
                    lut.SetSaturationRange(0.0, 0.0)
                    mapper.SetLookupTable(lut)

            self.Actor = vtk.vtkActor()
            self.Actor.SetMapper(mapper)
            if (self.Color[0] >= 0.0):
                self.Actor.GetProperty().SetColor(self.Color)
            if (self.FlatInterpolation == 1):
                self.Actor.GetProperty().SetInterpolationToFlat()
            self.Actor.GetProperty().SetOpacity(self.Opacity)
            self.vmtkRenderer.Renderer.AddActor(self.Actor)

        if (self.Legend == 1) & (self.Actor != None):
            self.ScalarBarActor = vtk.vtkScalarBarActor()
            self.ScalarBarActor.SetLookupTable(
                self.Actor.GetMapper().GetLookupTable())
            self.ScalarBarActor.GetLabelTextProperty().ItalicOff()
            self.ScalarBarActor.GetLabelTextProperty().BoldOff()
            self.ScalarBarActor.GetLabelTextProperty().ShadowOff()
            ##             self.ScalarBarActor.GetLabelTextProperty().SetColor(0.0,0.0,0.0)
            self.ScalarBarActor.SetLabelFormat('%.2f')
            self.vmtkRenderer.Renderer.AddActor(self.ScalarBarActor)

        #self.vmtkRenderer.RenderWindowInteractor.AddObserver("KeyPressEvent", self.KeyPressed)
        self.vmtkRenderer.AddKeyBinding('i', 'Interact.',
                                        self.InteractCallback)
        self.vmtkRenderer.AddKeyBinding('c', 'Clip.', self.ClipCallback)
        self.vmtkRenderer.AddKeyBinding('e', 'Extract.', self.ExtractCallback)
        self.vmtkRenderer.AddKeyBinding('n', 'Show clipped area.',
                                        self.NCallback)
        self.vmtkRenderer.AddKeyBinding('d', 'Switch clipped/unclipped area.',
                                        self.DCallback)
        self.vmtkRenderer.AddKeyBinding('t', 'Redo.', self.TCallback)
        self.vmtkRenderer.AddKeyBinding('u', 'Undo.', self.UndoCallback)
        self.PlaneWidget = vtk.vtkImplicitPlaneWidget()
        self.PlaneWidget.SetInteractor(
            self.vmtkRenderer.RenderWindowInteractor)
        self.PlaneWidget.SetPlaceFactor(1.25)
        self.PlaneWidget.DrawPlaneOff()
        self.PlaneWidget.SetProp3D(self.Actor)
        self.PlaneWidget.PlaceWidget()
        #Work around bug/strange behaviour in vtk
        self.PlaneWidget.SetOrigin(self.Actor.GetCenter())

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

        self.Mesh = self.InitialMesh

        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
Esempio n. 43
0
    def Execute(self):
        if self.Surface == None:
            self.PrintError('Error: No input surface.')

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

        self.vmtkRenderer.RegisterScript(self) 
            
        # a check to make sure nothing has ran out of order.
        if self.SeedSelector:
            pass
        else:
            # initialize the seed selection method
            self.SeedSelector = vmtkPickPointSeedSelector()
            self.SeedSelector.vmtkRenderer = self.vmtkRenderer
            self.SeedSelector.Script = self
        
        # label all non-connected regions in an input surface. 
        allRegionConnectivity = vtk.vtkPolyDataConnectivityFilter()
        allRegionConnectivity.SetInputData(self.Surface)
        allRegionConnectivity.SetExtractionModeToAllRegions()
        allRegionConnectivity.ColorRegionsOn()
        allRegionConnectivity.Update()

        # create the actor/mapper which renders the labeled input surface
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputData(allRegionConnectivity.GetOutput())
        mapper.ScalarVisibilityOff()
        mapper.Update()

        actor = vtk.vtkActor()
        actor.SetMapper(mapper)
        actor.GetProperty().SetColor(0.7, 0.7, 0.7) # standard gray color
        actor.GetProperty().SetDiffuse(0.9)
        actor.GetProperty().SetSpecular(0.2)
        actor.GetProperty().SetRepresentationToSurface()
        actor.GetProperty().EdgeVisibilityOff()

        # add this as the main actor to the scene (the first think you see)
        self.vmtkRenderer.Renderer.AddActor(actor)

        if self.SeedSelector:
            self.SeedSelector.InputInfo = self.InputInfo
            self.SeedSelector.InputText = self.InputText
            self.SeedSelector.OutputText = self.OutputText
            self.SeedSelector.PrintError = self.PrintError
            self.SeedSelector.PrintLog = self.PrintLog
            # until SeedSelector releases control of execution, the program will not
            # proceed past the next line. SeedSelector handles all user interaction and
            # modification/logging of actor properties & region Ids
            self.SeedSelector.Execute()

            # we store each extracted region as individual vtkPolyData objects within a list.
            # They are combined into one dataset below.
            polyDataAppender = vtk.vtkAppendPolyData()
            for outputSurfacePolyData in self.SeedSelector._OutputPolyDataList:
                polyDataAppender.AddInputData(outputSurfacePolyData)

            # Even though we clean the selection in the SeedSelection, this is necessary because it
            # may be possible for a user to select the same polydata object twice. If this is not cleaned,
            # a double selection may mess with further post processing scripts. 
            polyDataCleaner = vtk.vtkCleanPolyData()
            polyDataCleaner.SetInputConnection(polyDataAppender.GetOutputPort())
            polyDataCleaner.Update()

            self.Surface = polyDataAppender.GetOutput()

        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
Esempio n. 44
0
    def Execute(self):

        if (self._Surface == None):
            self.PrintError(
                'vmtkPickPointSeedSelector Error: Surface not set.')
            return

        self._SourceSeedIds.Initialize()
        self._TargetSeedIds.Initialize()

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

        self.vmtkRenderer.RegisterScript(self.Script)

        glyphs = vtk.vtkGlyph3D()
        glyphSource = vtk.vtkSphereSource()
        glyphs.SetInputData(self.PickedSeeds)
        glyphs.SetSourceConnection(glyphSource.GetOutputPort())
        glyphs.SetScaleModeToDataScalingOff()
        glyphs.SetScaleFactor(self._Surface.GetLength() * 0.01)
        glyphMapper = vtk.vtkPolyDataMapper()
        glyphMapper.SetInputConnection(glyphs.GetOutputPort())
        self.SeedActor = vtk.vtkActor()
        self.SeedActor.SetMapper(glyphMapper)
        self.SeedActor.GetProperty().SetColor(1.0, 0.0, 0.0)
        self.SeedActor.PickableOff()
        self.vmtkRenderer.Renderer.AddActor(self.SeedActor)

        ##self.vmtkRenderer.RenderWindowInteractor.AddObserver("KeyPressEvent", self.KeyPressed)
        self.vmtkRenderer.AddKeyBinding('u', 'Undo.', self.UndoCallback)
        self.vmtkRenderer.AddKeyBinding('space', 'Add points.',
                                        self.PickCallback)
        surfaceMapper = vtk.vtkPolyDataMapper()
        surfaceMapper.SetInputData(self._Surface)
        surfaceMapper.ScalarVisibilityOff()
        surfaceActor = vtk.vtkActor()
        surfaceActor.SetMapper(surfaceMapper)
        surfaceActor.GetProperty().SetOpacity(1.0)

        self.vmtkRenderer.Renderer.AddActor(surfaceActor)

        self.InputInfo(
            'Please position the mouse and press space to add source points, \'u\' to undo\n'
        )

        any = 0
        while any == 0:
            self.InitializeSeeds()
            self.vmtkRenderer.Render()
            any = self.PickedSeedIds.GetNumberOfIds()
        self._SourceSeedIds.DeepCopy(self.PickedSeedIds)

        self.InputInfo(
            'Please position the mouse and press space to add target points, \'u\' to undo\n'
        )

        any = 0
        while any == 0:
            self.InitializeSeeds()
            self.vmtkRenderer.Render()
            any = self.PickedSeedIds.GetNumberOfIds()
        self._TargetSeedIds.DeepCopy(self.PickedSeedIds)

        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
def visualize_landmarks(landmarks, centerline, algorithm, surface_path):
    """
    Visualize the interfaces between the resulting landmarks (points)

    Args:
        landmarks (ndarray): Points defining landmarks / interfaces between segments
        centerline (vtkPolyData): Centerline which has been landmarked
        algorithm (str): Name of landmarking algorithm
        surface_path (str): Location of surface model
    """
    vtkPoints = vtk.vtkPoints()
    landmarkSpheres = []
    for key, point in landmarks.items():
        sphere = vtk.vtkSphereSource()
        sphere.SetRadius(1)
        sphere.SetCenter(point[0], point[1], point[2])
        sphere.Update()
        landmarkSpheres.append(sphere.GetOutput())
        vtkPoints.InsertNextPoint(point)

    landmarkData = vtk_merge_polydata(landmarkSpheres)

    surface = None
    if path.exists(surface_path):
        surface = read_polydata(surface_path)

    vtkNameArray = vtk.vtkStringArray()
    vtkNameArray.SetNumberOfValues(7)

    if algorithm == "piccinelli":
        start = len(landmarks) - 1
        stop = -1
        interfaces = ["Bend %s-%s" % (i, i + 1) for i in range(len(landmarks))]
    elif algorithm == "bogunovic":
        start = 3
        stop = -1
        interfaces = [
            "Anterior-Posterior",
            "Posterior-Inferior",
            "Inferior (Start)",
            "Superior-Anterior",
        ]

    for i in range(start, stop, -1):
        if i == 0:
            if algorithm == "piccinelli":
                vtkNameArray.SetValue(i, 'Bend 1 (Start)')
            elif algorithm == "bogunovic":
                vtkNameArray.SetValue(i, interfaces[i])
        else:
            vtkNameArray.SetValue(i, interfaces[i])

    # Create the dataset with landmarking points
    labeledPolydata = vtk.vtkPolyData()
    labeledPolydata.SetPoints(vtkPoints)
    labeledPolydata.GetPointData().AddArray(vtkNameArray)

    centerlineMapper = vtk.vtkPolyDataMapper()
    centerlineMapper.SetInputData(centerline)
    centerlineActor = vtk.vtkActor()
    centerlineActor.SetMapper(centerlineMapper)
    centerlineActor.GetProperty().SetLineWidth(10)
    centerlineActor.GetProperty().SetColor(1, 0, 0)

    landmarkMapper = vtk.vtkPolyDataMapper()
    landmarkMapper.SetInputData(landmarkData)
    landmarkActor = vtk.vtkActor()
    landmarkActor.SetMapper(landmarkMapper)

    labelsMapper = vtk.vtkLabeledDataMapper()
    labelsMapper.SetInputData(labeledPolydata)
    labelsMapper.SetLabelModeToLabelFieldData()
    labelsMapper.GetLabelTextProperty().SetColor(1, 1, 1)
    labelsMapper.GetLabelTextProperty().SetFontSize(35)
    labelsMapper.GetLabelTextProperty().ItalicOff()

    labelsActor = vtk.vtkActor2D()
    labelsActor.SetMapper(labelsMapper)

    vmtkRenderer = vmtkrenderer.vmtkRenderer()
    vmtkRenderer.Initialize()
    vmtkRenderer.Renderer.AddActor(centerlineActor)
    vmtkRenderer.Renderer.AddActor(labelsActor)
    vmtkRenderer.Renderer.AddActor(landmarkActor)

    if surface is not None:
        surfaceMapper = vtk.vtkPolyDataMapper()
        surfaceMapper.SetInputData(surface)
        surfaceActor = vtk.vtkActor()
        surfaceActor.SetMapper(surfaceMapper)
        surfaceActor.GetProperty().SetOpacity(0.3)
        vmtkRenderer.Renderer.AddActor(surfaceActor)

    vmtkRenderer.Render()
Esempio n. 46
0
    def Execute(self):

        if self.Surface == None:
            self.PrintError('Error: No input surface.')

        if self.CheckNonManifold:
            self.PrintLog('NonManifold check.')
            nonManifoldChecker = vmtkNonManifoldSurfaceChecker()
            nonManifoldChecker.Surface = self.Surface
            nonManifoldChecker.PrintError = self.PrintError
            nonManifoldChecker.Execute()

            if (nonManifoldChecker.NumberOfNonManifoldEdges > 0):
                self.PrintLog(nonManifoldChecker.Report)
                return

        if not self.vmtkRenderer and self.SeedSelectorName in [
                'pickpoint', 'openprofiles'
        ]:
            self.vmtkRenderer = vmtkrenderer.vmtkRenderer()
            self.vmtkRenderer.Initialize()
            self.OwnRenderer = 1

        self.PrintLog('Cleaning surface.')
        surfaceCleaner = vtk.vtkCleanPolyData()
        surfaceCleaner.SetInputData(self.Surface)
        surfaceCleaner.Update()

        self.PrintLog('Triangulating surface.')
        surfaceTriangulator = vtk.vtkTriangleFilter()
        surfaceTriangulator.SetInputConnection(surfaceCleaner.GetOutputPort())
        surfaceTriangulator.PassLinesOff()
        surfaceTriangulator.PassVertsOff()
        surfaceTriangulator.Update()

        centerlineInputSurface = surfaceTriangulator.GetOutput()

        capCenterIds = None

        if self.SeedSelectorName in [
                'openprofiles', 'carotidprofiles', 'pickpoint', 'profileidlist'
        ]:
            self.PrintLog('Capping surface.')
            surfaceCapper = vtkvmtk.vtkvmtkCapPolyData()
            surfaceCapper.SetInputConnection(
                surfaceTriangulator.GetOutputPort())
            surfaceCapper.SetDisplacement(self.CapDisplacement)
            surfaceCapper.SetInPlaneDisplacement(self.CapDisplacement)
            surfaceCapper.Update()
            centerlineInputSurface = surfaceCapper.GetOutput()
            capCenterIds = surfaceCapper.GetCapCenterIds()

        if self.SeedSelector:
            pass
        elif self.SeedSelectorName:
            if self.SeedSelectorName == 'pickpoint':
                self.SeedSelector = vmtkPickPointSeedSelector()
                self.SeedSelector.vmtkRenderer = self.vmtkRenderer
                self.SeedSelector.Script = self
            elif self.SeedSelectorName == 'openprofiles':
                self.SeedSelector = vmtkOpenProfilesSeedSelector()
                self.SeedSelector.vmtkRenderer = self.vmtkRenderer
                self.SeedSelector.Script = self
                self.SeedSelector.SetSeedIds(surfaceCapper.GetCapCenterIds())
            elif self.SeedSelectorName == 'carotidprofiles':
                self.SeedSelector = vmtkCarotidProfilesSeedSelector()
                self.SeedSelector.SetSeedIds(surfaceCapper.GetCapCenterIds())
            elif self.SeedSelectorName == 'idlist':
                self.SeedSelector = vmtkIdListSeedSelector()
                self.SeedSelector.SourceIds = self.SourceIds
                self.SeedSelector.TargetIds = self.TargetIds
            elif self.SeedSelectorName == 'pointlist':
                self.SeedSelector = vmtkPointListSeedSelector()
                self.SeedSelector.SourcePoints = self.SourcePoints
                self.SeedSelector.TargetPoints = self.TargetPoints
            elif self.SeedSelectorName != 'profileidlist':
                self.PrintError(
                    "SeedSelectorName unknown (available: pickpoint, openprofiles, carotidprofiles, profileidlist, idlist, pointlist)"
                )
                return
        else:
            self.PrintError(
                'vmtkCenterlines error: either SeedSelector or SeedSelectorName must be specified'
            )
            return

        if self.SeedSelector:
            self.SeedSelector.SetSurface(centerlineInputSurface)
            self.SeedSelector.InputInfo = self.InputInfo
            self.SeedSelector.InputText = self.InputText
            self.SeedSelector.OutputText = self.OutputText
            self.SeedSelector.PrintError = self.PrintError
            self.SeedSelector.PrintLog = self.PrintLog
            self.SeedSelector.Execute()

            inletSeedIds = self.SeedSelector.GetSourceSeedIds()
            outletSeedIds = self.SeedSelector.GetTargetSeedIds()
        else:
            inletSeedIds = vtk.vtkIdList()
            outletSeedIds = vtk.vtkIdList()
            for id in self.SourceIds:
                inletSeedIds.InsertNextId(id)
            if self.TargetIds:
                for id in self.TargetIds:
                    outletSeedIds.InsertNextId(id)
            else:
                for i in range(capCenterIds.GetNumberOfIds()):
                    if i not in self.SourceIds:
                        outletSeedIds.InsertNextId(i)

        self.PrintLog('Computing centerlines.')
        self.InputInfo('Computing centerlines...')

        centerlineFilter = vtkvmtk.vtkvmtkPolyDataCenterlines()
        centerlineFilter.SetInputData(centerlineInputSurface)
        if self.SeedSelectorName in [
                'openprofiles', 'carotidprofiles', 'profileidlist'
        ]:
            centerlineFilter.SetCapCenterIds(capCenterIds)
        centerlineFilter.SetSourceSeedIds(inletSeedIds)
        centerlineFilter.SetTargetSeedIds(outletSeedIds)
        centerlineFilter.SetRadiusArrayName(self.RadiusArrayName)
        centerlineFilter.SetCostFunction(self.CostFunction)
        centerlineFilter.SetFlipNormals(self.FlipNormals)
        centerlineFilter.SetAppendEndPointsToCenterlines(self.AppendEndPoints)
        centerlineFilter.SetSimplifyVoronoi(self.SimplifyVoronoi)
        if self.DelaunayTessellation != None:
            centerlineFilter.GenerateDelaunayTessellationOff()
            centerlineFilter.SetDelaunayTessellation(self.DelaunayTessellation)
            centerlineFilter.SetDelaunayTolerance(self.DelaunayTolerance)
        if self.UseTetGen == 1:
            self.PrintLog('Running TetGen.')
            from vmtk import vmtkscripts
            surfaceToMesh = vmtkscripts.vmtkSurfaceToMesh()
            surfaceToMesh.Surface = centerlineInputSurface
            surfaceToMesh.Execute()
            tetgen = vmtkscripts.vmtkTetGen()
            tetgen.Mesh = surfaceToMesh.Mesh
            tetgen.PLC = 1
            tetgen.NoMerge = 1
            tetgen.Quality = 0
            if self.TetGenDetectInter == 1:
                tetgen.DetectInter = 1
                tetgen.NoMerge = 0
            tetgen.OutputSurfaceElements = 0
            tetgen.Execute()
            centerlineFilter.GenerateDelaunayTessellationOff()
            centerlineFilter.SetDelaunayTessellation(tetgen.Mesh)
        centerlineFilter.SetCenterlineResampling(self.Resampling)
        centerlineFilter.SetResamplingStepLength(self.ResamplingStepLength)
        centerlineFilter.Update()

        self.Centerlines = centerlineFilter.GetOutput()
        self.VoronoiDiagram = centerlineFilter.GetVoronoiDiagram()
        self.DelaunayTessellation = centerlineFilter.GetDelaunayTessellation()
        self.PoleIds = centerlineFilter.GetPoleIds()

        self.EikonalSolutionArrayName = centerlineFilter.GetEikonalSolutionArrayName(
        )
        self.EdgeArrayName = centerlineFilter.GetEdgeArrayName()
        self.EdgePCoordArrayName = centerlineFilter.GetEdgePCoordArrayName()
        self.CostFunctionArrayName = centerlineFilter.GetCostFunctionArrayName(
        )

        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
Esempio n. 47
0
    def BuildView(self):

        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)
        wholeExtent = self.Image.GetExtent()

        if self.Picker == None:
            self.Picker = vtk.vtkCellPicker()

        if self.PlaneWidgetX == None:
            self.PlaneWidgetX = vtkvmtk.vtkvmtkImagePlaneWidget()

        if self.PlaneWidgetY == None:
            self.PlaneWidgetY = vtkvmtk.vtkvmtkImagePlaneWidget()

        if self.PlaneWidgetZ == None:
            self.PlaneWidgetZ = vtkvmtk.vtkvmtkImagePlaneWidget()
            
        self.Picker.SetTolerance(0.005)

        self.PlaneWidgetX.SetResliceInterpolateToLinear()
        self.PlaneWidgetX.SetTextureInterpolate(self.TextureInterpolation)
        self.PlaneWidgetX.SetUseContinuousCursor(self.ContinuousCursor)
        self.PlaneWidgetX.SetInputData(self.Image)
        self.PlaneWidgetX.SetPlaneOrientationToXAxes()
        self.PlaneWidgetX.SetSliceIndex(wholeExtent[0])
        if self.vmtkRenderer.Annotations:
            self.PlaneWidgetX.DisplayTextOn()
        else:
            self.PlaneWidgetX.DisplayTextOff()
        self.PlaneWidgetX.SetPicker(self.Picker)
        self.PlaneWidgetX.KeyPressActivationOff()
        self.PlaneWidgetX.SetInteractor(self.vmtkRenderer.RenderWindowInteractor)
        if self.Margins:
            self.PlaneWidgetX.SetMarginSizeX(0.05)
            self.PlaneWidgetX.SetMarginSizeY(0.05)
        else:
            self.PlaneWidgetX.SetMarginSizeX(0.0)
            self.PlaneWidgetX.SetMarginSizeY(0.0)
        if self.WindowLevel[0] != 0.0:
            self.PlaneWidgetX.SetWindowLevel(self.WindowLevel[0],self.WindowLevel[1])
        self.PlaneWidgetX.On()

        self.PlaneWidgetY.SetResliceInterpolateToLinear()
        self.PlaneWidgetY.SetTextureInterpolate(self.TextureInterpolation)
        self.PlaneWidgetY.SetUseContinuousCursor(self.ContinuousCursor)
        self.PlaneWidgetY.SetInputData(self.Image)
        self.PlaneWidgetY.SetPlaneOrientationToYAxes()
        self.PlaneWidgetY.SetSliceIndex(wholeExtent[2])
        if self.vmtkRenderer.Annotations:
            self.PlaneWidgetY.DisplayTextOn()
        else:
            self.PlaneWidgetY.DisplayTextOff()
        self.PlaneWidgetY.SetPicker(self.Picker)
        self.PlaneWidgetY.KeyPressActivationOff()
        self.PlaneWidgetY.SetLookupTable(self.PlaneWidgetX.GetLookupTable())
        self.PlaneWidgetY.SetInteractor(self.vmtkRenderer.RenderWindowInteractor)
        if self.Margins:
            self.PlaneWidgetY.SetMarginSizeX(0.05)
            self.PlaneWidgetY.SetMarginSizeY(0.05)
        else:
            self.PlaneWidgetY.SetMarginSizeX(0.0)
            self.PlaneWidgetY.SetMarginSizeY(0.0)
        if self.WindowLevel[0] != 0.0:
            self.PlaneWidgetY.SetWindowLevel(self.WindowLevel[0],self.WindowLevel[1])
        self.PlaneWidgetY.On()

        self.PlaneWidgetZ.SetResliceInterpolateToLinear()
        self.PlaneWidgetZ.SetTextureInterpolate(self.TextureInterpolation)
        self.PlaneWidgetZ.SetUseContinuousCursor(self.ContinuousCursor)
        self.PlaneWidgetZ.SetInputData(self.Image)
        self.PlaneWidgetZ.SetPlaneOrientationToZAxes()
        self.PlaneWidgetZ.SetSliceIndex(wholeExtent[4])
        if self.vmtkRenderer.Annotations:
            self.PlaneWidgetZ.DisplayTextOn()
        else:
            self.PlaneWidgetZ.DisplayTextOff()
        self.PlaneWidgetZ.SetPicker(self.Picker)
        self.PlaneWidgetZ.KeyPressActivationOff()
        self.PlaneWidgetZ.SetLookupTable(self.PlaneWidgetX.GetLookupTable())
        self.PlaneWidgetZ.SetInteractor(self.vmtkRenderer.RenderWindowInteractor)
        if self.Margins:
            self.PlaneWidgetZ.SetMarginSizeX(0.05)
            self.PlaneWidgetZ.SetMarginSizeY(0.05)
        else:
            self.PlaneWidgetZ.SetMarginSizeX(0.0)
            self.PlaneWidgetZ.SetMarginSizeY(0.0)
        if self.WindowLevel[0] != 0.0:
            self.PlaneWidgetZ.SetWindowLevel(self.WindowLevel[0],self.WindowLevel[1])
        self.PlaneWidgetZ.On()

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

        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
Esempio n. 48
0
    def Execute(self):

        if (self._Surface == None):
            self.PrintError('vmtkPickPointSeedSelector Error: Surface not set.')
            return

        self._SourceSeedIds.Initialize()
        self._TargetSeedIds.Initialize()

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

        self.vmtkRenderer.RegisterScript(self.Script)

        glyphs = vtk.vtkGlyph3D()
        glyphSource = vtk.vtkSphereSource()
        glyphs.SetInputData(self.PickedSeeds)
        glyphs.SetSourceConnection(glyphSource.GetOutputPort())
        glyphs.SetScaleModeToDataScalingOff()
        glyphs.SetScaleFactor(self._Surface.GetLength()*0.01)
        glyphMapper = vtk.vtkPolyDataMapper()
        glyphMapper.SetInputConnection(glyphs.GetOutputPort())
        self.SeedActor = vtk.vtkActor()
        self.SeedActor.SetMapper(glyphMapper)
        self.SeedActor.GetProperty().SetColor(1.0,0.0,0.0)
        self.SeedActor.PickableOff()
        self.vmtkRenderer.Renderer.AddActor(self.SeedActor)

        ##self.vmtkRenderer.RenderWindowInteractor.AddObserver("KeyPressEvent", self.KeyPressed)
        self.vmtkRenderer.AddKeyBinding('u','Undo.',self.UndoCallback)
        self.vmtkRenderer.AddKeyBinding('space','Add points.',self.PickCallback)
        surfaceMapper = vtk.vtkPolyDataMapper()
        surfaceMapper.SetInputData(self._Surface)
        surfaceMapper.ScalarVisibilityOff()
        surfaceActor = vtk.vtkActor()
        surfaceActor.SetMapper(surfaceMapper)
        surfaceActor.GetProperty().SetOpacity(1.0)

        self.vmtkRenderer.Renderer.AddActor(surfaceActor)

        self.InputInfo('Please position the mouse and press space to add a point on the main body of the model, \'u\' to undo\n')

        any = 0
        while any == 0:
            self.InitializeSeeds()
            self.vmtkRenderer.Render()
            any = self.PickedSeedIds.GetNumberOfIds()
        self._SourceSeedIds.DeepCopy(self.PickedSeedIds)

        self.InputInfo('Please position the mouse and press space to add points at clip locations, \'u\' to undo\n')

        any = 0
        while any == 0:
            self.InitializeSeeds()
            self.vmtkRenderer.Render()
            any = self.PickedSeedIds.GetNumberOfIds()
        self._TargetSeedIds.DeepCopy(self.PickedSeedIds)

        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
Esempio n. 49
0
    def Execute(self):

        if not self.Mesh:
            self.PrintError('Error: No input mesh.')

        if not self.Centerlines:
            self.PrintError('Error: No input centerlines.')

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

        if self.Interactive:

            self.vmtkRenderer.RegisterScript(self)

            viewer = vmtkcenterlineviewer.vmtkCenterlineViewer()
            viewer.Centerlines = self.Centerlines
            viewer.CellDataArrayName = self.GroupIdsArrayName
            viewer.vmtkRenderer = self.vmtkRenderer
            viewer.InputText = self.InputText
            viewer.OutputText = self.OutputText
            viewer.PrintError = self.PrintError
            viewer.PringLog = self.PrintLog
            viewer.Display = 0
            viewer.Execute()

            groupIdsString = self.InputText("Please input groupIds to clip:\n",
                                            self.GroupIdsValidator)
            self.GroupIds = [
                int(groupId) for groupId in groupIdsString.split()
            ]

        clipper = vtkvmtk.vtkvmtkUnstructuredGridCenterlineGroupsClipper()
        clipper.SetInputData(self.Mesh)
        clipper.SetCenterlines(self.Centerlines)
        clipper.SetCenterlineGroupIdsArrayName(self.GroupIdsArrayName)
        clipper.SetGroupIdsArrayName(self.GroupIdsArrayName)
        clipper.SetCenterlineRadiusArrayName(self.RadiusArrayName)
        clipper.SetBlankingArrayName(self.BlankingArrayName)
        clipper.SetCutoffRadiusFactor(self.CutoffRadiusFactor)
        clipper.SetClipValue(self.ClipValue)
        clipper.SetUseRadiusInformation(self.UseRadiusInformation)
        if self.GroupIds:
            groupIds = vtk.vtkIdList()
            for groupId in self.GroupIds:
                groupIds.InsertNextId(groupId)
            clipper.SetCenterlineGroupIds(groupIds)
            clipper.ClipAllCenterlineGroupIdsOff()
        else:
            clipper.ClipAllCenterlineGroupIdsOn()
        if not self.InsideOut:
            clipper.GenerateClippedOutputOff()
        else:
            clipper.GenerateClippedOutputOn()
        clipper.Update()

        if not self.InsideOut:
            self.Mesh = clipper.GetOutput()
        else:
            self.Mesh = clipper.GetClippedOutputData()

        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
Esempio n. 50
0
    def Execute(self):

        if not self.Centerlines:
            self.PrintError('Error: No input centerlines.')
 
        if not self.GroupIdsArrayName:
            self.PrintError('Error: GroupIdsArrayName not specified.')
     
        if not self.vmtkRenderer:
            self.vmtkRenderer = vmtkrenderer.vmtkRenderer()
            self.vmtkRenderer.Initialize()
            self.OwnRenderer = 1

        self.vmtkRenderer.RegisterScript(self)
        
        groupIdsArray = self.Centerlines.GetCellData().GetArray(self.GroupIdsArrayName)
        groupIds = []
        for i in range(groupIdsArray.GetNumberOfTuples()):
            groupIds.append(int(groupIdsArray.GetComponent(i,0)))
        groupIds.sort()
        uniqueGroupIds = []
        for groupId in groupIds:
            if groupId not in uniqueGroupIds:
                uniqueGroupIds.append(groupId)
 
        labelMap = {}
        
        if not self.Labeling:
        
            viewer = vmtkcenterlineviewer.vmtkCenterlineViewer()
            viewer.Centerlines = self.Centerlines
            viewer.CellDataArrayName = self.GroupIdsArrayName
            viewer.vmtkRenderer = self.vmtkRenderer
            viewer.InputStream = self.InputStream
            viewer.OutputStream = self.OutputStream
            #viewer.InputText = self.InputText
            #viewer.OutputText = self.OutputText
            #viewer.PrintError = self.PrintError
            #viewer.PringLog = self.PrintLog
            viewer.Execute()
           
            ok = False
            while not ok:
                labelString = self.InputText("Please input labels for the following groupIds:\n%s\n" % " ".join([str(groupId) for groupId in uniqueGroupIds]),self.LabelValidator)
                labels = [int(label) for label in labelString.split()]
                if len(labels) == len(uniqueGroupIds):
                    ok = True

            for groupId in uniqueGroupIds:
                labelMap[groupId] = labels[uniqueGroupIds.index(groupId)]

        else:
 
            if len(self.Labeling) != 2 * len(uniqueGroupIds):
                self.PrintError('Error: incorrect labeling specified')

            for i in range(len(self.Labeling)/2):
                groupId = self.Labeling[2*i]
                labelId = self.Labeling[2*i+1]
                if not groupId in uniqueGroupIds:
                    self.PrintError('Error: groupId %d does not exist' % groupId)
                labelMap[groupId] = labelId
 
        labelIdsArray = vtk.vtkIntArray()
        labelIdsArray.SetName(self.LabelIdsArrayName)
        labelIdsArray.SetNumberOfComponents(1)
        labelIdsArray.SetNumberOfTuples(self.Centerlines.GetNumberOfCells())

        groupIdsArray = self.Centerlines.GetCellData().GetArray(self.GroupIdsArrayName)
        
        for i in range(groupIdsArray.GetNumberOfTuples()):
            groupId = int(groupIdsArray.GetComponent(i,0))
            labelIdsArray.SetComponent(i,0,labelMap[groupId])
        
        self.Centerlines.GetCellData().AddArray(labelIdsArray)

        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
Esempio n. 51
0
    def Execute(self):

        if (self._Surface == None):
            self.PrintError('vmtkOpenProfilesSeedSelector Error: Surface not set.')
            return
        
        if (self._SeedIds == None):
            self.PrintError('vmtkOpenProfilesSeedSelector Error: SeedIds not set.')
            return

        self._SourceSeedIds.Initialize()
        self._TargetSeedIds.Initialize()

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

        self.vmtkRenderer.RegisterScript(self.Script) 

        seedPoints = vtk.vtkPoints()
        for i in range(self._SeedIds.GetNumberOfIds()):
            seedPoints.InsertNextPoint(self._Surface.GetPoint(self._SeedIds.GetId(i)))
        seedPolyData = vtk.vtkPolyData()
        seedPolyData.SetPoints(seedPoints)
        labelsMapper = vtk.vtkLabeledDataMapper();
        labelsMapper.SetInputData(seedPolyData)
        labelsMapper.SetLabelModeToLabelIds()
        labelsActor = vtk.vtkActor2D()
        labelsActor.SetMapper(labelsMapper)

        self.vmtkRenderer.Renderer.AddActor(labelsActor)

        surfaceMapper = vtk.vtkPolyDataMapper()
        surfaceMapper.SetInputData(self._Surface)
        surfaceMapper.ScalarVisibilityOff()
        surfaceActor = vtk.vtkActor()
        surfaceActor.SetMapper(surfaceMapper)
        surfaceActor.GetProperty().SetOpacity(0.25)

        self.vmtkRenderer.Renderer.AddActor(surfaceActor)

        self.vmtkRenderer.Render()
        
        seedIdString = self.InputText("Please input list of inlet profile ids: ")
        separator = ' '
        if seedIdString.find(',') != -1:
            separator = ','
        seedIdList = seedIdString.split(separator)
        for seedIdString in seedIdList:
            self._SourceSeedIds.InsertNextId(int(seedIdString.strip()))

        seedIdString = self.InputText("Please input list of outlet profile ids (leave empty for all available profiles): ")
        if seedIdString.strip() == '':
            self.InputInfo("Selected outlets: ")
            for i in range(seedPoints.GetNumberOfPoints()):
                if self._SourceSeedIds.IsId(i) == -1:
                    self._TargetSeedIds.InsertNextId(i)
                    self.InputInfo("%d " % i)
            self.InputInfo("\n")
        else:
            seedIdList = seedIdString.split(separator)
            for seedIdString in seedIdList:
                self._TargetSeedIds.InsertNextId(int(seedIdString.strip()))
        
        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
Esempio n. 52
0
    def BuildView(self):

        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)
        wholeExtent = self.Image.GetExtent()

        if self.Picker == None:
            self.Picker = vtk.vtkCellPicker()

        if self.PlaneWidgetX == None:
            self.PlaneWidgetX = vtkvmtk.vtkvmtkImagePlaneWidget()

        if self.PlaneWidgetY == None:
            self.PlaneWidgetY = vtkvmtk.vtkvmtkImagePlaneWidget()

        if self.PlaneWidgetZ == None:
            self.PlaneWidgetZ = vtkvmtk.vtkvmtkImagePlaneWidget()

        self.Picker.SetTolerance(0.005)

        self.PlaneWidgetX.SetResliceInterpolateToLinear()
        self.PlaneWidgetX.SetTextureInterpolate(self.TextureInterpolation)
        self.PlaneWidgetX.SetUseContinuousCursor(self.ContinuousCursor)
        self.PlaneWidgetX.SetInputData(self.Image)
        self.PlaneWidgetX.SetPlaneOrientationToXAxes()
        self.PlaneWidgetX.SetSliceIndex(wholeExtent[0])
        if self.vmtkRenderer.Annotations:
            self.PlaneWidgetX.DisplayTextOn()
        else:
            self.PlaneWidgetX.DisplayTextOff()
        self.PlaneWidgetX.SetPicker(self.Picker)
        self.PlaneWidgetX.KeyPressActivationOff()
        self.PlaneWidgetX.SetInteractor(
            self.vmtkRenderer.RenderWindowInteractor)
        if self.Margins:
            self.PlaneWidgetX.SetMarginSizeX(0.05)
            self.PlaneWidgetX.SetMarginSizeY(0.05)
        else:
            self.PlaneWidgetX.SetMarginSizeX(0.0)
            self.PlaneWidgetX.SetMarginSizeY(0.0)
        if self.WindowLevel[0] != 0.0:
            self.PlaneWidgetX.SetWindowLevel(self.WindowLevel[0],
                                             self.WindowLevel[1])
        self.PlaneWidgetX.On()

        self.PlaneWidgetY.SetResliceInterpolateToLinear()
        self.PlaneWidgetY.SetTextureInterpolate(self.TextureInterpolation)
        self.PlaneWidgetY.SetUseContinuousCursor(self.ContinuousCursor)
        self.PlaneWidgetY.SetInputData(self.Image)
        self.PlaneWidgetY.SetPlaneOrientationToYAxes()
        self.PlaneWidgetY.SetSliceIndex(wholeExtent[2])
        if self.vmtkRenderer.Annotations:
            self.PlaneWidgetY.DisplayTextOn()
        else:
            self.PlaneWidgetY.DisplayTextOff()
        self.PlaneWidgetY.SetPicker(self.Picker)
        self.PlaneWidgetY.KeyPressActivationOff()
        self.PlaneWidgetY.SetLookupTable(self.PlaneWidgetX.GetLookupTable())
        self.PlaneWidgetY.SetInteractor(
            self.vmtkRenderer.RenderWindowInteractor)
        if self.Margins:
            self.PlaneWidgetY.SetMarginSizeX(0.05)
            self.PlaneWidgetY.SetMarginSizeY(0.05)
        else:
            self.PlaneWidgetY.SetMarginSizeX(0.0)
            self.PlaneWidgetY.SetMarginSizeY(0.0)
        if self.WindowLevel[0] != 0.0:
            self.PlaneWidgetY.SetWindowLevel(self.WindowLevel[0],
                                             self.WindowLevel[1])
        self.PlaneWidgetY.On()

        self.PlaneWidgetZ.SetResliceInterpolateToLinear()
        self.PlaneWidgetZ.SetTextureInterpolate(self.TextureInterpolation)
        self.PlaneWidgetZ.SetUseContinuousCursor(self.ContinuousCursor)
        self.PlaneWidgetZ.SetInputData(self.Image)
        self.PlaneWidgetZ.SetPlaneOrientationToZAxes()
        self.PlaneWidgetZ.SetSliceIndex(wholeExtent[4])
        if self.vmtkRenderer.Annotations:
            self.PlaneWidgetZ.DisplayTextOn()
        else:
            self.PlaneWidgetZ.DisplayTextOff()
        self.PlaneWidgetZ.SetPicker(self.Picker)
        self.PlaneWidgetZ.KeyPressActivationOff()
        self.PlaneWidgetZ.SetLookupTable(self.PlaneWidgetX.GetLookupTable())
        self.PlaneWidgetZ.SetInteractor(
            self.vmtkRenderer.RenderWindowInteractor)
        if self.Margins:
            self.PlaneWidgetZ.SetMarginSizeX(0.05)
            self.PlaneWidgetZ.SetMarginSizeY(0.05)
        else:
            self.PlaneWidgetZ.SetMarginSizeX(0.0)
            self.PlaneWidgetZ.SetMarginSizeY(0.0)
        if self.WindowLevel[0] != 0.0:
            self.PlaneWidgetZ.SetWindowLevel(self.WindowLevel[0],
                                             self.WindowLevel[1])
        self.PlaneWidgetZ.On()

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

        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
Esempio n. 53
0
    def Execute(self):
        # Error handling
        if self.Surface == None:
            self.PrintError(
                'Error: no input surface was supplied, ensure file exists, ensure correct environment'
            )

        # Allocate a renderer and label own renderer in use to prevent multiple renderers from being used
        if not self.vmtkRenderer:
            self.vmtkRenderer = vmtkrenderer.vmtkRenderer()
            self.vmtkRenderer.Initialize()
            self.OwnRenderer = 1

        self.vmtkRenderer.RegisterScript(self)

        # Render and build view of the input surface
        self.SurfaceViewer = vmtkscripts.vmtkSurfaceViewer()
        self.SurfaceViewer.vmtkRenderer = self.vmtkRenderer

        self.SurfaceViewer.Surface = self.Surface
        self.SurfaceViewer.BuildView()

        # Test question in render window
        #queryStr = 'Is this the question you wanted to see? '
        #inputStr = self.YesNoInput(queryStr, self.YesNoValidator)

        # Surface smoothing, try defaults first then take user input if not adequate
        acceptableResult = 0
        response = 0
        while acceptableResult == 0:
            if response == 0:
                self.SurfaceSmoothing = vmtkscripts.vmtkSurfaceSmoothing()
                self.SurfaceSmoothing.NumberOfIterations = 100
                self.PassBand = 0.001
            elif response == 1:
                self.SurfaceViewer.Surface = self.Surface
                self.SurfaceViewer.BuildView()
                self.SurfaceSmoothing = vmtkscripts.vmtkSurfaceSmoothing()

                #Take passband from user
                queryStr = 'Please enter value for pass band (0.001 - 0.1): '
                self.SurfaceSmoothing.PassBand = float(
                    self.InputText(queryStr, self.PassBandValidator))

                #Take number of iterations from user
                queryStr = 'Please enter number of iterations (1-999): '
                self.SurfaceSmoothing.NumberOfIterations = int(
                    self.InputText(queryStr, self.IterationValidator))

            self.SurfaceSmoothing.Surface = self.Surface
            self.SurfaceSmoothing.Execute()
            self.SurfaceViewer.Surface = self.SurfaceSmoothing.Surface
            self.SurfaceViewer.BuildView()

            # Accept or reject result of smoothing surface
            queryStr = 'Accept result of smoothing?(y/n): '
            if (self.YesNoInput(queryStr, self.YesNoValidator)):
                acceptableResult = 1
                self.Surface = self.SurfaceSmoothing.Surface
            else:
                acceptableResult = 0
                response = 1

        # Surface clipping
        # The only issue here is that 2 renderers get built 2/2 the structure of vmtkSurfaceClipper
        # Issue to be revisited later
        acceptableResult = 0
        while acceptableResult == 0:

            self.SurfaceClipper = vmtkscripts.vmtkSurfaceClipper()
            self.SurfaceClipper.Surface = self.Surface
            self.SurfaceClipper.Execute()

            self.SurfaceViewer.Surface = self.SurfaceClipper.Surface
            self.SurfaceViewer.BuildView()

            queryStr = 'Accept result of clipping?(y/n): '
            if (self.YesNoInput(queryStr, self.YesNoValidator)):
                acceptableResult = 1
                self.Surface = self.SurfaceClipper.Surface
            else:
                acceptableResult = 0

            self.SurfaceViewer.Surface = self.SurfaceClipper.Surface
            self.SurfaceViewer.BuildView()

        # Create centerlines based off the acceptable clipped surface
        centerliner = vmtkscripts.vmtkCenterlines()
        centerliner.Surface = self.Surface
        centerliner.SeedSelectorName = 'openprofiles'
        centerliner.Execute()

        self.Centerlines = centerliner.Centerlines

        # Add flow extensions until user has acceptable result
        acceptableResult = 0
        response = 0
        while (acceptableResult == 0):

            self.FlowExtensions = vmtkscripts.vmtkFlowExtensions()
            self.FlowExtensions.Surface = self.Surface
            self.FlowExtensions.Centerlines = self.Centerlines
            self.FlowExtensions.AdaptiveExtensionLength = 1
            #self.FlowExtensions.CenterlineNormalEstimationDistanceRatio = 1
            self.FlowExtensions.Interactive = 0

            # Take user extension ratio if response to acceptable outcome question
            # Default extension ratio is 10
            if (response == 0):
                self.FlowExtensions.ExtensionRatio = 10
            elif (response == 1):
                #Take extension ratio from user
                queryStr = 'Please enter value for pass band; default is 20 (min/max 1-50): '
                self.FlowExtensions.ExtensionRatio = float(
                    self.InputText(queryStr, self.ExtensionRatioValidator))

            self.FlowExtensions.Execute()

            self.SurfaceViewer.Surface = self.FlowExtensions.Surface
            self.SurfaceViewer.BuildView()

            queryStr = 'Accept flow extensions?(y/n): '
            if (self.YesNoInput(queryStr, self.YesNoValidator)):
                acceptableResult = 1
                self.Surface = self.FlowExtensions.Surface
            else:
                acceptableResult = 0
                response = 1

        # self.SurfaceViewer.BuildView()

        # Deallocate renderer
        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
Esempio n. 54
0
    def Execute(self):

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

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

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

        surfaceViewer = vmtksurfaceviewer.vmtkSurfaceViewer()
        surfaceViewer.vmtkRenderer = self.vmtkRenderer
        surfaceViewer.Surface = self.InputTraces
        surfaceViewer.ArrayName = self.ArrayName
        surfaceViewer.ColorMap = self.ColorMap
        surfaceViewer.NumberOfColors = self.NumberOfColors
        surfaceViewer.Execute()

        if self.ColorMap == 'grayscale':
            lut = surfaceViewer.Actor.GetMapper().GetLookupTable()
            lut.SetNumberOfTableValues(self.NumberOfColors)
            lut.SetValueRange(0.0, 1.0)
            lut.SetSaturationRange(0.0, 0.0)
            lut.Build()
            surfaceViewer.Actor.GetMapper().SetLookupTable(lut)

        if self.ColorMap == 'rainbow':
            lut = surfaceViewer.Actor.GetMapper().GetLookupTable()
            lut.SetHueRange(0.666667, 0.0)
            lut.SetSaturationRange(0.75, 0.75)
            lut.SetValueRange(1.0, 1.0)
            lut.SetAlphaRange(1.0, 1.0)
            lut.SetNumberOfColors(self.NumberOfColors)
            lut.Build()
            surfaceViewer.Actor.GetMapper().SetLookupTable(lut)

        if self.ColorMap == 'blackbody':
            lut = surfaceViewer.Actor.GetMapper().GetLookupTable()
            lut.SetNumberOfTableValues(self.NumberOfColors)
            colorTransferFunction = vtk.vtkColorTransferFunction()
            colorTransferFunction.SetColorSpaceToRGB()
            colorTransferFunction.AddRGBPoint(0, 0.0, 0.0, 0.0)
            colorTransferFunction.AddRGBPoint(0.4, 0.901961, 0.0, 0.0)
            colorTransferFunction.AddRGBPoint(0.8, 0.901961, 0.901961, 0.0)
            colorTransferFunction.AddRGBPoint(1.0, 1.0, 1.0, 1.0)
            for ii, ss in enumerate([
                    float(xx) / float(self.NumberOfColors)
                    for xx in range(self.NumberOfColors)
            ]):
                cc = colorTransferFunction.GetColor(ss)
                lut.SetTableValue(ii, cc[0], cc[1], cc[2], 1.0)
            lut.Build()
            surfaceViewer.Actor.GetMapper().SetLookupTable(lut)

        if self.ColorMap == 'cooltowarm':
            lut = surfaceViewer.Actor.GetMapper().GetLookupTable()
            lut.SetNumberOfTableValues(self.NumberOfColors)
            colorTransferFunction = vtk.vtkColorTransferFunction()
            colorTransferFunction.SetColorSpaceToDiverging()
            colorTransferFunction.AddRGBPoint(0, 0.231373, 0.298039, 0.752941)
            colorTransferFunction.AddRGBPoint(0.5, 0.865003, 0.865003,
                                              0.865003)
            colorTransferFunction.AddRGBPoint(1.0, 0.705882, 0.0156863,
                                              0.14902)
            for ii, ss in enumerate([
                    float(xx) / float(self.NumberOfColors)
                    for xx in range(self.NumberOfColors)
            ]):
                cc = colorTransferFunction.GetColor(ss)
                lut.SetTableValue(ii, cc[0], cc[1], cc[2], 1.0)
            lut.Build()
            surfaceViewer.Actor.GetMapper().SetLookupTable(lut)

        if (self.Legend == 1):
            self.ScalarBarActor = vtk.vtkScalarBarActor()
            self.ScalarBarActor.SetLookupTable(
                surfaceViewer.Actor.GetMapper().GetLookupTable())
            self.ScalarBarActor.GetLabelTextProperty().ItalicOff()
            self.ScalarBarActor.GetLabelTextProperty().BoldOff()
            self.ScalarBarActor.GetLabelTextProperty().ShadowOff()
            self.ScalarBarActor.SetWidth(0.1)
            self.ScalarBarActor.SetHeight(0.6)
            self.ScalarBarActor.SetNumberOfLabels(4)
            self.ScalarBarActor.SetTitle(self.ArrayName + " [" +
                                         self.ArrayUnit + "]")
            self.ScalarBarActor.SetLabelFormat('%.2f')
            self.vmtkRenderer.Renderer.AddActor(self.ScalarBarActor)

        self.Traces = vtk.vtkPolyData()
        self.Traces.DeepCopy(self.InputTraces)
        self.Traces.GetPointData().SetActiveScalars("IntegrationTime")
        timeRange = self.Traces.GetPointData().GetScalars().GetRange(0)
        currentCycle = 0
        minTime = self.MinTime
        currentTime = self.TimeStep
        maxTime = self.MaxTime
        if (self.ArrayMax == None and self.ArrayName == "Velocity"):
            self.ArrayMax = round(
                self.Traces.GetPointData().GetArray('Speed').GetRange()[1], 0)

        if self.Method is 'particles':
            particleTime = minTime
            imageNumber = 0
            while particleTime <= maxTime:
                contour = vtk.vtkContourFilter()
                contour.SetInputData(self.Traces)
                i = 0
                while i <= currentCycle:
                    time = minTime + currentTime + (maxTime - minTime) * i
                    if time < timeRange[0] or time > timeRange[1]:
                        pass
                    else:
                        contour.SetValue(i, time)
                    i += 1

                contour.Update()
                surfaceViewer.vmtkRenderer = self.vmtkRenderer
                surfaceViewer.Actor.GetProperty().SetPointSize(self.PointSize)
                vtk.vtkPolyDataMapper.SafeDownCast(
                    surfaceViewer.Actor.GetMapper()).SetInputConnection(
                        contour.GetOutputPort())

                surfaceViewer.Actor.GetMapper().GetLookupTable(
                ).SetVectorModeToMagnitude()
                surfaceViewer.Actor.GetMapper(
                ).SetScalarModeToUsePointFieldData()
                surfaceViewer.Actor.GetMapper().SelectColorArray(
                    self.ArrayName)
                surfaceViewer.Actor.GetMapper().SetScalarRange(
                    [0.0, self.ArrayMax])

                surfaceViewer.vmtkRenderer.RenderWindow.Render()
                if self.WithScreenshots:
                    self.Screenshot(surfaceViewer, imageNumber)

                particleTime += self.TimeStep
                currentTime += self.TimeStep
                imageNumber += 1

        elif self.Method is 'streaklines':
            particleTime = minTime
            imageNumber = 0
            while particleTime <= maxTime:
                clip1 = vtk.vtkClipPolyData()
                clip1.SetInputData(self.Traces)
                clip1.GenerateClipScalarsOff()
                clip1.InsideOutOn()
                clip2 = vtk.vtkClipPolyData()
                clip2.SetInputConnection(clip1.GetOutputPort())
                clip2.GenerateClipScalarsOff()
                clip2.InsideOutOff()

                cyclesPerRange = (int(
                    (timeRange[1] - timeRange[0]) / (maxTime - minTime))) + 1
                cycle = currentCycle % cyclesPerRange
                time = minTime + currentTime + (maxTime - minTime) * cycle
                streakLineTimeLength = self.StreakLineTimeLength

                clip1.SetValue(time)
                clip2.SetValue(time - streakLineTimeLength)
                clip2.Update()

                surfaceViewer.Actor.GetProperty().SetLineWidth(self.LineWidth)
                vtk.vtkPolyDataMapper.SafeDownCast(
                    surfaceViewer.Actor.GetMapper()).SetInputConnection(
                        clip2.GetOutputPort())

                surfaceViewer.Actor.GetMapper().GetLookupTable(
                ).SetVectorModeToMagnitude()
                surfaceViewer.Actor.GetMapper(
                ).SetScalarModeToUsePointFieldData()
                surfaceViewer.Actor.GetMapper().SelectColorArray(
                    self.ArrayName)
                surfaceViewer.Actor.GetMapper().SetScalarRange(
                    [0.0, self.ArrayMax])

                surfaceViewer.vmtkRenderer = self.vmtkRenderer
                surfaceViewer.vmtkRenderer.RenderWindow.Render()
                if self.WithScreenshots:
                    self.Screenshot(surfaceViewer, imageNumber)

                particleTime += self.TimeStep
                currentTime += self.TimeStep
                imageNumber += 1
        else:
            self.PrintError('Error: pathlineanimator  method not supported.')
Esempio n. 55
0
    def Execute(self):

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

        self.Clipper = vtk.vtkClipPolyData()
        self.Clipper.SetInputData(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.SetInputData(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.SetInputData(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()
            if self.WidgetType == "box":
                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.SetInputData(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.SetInputData(self.Surface)
            cleaner.Update()
            self.Surface = cleaner.GetOutput()

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

            cleaner = vtk.vtkCleanPolyData()
            cleaner.SetInputData(self.CutLines)
            cleaner.Update()
            stripper = vtk.vtkStripper()
            stripper.SetInputConnection(cleaner.GetOutputPort())
            stripper.Update()
            self.CutLines = stripper.GetOutput()
Esempio n. 56
0
    def Execute(self):

        if self.Centerlines == None:
            self.PrintError('Error: No input centerlines.')

        if self.ReferenceSystems == None:
            self.PrintError('Error: No input reference systems.')

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

        if self.Interactive:

            self.vmtkRenderer.RegisterScript(self)

            viewer = vmtkcenterlineviewer.vmtkCenterlineViewer()
            viewer.Centerlines = self.Centerlines
            viewer.CellDataArrayName = self.GroupIdsArrayName
            viewer.vmtkRenderer = self.vmtkRenderer
            viewer.InputText = self.InputText
            viewer.OutputText = self.OutputText
            viewer.PrintError = self.PrintError
            viewer.PringLog = self.PrintLog
            viewer.Display = 0
            viewer.Execute()

            groupIdString = self.InputText(
                "Please input the reference groupId:\n", self.GroupIdValidator)
            self.ReferenceGroupId = int(groupIdString)

        offsetFilter = vtkvmtk.vtkvmtkCenterlineReferenceSystemAttributesOffset(
        )
        offsetFilter.SetInputData(self.Centerlines)
        offsetFilter.SetReferenceSystems(self.ReferenceSystems)
        offsetFilter.SetAbscissasArrayName(self.AbscissasArrayName)
        offsetFilter.SetNormalsArrayName(self.NormalsArrayName)
        if not self.ReplaceAttributes:
            offsetFilter.SetOffsetAbscissasArrayName(
                self.OffsetAbscissasArrayName)
            offsetFilter.SetOffsetNormalsArrayName(self.OffsetNormalsArrayName)
        else:
            offsetFilter.SetOffsetAbscissasArrayName(self.AbscissasArrayName)
            offsetFilter.SetOffsetNormalsArrayName(self.NormalsArrayName)
        offsetFilter.SetGroupIdsArrayName(self.GroupIdsArrayName)
        offsetFilter.SetCenterlineIdsArrayName(self.CenterlineIdsArrayName)
        offsetFilter.SetReferenceSystemsNormalArrayName(
            self.ReferenceSystemsNormalArrayName)
        offsetFilter.SetReferenceSystemsGroupIdsArrayName(
            self.GroupIdsArrayName)
        offsetFilter.SetReferenceGroupId(self.ReferenceGroupId)
        offsetFilter.Update()

        self.Centerlines = offsetFilter.GetOutput()

        if self.ReferenceGroupId == -1:
            self.ReferenceGroupId = offsetFilter.GetReferenceGroupId()

        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
Esempio n. 57
0
    def Execute(self):

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

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

        self.SeedSelector = vmtkPickPointSeedSelector()
        self.SeedSelector.vmtkRenderer = self.vmtkRenderer
        self.SeedSelector.Script = self

        self.SeedSelector.SetSurface(self.Surface)
        self.SeedSelector.InputInfo = self.InputInfo
        self.SeedSelector.InputText = self.InputText
        self.SeedSelector.OutputText = self.OutputText
        self.SeedSelector.PrintError = self.PrintError
        self.SeedSelector.PrintLog = self.PrintLog
        self.SeedSelector.Execute()

        mainBodySeedIds = self.SeedSelector.GetSourceSeedIds()
        mainBodySeedId = mainBodySeedIds.GetId(0)
        mainBodyPoint = self.Surface.GetPoint(mainBodySeedId)

        clipSeedIds = self.SeedSelector.GetTargetSeedIds()

        surfaceCleaner = vtk.vtkCleanPolyData()
        surfaceCleaner.SetInputData(self.Surface)
        surfaceCleaner.Update()

        surfaceTriangulator = vtk.vtkTriangleFilter()
        surfaceTriangulator.SetInputConnection(surfaceCleaner.GetOutputPort())
        surfaceTriangulator.PassLinesOff()
        surfaceTriangulator.PassVertsOff()
        surfaceTriangulator.Update()

        clippedSurface = surfaceTriangulator.GetOutput()

        for i in range(clipSeedIds.GetNumberOfIds()):

            seedId = clipSeedIds.GetId(i)

            locator = vtk.vtkPointLocator()
            locator.SetDataSet(clippedSurface)
            locator.BuildLocator()

            seedPoint = self.Surface.GetPoint(seedId)
            seedPointId = locator.FindClosestPoint(seedPoint)

            planeEstimator = vtkvmtk.vtkvmtkPolyDataNormalPlaneEstimator()
            planeEstimator.SetInputData(clippedSurface)
            planeEstimator.SetOriginPointId(seedPointId)
            planeEstimator.Update()

            plane = vtk.vtkPlane()
            plane.SetOrigin(planeEstimator.GetOrigin())
            plane.SetNormal(planeEstimator.GetNormal())

            seamFilter = vtkvmtk.vtkvmtkTopologicalSeamFilter()
            seamFilter.SetInputData(clippedSurface)
            seamFilter.SetClosestPoint(seedPoint)
            seamFilter.SetSeamScalarsArrayName("SeamScalars")
            seamFilter.SetSeamFunction(plane)

            clipper = vtk.vtkClipPolyData()
            clipper.SetInputConnection(seamFilter.GetOutputPort())
            clipper.GenerateClipScalarsOff()
            clipper.GenerateClippedOutputOn()

            connectivity = vtk.vtkPolyDataConnectivityFilter()
            connectivity.SetInputConnection(clipper.GetOutputPort())
            connectivity.SetExtractionModeToClosestPointRegion()
            connectivity.SetClosestPoint(mainBodyPoint)

            surfaceCleaner = vtk.vtkCleanPolyData()
            surfaceCleaner.SetInputConnection(connectivity.GetOutputPort())
            surfaceCleaner.Update()

            surfaceTriangulator = vtk.vtkTriangleFilter()
            surfaceTriangulator.SetInputConnection(
                surfaceCleaner.GetOutputPort())
            surfaceTriangulator.PassLinesOff()
            surfaceTriangulator.PassVertsOff()
            surfaceTriangulator.Update()

            #clippedSurface = vtk.vtkPolyData()
            #clippedSurface.DeepCopy(surfaceTriangulator.GetOutput())
            clippedSurface = surfaceTriangulator.GetOutput()

        self.Surface = clippedSurface

        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()
Esempio n. 58
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. 59
0
    def Execute(self):

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

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

        #Save the centerlines
        previousCenterlines = self.Centerlines
        
        cleaner = vtk.vtkCleanPolyData()
        cleaner.SetInputData(self.Centerlines)
        cleaner.Update()
        self.Centerlines = cleaner.GetOutput()

        if self.Tolerance == -1:
            self.Tolerance = 0.000001*self.Mesh.GetLength()

        if self.RadiusArrayName != '':
            self.RadiusArray = self.Centerlines.GetPointData().GetArray(self.RadiusArrayName)
            if self.RadiusArray == None:
                self.PrintError('Error : could not find radius array')

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

        meshMapper = vtk.vtkDataSetMapper()
        meshMapper.SetInputData(self.Mesh)
        meshMapper.ScalarVisibilityOff()
        self.MeshActor = vtk.vtkActor()
        self.MeshActor.SetMapper(meshMapper)
        self.MeshActor.GetProperty().SetOpacity(0.25)
        self.MeshActor.PickableOff()
        self.vmtkRenderer.Renderer.AddActor(self.MeshActor)

        centerlinesMapper = vtk.vtkDataSetMapper()
        centerlinesMapper.SetInputData(self.Centerlines)
        centerlinesMapper.ScalarVisibilityOff()
        self.CenterlinesActor = vtk.vtkActor()
        self.CenterlinesActor.SetMapper(centerlinesMapper)
        self.vmtkRenderer.Renderer.AddActor(self.CenterlinesActor)

        glyphs = vtk.vtkGlyph3D()
        glyphSource = vtk.vtkSphereSource()
        glyphSource.SetRadius(1)
        glyphs.SetInputData(self.Spheres)
        glyphs.SetSourceConnection(glyphSource.GetOutputPort())
        glyphs.SetScaleModeToScaleByScalar()
        glyphs.SetScaleFactor(1.)
        glyphMapper = vtk.vtkPolyDataMapper()
        glyphMapper.SetInputConnection(glyphs.GetOutput())
        glyphMapper.ScalarVisibilityOff()
        self.SpheresActor = vtk.vtkActor()
        self.SpheresActor.SetMapper(glyphMapper)
        self.SpheresActor.GetProperty().SetColor(1.0,0.0,0.0)
        self.SpheresActor.GetProperty().SetOpacity(0.25)
        self.SpheresActor.PickableOff()
        self.vmtkRenderer.Renderer.AddActor(self.SpheresActor)

        self.InterpolatedGlyphs = vtk.vtkGlyph3D()
        interpolatedGlyphSource = vtk.vtkSphereSource()
        interpolatedGlyphSource.SetRadius(1)
        self.InterpolatedGlyphs.SetInputData(self.Centerlines)
        self.InterpolatedGlyphs.SetSourceConnection(interpolatedGlyphSource.GetOutputPort())
        #scaling is off for now
        self.InterpolatedGlyphs.SetScaleModeToDataScalingOff()
        self.InterpolatedGlyphs.SetScaleFactor(0.)
        interpolatedGlyphMapper = vtk.vtkPolyDataMapper()
        interpolatedGlyphMapper.SetInputConnection(self.InterpolatedGlyphs.GetOutputPort())
        interpolatedGlyphMapper.ScalarVisibilityOff()
        self.InterpolatedSpheresActor = vtk.vtkActor()
        self.InterpolatedSpheresActor.SetMapper(interpolatedGlyphMapper)
        self.InterpolatedSpheresActor.GetProperty().SetColor(0.0,1.0,0.0)
        self.InterpolatedSpheresActor.GetProperty().SetOpacity(0.25)
        self.InterpolatedSpheresActor.PickableOff()
        self.InterpolatedSpheresActor.VisibilityOff()
        self.vmtkRenderer.Renderer.AddActor(self.InterpolatedSpheresActor)

        polyBallMapper = vtk.vtkPolyDataMapper()
        polyBallMapper.ScalarVisibilityOff()
        self.PolyBallActor = vtk.vtkActor()
        self.PolyBallActor.SetMapper(polyBallMapper)
        self.PolyBallActor.GetProperty().SetColor(0.0,1.0,0.0)
        self.PolyBallActor.GetProperty().SetOpacity(0.25)
        self.PolyBallActor.PickableOff()
        self.PolyBallActor.VisibilityOff()
        self.vmtkRenderer.Renderer.AddActor(self.PolyBallActor)

        
        self.SphereWidget = vtk.vtkSphereWidget()
        self.SphereWidget.TranslationOff()
        self.SphereWidget.SetInteractor(self.vmtkRenderer.RenderWindowInteractor)
        self.SphereWidget.AddObserver("InteractionEvent", self.SphereCallback)
                
        self.Clipper = vtk.vtkClipDataSet()
        self.Clipper.SetInputData(self.Mesh)
        self.Clipper.SetInsideOut(self.InsideOut)
        self.Clipper.GenerateClippedOutputOn()
        
        #self.LineClipper = vtkvmtk.vtkvmtkClipDataSetLine()
        #self.LineClipper.SetInputData(self.Mesh)
        #self.LineClipper.SetInsideOut(self.InsideOut)
        #self.LineClipper.GenerateClippedOutputOn()
        
        self.InitializeSpheres()
        
        self.PreviewMesh = self.Mesh
        
        self.Display()
        
        self.PolyBallActor.VisibilityOff()
        self.ClipMesh()
        
        
        if self.ClippedMesh == None:
            #return an empty mesh
            self.ClippedMesh = vtk.vtkUnstructuredGrid()
        elif self.IncludeSurfaceCells:
            #Create the surface cells
            self.PreviewMesh = self.CreateSurfaceCells(self.PreviewMesh)
            self.ClippedMesh = self.CreateSurfaceCells(self.ClippedMesh)
        
        self.Mesh = self.PreviewMesh
        
        if self.OwnRenderer:
            self.vmtkRenderer.Deallocate()

        #Restore the centerlines
        self.Centerlines = previousCenterlines