def model(self,cmd): import qt import slicer p = urlparse.urlparse(cmd) q = urlparse.parse_qs(p.query) try: ID = str(q['ID'][0].strip()) except KeyError: ID = 'vtkMRMLModelNode4' import slicer node = slicer.util.getNode(ID) objWriter = vtk.vtkOBJWriter() #objWriter.SetWriteToMemory(True) objWriter.SetWriteToMemory(False) objWriter.SetFileName('C:/Users/Frankie/PerkWorkFiles/' + ID +'.obj') if (node.GetClassName() == "vtkMRMLTransformDisplayNode"): polyData = vtk.vtkPolyData() (slicer.modules.transforms.logic()).GetVisualization3d(polyData, node, node.GetRegionNode()) objWriter.SetInputData(polyData) elif (node.GetClassName() == "vtkMRMLModelNode"): objWriter.SetInputData(node.GetPolyData()) objWriter.Update() #objData = StringIO.StringIO() #objData.write(objWriter.GetResult()) #print objData.getvalue() #return objWriter.GetResult() return "nothing because I can't make it work so I'm using a temporary solution"
def extractNetwork(self, polyData): ''' Returns the network of the given surface. ''' # import the vmtk libraries try: from libvtkvmtkComputationalGeometryPython import * from libvtkvmtkMiscPython import * except ImportError: print "FAILURE: Unable to import the SlicerVmtk4 libraries!" radiusArrayName = 'Radius' topologyArrayName = 'Topology' marksArrayName = 'Marks' networkExtraction = vtkvmtkPolyDataNetworkExtraction() networkExtraction.SetInput(polyData) networkExtraction.SetAdvancementRatio(1.05) networkExtraction.SetRadiusArrayName(radiusArrayName) networkExtraction.SetTopologyArrayName(topologyArrayName) networkExtraction.SetMarksArrayName(marksArrayName) networkExtraction.Update() outPolyData = vtk.vtkPolyData() outPolyData.DeepCopy(networkExtraction.GetOutput()) outPolyData.Update() return outPolyData
def openSurfaceAtPoint( self, polyData, seed ): ''' Returns a new surface with an opening at the given seed. ''' someradius = 1.0 pointLocator = vtk.vtkPointLocator() pointLocator.SetDataSet( polyData ) pointLocator.BuildLocator() # find the closest point next to the seed on the surface # id = pointLocator.FindClosestPoint(int(seed[0]),int(seed[1]),int(seed[2])) id = pointLocator.FindClosestPoint( seed ) # the seed is now guaranteed on the surface seed = polyData.GetPoint( id ) sphere = vtk.vtkSphere() sphere.SetCenter( seed[0], seed[1], seed[2] ) sphere.SetRadius( someradius ) clip = vtk.vtkClipPolyData() clip.SetInputData( polyData ) clip.SetClipFunction( sphere ) clip.Update() outPolyData = vtk.vtkPolyData() outPolyData.DeepCopy( clip.GetOutput() ) return outPolyData
def __init__(self, sliceWidget): super(PaintEffectTool, self).__init__(sliceWidget) # configuration variables self.radius = 5 self.smudge = 0 self.delayedPaint = 1 # interaction state variables self.position = [0, 0, 0] self.paintCoordinates = [] self.feedbackActors = [] self.lastRadius = 0 # scratch variables self.rasToXY = vtk.vtkMatrix4x4() # initialization self.brush = vtk.vtkPolyData() self.createGlyph(self.brush) self.mapper = vtk.vtkPolyDataMapper2D() self.actor = vtk.vtkActor2D() self.mapper.SetInput(self.brush) self.actor.SetMapper(self.mapper) self.actor.VisibilityOff() self.renderer.AddActor2D(self.actor) self.actors.append(self.actor) self.processEvent()
def performPostProcessing(self, snrThreshold, distanceMinimumValue, distanceMaximumValue): # Create new vtkPolyData newPoints = vtk.vtkPoints() newVertices = vtk.vtkCellArray() newPolyData = vtk.vtkPolyData() newPolyData.SetPoints(newPoints) newPolyData.SetVerts(newVertices) colorArray = vtk.vtkDoubleArray() colorArray.SetNumberOfComponents(4) colorArray.SetName('Colors') newPolyData.GetPointData().SetScalars(colorArray) # Filter accordingly to the input parameters recordedDataBufferFiltered = [] for idx in range(len(self.recordedDataBuffer)): d = self.recordedDataBuffer[idx][3] snr = self.recordedDataBuffer[idx][4] if (snr > snrThreshold and d < distanceMaximumValue and d > distanceMinimumValue): recordedDataBufferFiltered.append(self.recordedDataBuffer[idx]) self.addPointToPolyData(newPolyData, self.recordedDataBuffer[idx][0:3]) # Update recorded model and buffer self.recordedModelNode.GetPolyData().DeepCopy(newPolyData) self.recordedModelNode.GetPolyData().Modified() self.recordedDataBuffer = recordedDataBufferFiltered
def run(self, inputFiducials, inputModel, outputTransform, transformType=0, numIterations=100): self.delayDisplay('Running iterative closest point registration') fiducialsPolyData = vtk.vtkPolyData() self.FiducialsToPolyData(inputFiducials, fiducialsPolyData) icpTransform = vtk.vtkIterativeClosestPointTransform() icpTransform.SetSource(fiducialsPolyData) icpTransform.SetTarget(inputModel.GetPolyData()) icpTransform.GetLandmarkTransform().SetModeToRigidBody() if transformType == 1: icpTransform.GetLandmarkTransform().SetModeToSimilarity() if transformType == 2: icpTransform.GetLandmarkTransform().SetModeToAffine() icpTransform.SetMaximumNumberOfIterations(numIterations) icpTransform.Modified() icpTransform.Update() outputTransform.SetMatrixTransformToParent(icpTransform.GetMatrix()) return True
def createGlyph(self): self.polyData = vtk.vtkPolyData() points = vtk.vtkPoints() lines = vtk.vtkCellArray() self.polyData.SetPoints( points ) self.polyData.SetLines( lines ) prevPoint = None firstPoint = None for x,y in ((0,0),)*4: p = points.InsertNextPoint( x, y, 0 ) if prevPoint != None: idList = vtk.vtkIdList() idList.InsertNextId( prevPoint ) idList.InsertNextId( p ) self.polyData.InsertNextCell( vtk.VTK_LINE, idList ) prevPoint = p if firstPoint == None: firstPoint = p # make the last line in the polydata idList = vtk.vtkIdList() idList.InsertNextId( p ) idList.InsertNextId( firstPoint ) self.polyData.InsertNextCell( vtk.VTK_LINE, idList )
def model(self, cmd): import qt import slicer p = urlparse.urlparse(cmd) q = urlparse.parse_qs(p.query) try: ID = str(q['ID'][0].strip()) except KeyError: ID = 'vtkMRMLModelNode4' import slicer node = slicer.util.getNode(ID) objWriter = vtk.vtkOBJWriter() #objWriter.SetWriteToMemory(True) objWriter.SetWriteToMemory(False) objWriter.SetFileName('C:/Users/Frankie/PerkWorkFiles/' + ID + '.obj') if (node.GetClassName() == "vtkMRMLTransformDisplayNode"): polyData = vtk.vtkPolyData() (slicer.modules.transforms.logic()).GetVisualization3d( polyData, node, node.GetRegionNode()) objWriter.SetInputData(polyData) elif (node.GetClassName() == "vtkMRMLModelNode"): objWriter.SetInputData(node.GetPolyData()) objWriter.Update() #objData = StringIO.StringIO() #objData.write(objWriter.GetResult()) #print objData.getvalue() #return objWriter.GetResult() return "nothing because I can't make it work so I'm using a temporary solution"
def __init__(self, sliceWidget): super(LevelTracingEffectTool,self).__init__(sliceWidget) # create a logic instance to do the non-gui work self.logic = LevelTracingEffectLogic(self.sliceWidget.sliceLogic()) # instance variables self.actionState = '' # initialization self.xyPoints = vtk.vtkPoints() self.rasPoints = vtk.vtkPoints() self.polyData = vtk.vtkPolyData() self.tracingFilter = vtkITK.vtkITKLevelTracingImageFilter() self.ijkToXY = vtk.vtkTransform() self.mapper = vtk.vtkPolyDataMapper2D() self.actor = vtk.vtkActor2D() property_ = self.actor.GetProperty() property_.SetColor( 107/255., 190/255., 99/255. ) property_.SetLineWidth( 1 ) self.mapper.SetInput(self.polyData) self.actor.SetMapper(self.mapper) property_ = self.actor.GetProperty() property_.SetColor(1,1,0) property_.SetLineWidth(1) self.renderer.AddActor2D( self.actor ) self.actors.append( self.actor )
def run(self, inputFiducials, inputModel, outputTransform, transformType=0, numIterations=100): """Run iterative closest point registration.""" logging.info('Running iterative closest point registration') fiducialsPolyData = vtk.vtkPolyData() self.FiducialsToPolyData(inputFiducials, fiducialsPolyData) icpTransform = vtk.vtkIterativeClosestPointTransform() icpTransform.SetSource(fiducialsPolyData) icpTransform.SetTarget(inputModel.GetPolyData()) icpTransform.GetLandmarkTransform().SetModeToRigidBody() if transformType == 1: icpTransform.GetLandmarkTransform().SetModeToSimilarity() if transformType == 2: icpTransform.GetLandmarkTransform().SetModeToAffine() icpTransform.SetMaximumNumberOfIterations(numIterations) icpTransform.Modified() icpTransform.Update() outputTransform.SetMatrixTransformToParent(icpTransform.GetMatrix()) if slicer.app.majorVersion >= 5 or (slicer.app.majorVersion >= 4 and slicer.app.minorVersion >= 11): outputTransform.SetNodeReferenceID(slicer.vtkMRMLTransformNode.GetMovingNodeReferenceRole(), inputFiducials.GetID()) outputTransform.SetNodeReferenceID(slicer.vtkMRMLTransformNode.GetFixedNodeReferenceRole(), inputModel.GetID()) return True
def extractNetwork( self, polyData ): ''' Returns the network of the given surface. ''' # import the vmtk libraries try: import vtkvmtkComputationalGeometryPython as vtkvmtkComputationalGeometry import vtkvmtkMiscPython as vtkvmtkMisc except ImportError: logging.error("Unable to import the SlicerVmtk libraries") radiusArrayName = 'Radius' topologyArrayName = 'Topology' marksArrayName = 'Marks' networkExtraction = vtkvmtkMisc.vtkvmtkPolyDataNetworkExtraction() networkExtraction.SetInputData( polyData ) networkExtraction.SetAdvancementRatio( 1.05 ) networkExtraction.SetRadiusArrayName( radiusArrayName ) networkExtraction.SetTopologyArrayName( topologyArrayName ) networkExtraction.SetMarksArrayName( marksArrayName ) networkExtraction.Update() outPolyData = vtk.vtkPolyData() outPolyData.DeepCopy( networkExtraction.GetOutput() ) return outPolyData
def openSurfaceAtPoint(self, polyData, seed): ''' Returns a new surface with an opening at the given seed. ''' someradius = 1.0 pointLocator = vtk.vtkPointLocator() pointLocator.SetDataSet(polyData) pointLocator.BuildLocator() # find the closest point next to the seed on the surface #id = pointLocator.FindClosestPoint(int(seed[0]),int(seed[1]),int(seed[2])) id = pointLocator.FindClosestPoint(seed) # the seed is now guaranteed on the surface seed = polyData.GetPoint(id) sphere = vtk.vtkSphere() sphere.SetCenter(seed[0], seed[1], seed[2]) sphere.SetRadius(someradius) clip = vtk.vtkClipPolyData() clip.SetInput(polyData) clip.SetClipFunction(sphere) clip.Update() outPolyData = vtk.vtkPolyData() outPolyData.DeepCopy(clip.GetOutput()) outPolyData.Update() return outPolyData
def __init__(self, sliceWidget): super(PaintEffectTool,self).__init__(sliceWidget) # create a logic instance to do the non-gui work self.logic = PaintEffectLogic(self.sliceWidget.sliceLogic()) # configuration variables self.delayedPaint = True self.parameterNode = self.editUtil.getParameterNode() self.sphere = not (0 == int(self.parameterNode.GetParameter("PaintEffect,sphere"))) self.smudge = not (0 == int(self.parameterNode.GetParameter("PaintEffect,smudge"))) self.pixelMode = not (0 == int(self.parameterNode.GetParameter("PaintEffect,pixelMode"))) self.radius = float(self.parameterNode.GetParameter("PaintEffect,radius")) # interaction state variables self.position = [0, 0, 0] self.paintCoordinates = [] self.feedbackActors = [] self.lastRadius = 0 # scratch variables self.rasToXY = vtk.vtkMatrix4x4() # initialization self.brush = vtk.vtkPolyData() self.createGlyph(self.brush) self.mapper = vtk.vtkPolyDataMapper2D() self.actor = vtk.vtkActor2D() self.mapper.SetInput(self.brush) self.actor.SetMapper(self.mapper) self.actor.VisibilityOff() self.renderer.AddActor2D(self.actor) self.actors.append(self.actor) self.processEvent()
def __init__(self, sliceWidget): super(PaintEffectTool,self).__init__(sliceWidget) # configuration variables self.radius = 5 self.smudge = 0 self.delayedPaint = 1 # interaction state variables self.position = [0, 0, 0] self.paintCoordinates = [] self.feedbackActors = [] self.lastRadius = 0 # scratch variables self.rasToXY = vtk.vtkMatrix4x4() # initialization self.brush = vtk.vtkPolyData() self.createGlyph(self.brush) self.mapper = vtk.vtkPolyDataMapper2D() self.actor = vtk.vtkActor2D() self.mapper.SetInput(self.brush) self.actor.SetMapper(self.mapper) self.actor.VisibilityOff() self.renderer.AddActor2D(self.actor) self.actors.append(self.actor) self.processEvent()
def updateCurve(self): if self.SourceNode and self.DestinationNode: if self.SourceNode.GetNumberOfFiducials() < 2: if self.CurvePoly != None: self.CurvePoly.Initialize() else: if self.CurvePoly == None: self.CurvePoly = vtk.vtkPolyData() if self.DestinationNode.GetDisplayNodeID() == None: modelDisplayNode = slicer.vtkMRMLModelDisplayNode() modelDisplayNode.SetColor(self.CurveColour) slicer.mrmlScene.AddNode(modelDisplayNode) self.DestinationNode.SetAndObserveDisplayNodeID( modelDisplayNode.GetID()) if self.InterpolationMethod == 0: self.nodesToLinear(self.SourceNode, self.CurvePoly) elif self.InterpolationMethod == 1: self.nodesToSpline(self.SourceNode, self.CurvePoly) tubeFilter = vtk.vtkTubeFilter() tubeFilter.SetInputData(self.CurvePoly) tubeFilter.SetRadius(self.CurveThickness) tubeFilter.SetNumberOfSides(self.CurveFaces) tubeFilter.CappingOn() tubeFilter.Update() self.DestinationNode.SetAndObservePolyData(tubeFilter.GetOutput()) self.DestinationNode.Modified() if self.DestinationNode.GetScene() == None: slicer.mrmlScene.AddNode(self.DestinationNode) displayNode = self.DestinationNode.GetDisplayNode() if displayNode: displayNode.SetActiveScalarName('')
def onApplyButton(self): """ Aply the Surface ICP Registration """ print("Run the algorithm") fixed = self.modelSelectors['Fixed Surface Volume'].currentNode() moving = self.modelSelectors['Moving Surface Volume'].currentNode() outputSurf = self.modelOutputSurfaceSelectors['Output Surface Volume'].currentNode() initialTrans = self.volumeInitialTransformSelectors["Initial Transform"].currentNode() outputTrans = self.volumeOutputTransformSelectors["Output Transform"].currentNode() inputPolyData = moving.GetPolyData() if initialTrans: print "Applying initial transform" initialMatrix = initialTrans.GetMatrixTransformToParent() transform = vtk.vtkTransform() transform.SetMatrix(initialMatrix) transformFilter = vtk.vtkTransformPolyDataFilter() transformFilter.SetInput(inputPolyData) transformFilter.SetTransform(transform) transformFilter.Update() inputPolyData = transformFilter.GetOutput() self.icp.SetSource(inputPolyData) self.icp.SetTarget(fixed.GetPolyData()) print self.icpLandmarkTransformType if self.icpLandmarkTransformType == "RigidBody": print self.icpLandmarkTransformType self.icp.GetLandmarkTransform().SetModeToRigidBody() elif self.icpLandmarkTransformType == "Similarity": print self.icpLandmarkTransformType self.icp.GetLandmarkTransform().SetModeToSimilarity() print self.icpLandmarkTransformType elif self.icpLandmarkTransformType == "Affine": self.icp.GetLandmarkTransform().SetModeToAffine() self.icp.SetMaximumNumberOfIterations(self.numberOfIterationsValueChanged) self.icp.SetMaximumMeanDistance(self.maxDistanceValueChanged) self.icp.SetMaximumNumberOfLandmarks(self.numberOfLandmarksValueChanged) self.icp.SetCheckMeanDistance(int(self.checkMeanDistanceActive)) self.icp.SetStartByMatchingCentroids(int(self.matchCentroidsLinearActive)) #self.icp.Update print self.icp.GetLandmarkTransform() outputMatrix = vtk.vtkMatrix4x4() self.icp.GetMatrix(outputMatrix) outputTrans.SetAndObserveMatrixTransformToParent(outputMatrix) outputPolyData = vtk.vtkPolyData() outputPolyData.DeepCopy(inputPolyData) outputSurf.SetAndObservePolyData(outputPolyData) print self.icp.GetLandmarkTransform() print self.icp.GetLandmarkTransform().GetSourceLandmarks() print self.icp.GetLandmarkTransform().GetTargetLandmarks() print self.icp.GetMaximumMeanDistance() print self.icp.GetMeanDistanceModeAsString() print self.icp.GetMaximumNumberOfIterations() print self.icp.GetMaximumNumberOfLandmarks()
def generateGridModel(self): print "generateGridModel" polyData = vtk.vtkPolyData() if (self.gridPattern == self.gridPatternRectangular): polyData = self.generateGridPolyDataRectangular() elif (self.gridPattern == self.gridPatternTriangular): polyData = self.generateGridPolyDataTriangular() self.addPolyDataToScene(polyData, "Grid")
def generateGridModel(self): print "generateGridModel" polyData = vtk.vtkPolyData() if (self.gridPattern == self.gridPatternRectangular): polyData = self.generateGridPolyDataRectangular() elif (self.gridPattern == self.gridPatternTriangular): polyData = self.generateGridPolyDataTriangular() self.addPolyDataToScene(polyData,"Grid")
def DepthMapToPointCloud(self, depthmapFilename, rgbFilename): # Create point cloud depthImage = imageio.imread(depthmapFilename) rgbImage = imageio.imread(rgbFilename) height = len(depthImage) width = len(depthImage[0]) minimumDepth = np.amin(depthImage) maximumDepth = np.amax(depthImage) print(maximumDepth) points = vtk.vtkPoints() fx_d = self.focalLengthBox.value fy_d = self.focalLengthBox.value for u in range(height): for v in range(width): vflipped = width - (v + 1) z = depthImage[u][vflipped] z = z[0] / self.depthDividerBox.value if z < 60: #if True: points.InsertNextPoint( np.array([ z * (u - (height / 2)) / fx_d, z * (v - (width / 2)) / fy_d, z ])) # Create junk polygons so that Slicer can actually display the point cloud polydata = vtk.vtkPolyData() polydata.SetPoints(points) poly = vtk.vtkPolygon() poly.GetPointIds().SetNumberOfIds(points.GetNumberOfPoints()) for n in range(points.GetNumberOfPoints()): poly.GetPointIds().SetId(n, n) polys = vtk.vtkCellArray() polys.InsertNextCell(poly) polydata.SetPolys(polys) # Display the point cloud modelNode = self.pointCloudSelector.currentNode() modelNode.SetAndObservePolyData(polydata) modelDisplayNode = modelNode.GetModelDisplayNode() if modelDisplayNode is None: modelDisplayNode = slicer.vtkMRMLModelDisplayNode() modelDisplayNode.SetScene(slicer.mrmlScene) slicer.mrmlScene.AddNode(modelDisplayNode) modelNode.SetAndObserveDisplayNodeID(modelDisplayNode.GetID()) modelDisplayNode.SetRepresentation( modelDisplayNode.PointsRepresentation) modelDisplayNode.SetPointSize(4) modelDisplayNode.SetOpacity(0.2) modelDisplayNode.SetColor(1, 0, 0) return modelNode
def clearPointsInPolyData(self,): if self.recordedModelNode: newPoints = vtk.vtkPoints() newVertices = vtk.vtkCellArray() newPolyData = vtk.vtkPolyData() newPolyData.SetPoints(newPoints) newPolyData.SetVerts(newVertices) self.recordedModelNode.GetPolyData().DeepCopy(newPolyData) self.recordedModelNode.GetPolyData().Modified()
def prepareModel( self, polyData ): ''' ''' # import the vmtk libraries try: #from libvtkvmtkComputationalGeometryPython import * #from libvtkvmtkMiscPython import * import libvtkvmtkComputationalGeometryPython as cg import libvtkvmtkMiscPython as m except ImportError: print "FAILURE: Unable to import the SlicerVmtk libraries!" capDisplacement = 0.0 surfaceCleaner = vtk.vtkCleanPolyData() surfaceCleaner.SetInput( polyData ) surfaceCleaner.Update() surfaceTriangulator = vtk.vtkTriangleFilter() surfaceTriangulator.SetInput( surfaceCleaner.GetOutput() ) surfaceTriangulator.PassLinesOff() surfaceTriangulator.PassVertsOff() surfaceTriangulator.Update() # new steps for preparation to avoid problems because of slim models (f.e. at stenosis) subdiv = vtk.vtkLinearSubdivisionFilter() subdiv.SetInput( surfaceTriangulator.GetOutput() ) subdiv.SetNumberOfSubdivisions( 1 ) subdiv.Update() smooth = vtk.vtkWindowedSincPolyDataFilter() smooth.SetInput( subdiv.GetOutput() ) smooth.SetNumberOfIterations( 20 ) smooth.SetPassBand( 0.1 ) smooth.SetBoundarySmoothing( 1 ) smooth.Update() normals = vtk.vtkPolyDataNormals() normals.SetInput( smooth.GetOutput() ) normals.SetAutoOrientNormals( 1 ) normals.SetFlipNormals( 0 ) normals.SetConsistency( 1 ) normals.SplittingOff() normals.Update() surfaceCapper = m.vtkvmtkCapPolyData() surfaceCapper.SetInput( normals.GetOutput() ) surfaceCapper.SetDisplacement( capDisplacement ) surfaceCapper.SetInPlaneDisplacement( capDisplacement ) surfaceCapper.Update() outPolyData = vtk.vtkPolyData() outPolyData.DeepCopy( surfaceCapper.GetOutput() ) outPolyData.Update() return outPolyData
def ConvertTextureToPointAttribute(modelNode, textureImageNode): polyData=modelNode.GetPolyData() textureImageFlipVert=vtk.vtkImageFlip() textureImageFlipVert.SetFilteredAxis(1) textureImageFlipVert.SetInputConnection(textureImageNode.GetImageDataConnection()) textureImageFlipVert.Update() textureImageData=textureImageFlipVert.GetOutput() pointData=polyData.GetPointData() tcoords=pointData.GetTCoords() numOfPoints=pointData.GetNumberOfTuples() assert numOfPoints==tcoords.GetNumberOfTuples(), "Number of texture coordinates does not equal number of points" textureSamplingPointsUv=vtk.vtkPoints() textureSamplingPointsUv.SetNumberOfPoints(numOfPoints) for pointIndex in xrange(numOfPoints): uv=tcoords.GetTuple2(pointIndex) textureSamplingPointsUv.SetPoint(pointIndex, uv[0], uv[1], 0) textureSamplingPointDataUv=vtk.vtkPolyData() uvToXyz=vtk.vtkTransform() textureImageDataSpacingSpacing=textureImageData.GetSpacing() textureImageDataSpacingOrigin=textureImageData.GetOrigin() textureImageDataSpacingDimensions=textureImageData.GetDimensions() uvToXyz.Scale(textureImageDataSpacingDimensions[0]/textureImageDataSpacingSpacing[0], textureImageDataSpacingDimensions[1]/textureImageDataSpacingSpacing[1], 1) uvToXyz.Translate(textureImageDataSpacingOrigin) textureSamplingPointDataUv.SetPoints(textureSamplingPointsUv) transformPolyDataToXyz=vtk.vtkTransformPolyDataFilter() transformPolyDataToXyz.SetInputData(textureSamplingPointDataUv) transformPolyDataToXyz.SetTransform(uvToXyz) probeFilter=vtk.vtkProbeFilter() probeFilter.SetInputConnection(transformPolyDataToXyz.GetOutputPort()) probeFilter.SetSourceData(textureImageData) probeFilter.Update() rgbPoints=probeFilter.GetOutput().GetPointData().GetArray('ImageScalars') colorArrayRed=vtk.vtkDoubleArray() colorArrayRed.SetName('ColorRed') colorArrayRed.SetNumberOfTuples(numOfPoints) colorArrayGreen=vtk.vtkDoubleArray() colorArrayGreen.SetName('ColorGreen') colorArrayGreen.SetNumberOfTuples(numOfPoints) colorArrayBlue=vtk.vtkDoubleArray() colorArrayBlue.SetName('ColorBlue') colorArrayBlue.SetNumberOfTuples(numOfPoints) for pointIndex in xrange(numOfPoints): rgb=rgbPoints.GetTuple3(pointIndex) colorArrayRed.SetValue(pointIndex,rgb[0]) colorArrayGreen.SetValue(pointIndex,rgb[1]) colorArrayBlue.SetValue(pointIndex,rgb[2]) colorArrayRed.Modified() colorArrayGreen.Modified() colorArrayBlue.Modified() pointData.AddArray(colorArrayRed) pointData.AddArray(colorArrayGreen) pointData.AddArray(colorArrayBlue) pointData.Modified() polyData.Modified()
def JoinBoundaryPoints( self, hullPoints1, hullPoints2, offset ): if ( hullPoints1.GetNumberOfPoints() != hullPoints2.GetNumberOfPoints() ): return joiningAppend = vtk.vtkAppendPolyData() numPoints = hullPoints1.GetNumberOfPoints() for i in range( 0, numPoints ): currPointsForSurface = vtk.vtkPoints() point1 = [ 0, 0, 0 ] hullPoints1.GetPoint( ( i - offset )% numPoints, point1 ) currPointsForSurface.InsertNextPoint( point1[ 0 ], point1[ 1 ], point1[ 2 ] ) point2 = [ 0, 0, 0 ] hullPoints2.GetPoint( ( - i ) % numPoints, point2 ) currPointsForSurface.InsertNextPoint( point2[ 0 ], point2[ 1 ], point2[ 2 ] ) # Observe that the deep is flipped from the surface # Must proceed in opposite orders point3 = [ 0, 0, 0 ] hullPoints1.GetPoint( ( i + 1 - offset ) % numPoints, point3 ) currPointsForSurface.InsertNextPoint( point3[ 0 ], point3[ 1 ], point3[ 2 ] ) point4 = [ 0, 0, 0 ] hullPoints2.GetPoint( ( - ( i + 1 ) ) % numPoints, point4 ) currPointsForSurface.InsertNextPoint( point4[ 0 ], point4[ 1 ], point4[ 2 ] ) # We know what the triangles should look like, so create them manually # Note: The order here is important - ensure the triangles face the correct way triangle1 = vtk.vtkTriangle() triangle1.GetPointIds().SetId( 0, 0 ) triangle1.GetPointIds().SetId( 1, 1 ) triangle1.GetPointIds().SetId( 2, 2 ) triangle2 = vtk.vtkTriangle() triangle2.GetPointIds().SetId( 0, 3 ) triangle2.GetPointIds().SetId( 1, 2 ) triangle2.GetPointIds().SetId( 2, 1 ) triangles = vtk.vtkCellArray() triangles.InsertNextCell( triangle1 ) triangles.InsertNextCell( triangle2 ) currPolyDataForSurface = vtk.vtkPolyData() currPolyDataForSurface.SetPoints( currPointsForSurface ) currPolyDataForSurface.SetPolys( triangles ) joiningAppend.AddInputData( currPolyDataForSurface ) joiningAppend.Update() return joiningAppend.GetOutput()
def PointsToPolyData(self, listOfPoints): """ Converts 3D list of points of an array into a polyData line The connections between this line are simply the order in which they are provided """ points = vtk.vtkPoints() idlist = vtk.vtkIdList() numOfPoints = len(listOfPoints) if numOfPoints == 0: print("WARNING:No points to convert to polyData") return vtk.vtkPolyData() #returning Blank PolyData points.SetNumberOfPoints(numOfPoints) for i in range(numOfPoints): points.InsertPoint(i, listOfPoints[i]) #Add the points idlist.InsertNextId(i) polyData = vtk.vtkPolyData() polyData.Allocate() polyData.InsertNextCell(vtk.VTK_LINE, idlist) polyData.SetPoints(points) return polyData
def PointsToPolyData(self,listOfPoints): """ Converts 3D list of points of an array into a polyData line The connections between this line are simply the order in which they are provided """ points=vtk.vtkPoints() idlist = vtk.vtkIdList() numOfPoints=len(listOfPoints) if numOfPoints==0: print ("WARNING:No points to convert to polyData") return vtk.vtkPolyData() #returning Blank PolyData points.SetNumberOfPoints(numOfPoints) for i in range (numOfPoints): points.InsertPoint(i, listOfPoints[i]) #Add the points idlist.InsertNextId(i) polyData=vtk.vtkPolyData() polyData.Allocate() polyData.InsertNextCell(vtk.VTK_LINE,idlist) polyData.SetPoints(points) return polyData
def startTransformMapping(self, groundTruthTransformNode, mappedTransformNode, outputVisitedPointsModelNode, positionErrorTransformNode, orientationErrorTransformNode): self.removeObservers() self.groundTruthTransformNode = groundTruthTransformNode self.mappedTransformNode = mappedTransformNode self.outputVisitedPointsModelNode = outputVisitedPointsModelNode self.positionErrorTransformNode = positionErrorTransformNode self.orientationErrorTransformNode = orientationErrorTransformNode self.positionErrorMagnitudeList = [] self.orientationErrorMagnitudeList = [] if self.outputVisitedPointsModelNode: if not self.outputVisitedPointsModelNode.GetDisplayNode(): modelDisplay = slicer.vtkMRMLModelDisplayNode() #modelDisplay.SetSliceIntersectionVisibility(False) # Show in slice view #modelDisplay.SetEdgeVisibility(True) # Hide in 3D view modelDisplay.SetEdgeVisibility(True) slicer.mrmlScene.AddNode(modelDisplay) self.outputVisitedPointsModelNode.SetAndObserveDisplayNodeID(modelDisplay.GetID()) self.visitedPoints = vtk.vtkPoints() self.visitedPointsPolydata = vtk.vtkPolyData() self.visitedPointsPolydata.SetPoints(self.visitedPoints) glyph = vtk.vtkPolyData() cubeSource = vtk.vtkCubeSource() cubeSource.SetXLength(self.minimumSamplingDistance) cubeSource.SetYLength(self.minimumSamplingDistance) cubeSource.SetZLength(self.minimumSamplingDistance) self.visitedPointsGlyph3d = vtk.vtkGlyph3D() self.visitedPointsGlyph3d.SetSourceConnection(cubeSource.GetOutputPort()) self.visitedPointsGlyph3d.SetInputData(self.visitedPointsPolydata) self.visitedPointsGlyph3d.Update() self.outputVisitedPointsModelNode.SetPolyDataConnection(self.visitedPointsGlyph3d.GetOutputPort()) self.initializeErrorTransform(self.positionErrorTransformNode) self.initializeErrorTransform(self.orientationErrorTransformNode) # Start the updates self.addObservers() self.onGroundTruthTransformNodeModified(0,0)
def computeCenterlines( self, polyData, inletSeedIds, outletSeedIds ): ''' Returns a tupel of two vtkPolyData objects. The first are the centerlines, the second is the corresponding Voronoi diagram. ''' # import the vmtk libraries try: from libvtkvmtkComputationalGeometryPython import * from libvtkvmtkMiscPython import * except ImportError: print "FAILURE: Unable to import the SlicerVmtk4 libraries!" flipNormals = 0 radiusArrayName = 'Radius' costFunction = '1/R' centerlineFilter = vtkvmtkPolyDataCenterlines() centerlineFilter.SetInput( polyData ) centerlineFilter.SetSourceSeedIds( inletSeedIds ) centerlineFilter.SetTargetSeedIds( outletSeedIds ) centerlineFilter.SetRadiusArrayName( radiusArrayName ) centerlineFilter.SetCostFunction( costFunction ) centerlineFilter.SetFlipNormals( flipNormals ) centerlineFilter.SetAppendEndPointsToCenterlines( 0 ) centerlineFilter.SetSimplifyVoronoi( 0 ) centerlineFilter.SetCenterlineResampling( 0 ) centerlineFilter.SetResamplingStepLength( 1.0 ) centerlineFilter.Update() outPolyData = vtk.vtkPolyData() outPolyData.DeepCopy( centerlineFilter.GetOutput() ) outPolyData.Update() outPolyData2 = vtk.vtkPolyData() outPolyData2.DeepCopy( centerlineFilter.GetVoronoiDiagram() ) outPolyData2.Update() return [outPolyData, outPolyData2]
def computeCenterlines( self, polyData, inletSeedIds, outletSeedIds ): ''' Returns a tupel of two vtkPolyData objects. The first are the centerlines, the second is the corresponding Voronoi diagram. ''' # import the vmtk libraries try: import libvtkvmtkComputationalGeometryPython as cg import libvtkvmtkMiscPython as m except ImportError: print "FAILURE: Unable to import the SlicerVmtk libraries!" flipNormals = 0 radiusArrayName = 'Radius' costFunction = '1/R' centerlineFilter = cg.vtkvmtkPolyDataCenterlines() centerlineFilter.SetInput( polyData ) centerlineFilter.SetSourceSeedIds( inletSeedIds ) centerlineFilter.SetTargetSeedIds( outletSeedIds ) centerlineFilter.SetRadiusArrayName( radiusArrayName ) centerlineFilter.SetCostFunction( costFunction ) centerlineFilter.SetFlipNormals( flipNormals ) centerlineFilter.SetAppendEndPointsToCenterlines( 0 ) centerlineFilter.SetSimplifyVoronoi( 0 ) centerlineFilter.SetCenterlineResampling( 0 ) centerlineFilter.SetResamplingStepLength( 1.0 ) centerlineFilter.Update() outPolyData = vtk.vtkPolyData() outPolyData.DeepCopy( centerlineFilter.GetOutput() ) outPolyData.Update() outPolyData2 = vtk.vtkPolyData() outPolyData2.DeepCopy( centerlineFilter.GetVoronoiDiagram() ) outPolyData2.Update() return [outPolyData, outPolyData2]
def clearPointsInRecordedModel(self): self.recordedDataBuffer = [] newPoints = vtk.vtkPoints() newVertices = vtk.vtkCellArray() newPolyData = vtk.vtkPolyData() newPolyData.SetPoints(newPoints) newPolyData.SetVerts(newVertices) colorArray = vtk.vtkDoubleArray() colorArray.SetNumberOfComponents(4) colorArray.SetName('Colors') newPolyData.GetPointData().SetScalars(colorArray) self.recordedModelNode.GetPolyData().DeepCopy(newPolyData) self.recordedModelNode.GetPolyData().Modified()
def marchingCubes( self, image, ijkToRasMatrix, threshold ): transformIJKtoRAS = vtk.vtkTransform() transformIJKtoRAS.SetMatrix( ijkToRasMatrix ) marchingCubes = vtk.vtkMarchingCubes() marchingCubes.SetInput( image ) marchingCubes.SetValue( 0, threshold ) marchingCubes.ComputeScalarsOn() marchingCubes.ComputeGradientsOn() marchingCubes.ComputeNormalsOn() marchingCubes.GetOutput().ReleaseDataFlagOn() marchingCubes.Update() if transformIJKtoRAS.GetMatrix().Determinant() < 0: reverser = vtk.vtkReverseSense() reverser.SetInput( marchingCubes.GetOutput() ) reverser.ReverseNormalsOn() reverser.GetOutput().ReleaseDataFlagOn() reverser.Update() correctedOutput = reverser.GetOutput() else: correctedOutput = marchingCubes.GetOutput() transformer = vtk.vtkTransformPolyDataFilter() transformer.SetInput( correctedOutput ) transformer.SetTransform( transformIJKtoRAS ) transformer.GetOutput().ReleaseDataFlagOn() transformer.Update() normals = vtk.vtkPolyDataNormals() normals.ComputePointNormalsOn() normals.SetInput( transformer.GetOutput() ) normals.SetFeatureAngle( 60 ) normals.SetSplitting( 1 ) normals.GetOutput().ReleaseDataFlagOn() normals.Update() stripper = vtk.vtkStripper() stripper.SetInput( normals.GetOutput() ) stripper.GetOutput().ReleaseDataFlagOff() stripper.Update() stripper.GetOutput().Update() result = vtk.vtkPolyData() result.DeepCopy( stripper.GetOutput() ) result.Update() return result
def marchingCubes(self,image,ijkToRasMatrix,threshold): transformIJKtoRAS = vtk.vtkTransform() transformIJKtoRAS.SetMatrix(ijkToRasMatrix) marchingCubes = vtk.vtkMarchingCubes() marchingCubes.SetInput(image) marchingCubes.SetValue(0,threshold) marchingCubes.ComputeScalarsOn() marchingCubes.ComputeGradientsOn() marchingCubes.ComputeNormalsOn() marchingCubes.GetOutput().ReleaseDataFlagOn() marchingCubes.Update() if transformIJKtoRAS.GetMatrix().Determinant() < 0: reverser = vtk.vtkReverseSense() reverser.SetInput(marchingCubes.GetOutput()) reverser.ReverseNormalsOn() reverser.GetOutput().ReleaseDataFlagOn() reverser.Update() correctedOutput = reverser.GetOutput() else: correctedOutput = marchingCubes.GetOutput() transformer = vtk.vtkTransformPolyDataFilter() transformer.SetInput(correctedOutput) transformer.SetTransform(transformIJKtoRAS) transformer.GetOutput().ReleaseDataFlagOn() transformer.Update() normals = vtk.vtkPolyDataNormals() normals.ComputePointNormalsOn() normals.SetInput(transformer.GetOutput()) normals.SetFeatureAngle(60) normals.SetSplitting(1) normals.GetOutput().ReleaseDataFlagOn() normals.Update() stripper = vtk.vtkStripper() stripper.SetInput(normals.GetOutput()) stripper.GetOutput().ReleaseDataFlagOff() stripper.Update() stripper.GetOutput().Update() result = vtk.vtkPolyData() result.DeepCopy(stripper.GetOutput()) result.Update() return result
def onProbeVolumeButtonClicked(self): # Set flag to prevent model from being thresholded without user input self.thresholdFlag = 0 wallModel = self.inputModelSelector.currentNode() inputVol = self.inputVolumeSelector.currentNode() self.polyData = vtk.vtkPolyData() if not (wallModel): qt.QMessageBox.critical(slicer.util.mainWindow(), 'Scar Visualization', 'Wall model is required to proceed.') elif not (inputVol): qt.QMessageBox.critical(slicer.util.mainWindow(), 'Scar Visualization', 'Input volume is required to proceed.') else: self.outputModel = slicer.vtkMRMLModelNode() self.outputModel.SetName("Output Model") slicer.mrmlScene.AddNode(self.outputModel) paramProbe = {} paramProbe['InputVolume'] = inputVol paramProbe['InputModel'] = wallModel paramProbe['OutputModel'] = self.outputModel # Pass parameters to Probe Volume Model slicer.cli.run(slicer.modules.probevolumewithmodel, None, paramProbe, wait_for_completion=True) # Set color of output model labelsColorNode = slicer.modules.colors.logic( ).GetColorTableNodeID(35) # Color Warm Tint 3 self.outputModel.GetDisplayNode().SetAndObserveColorNodeID( labelsColorNode) # Delete input model which is not required anymore slicer.mrmlScene.RemoveNode(wallModel) # Update threshold widget with scalar values from model self.polyData = self.outputModel.GetPolyData() self.numberOfPoints = self.polyData.GetNumberOfPoints() self.scalars = vtk.vtkFloatArray() self.scalars = self.polyData.GetPointData().GetScalars("NRRDImage") self.range = [0] * 2 numberOfComponents = self.scalars.GetNumberOfComponents() for i in xrange(numberOfComponents): self.scalars.GetRange(self.range, i) lowerThreshold = self.range[0] upperThreshold = self.range[1] # Set threshold range according to current model self.threshold.minimum = lowerThreshold self.threshold.maximum = upperThreshold self.thresholdFlag = 1
def ImageNegation(self,imageData,referenceVolume): """ This function negates the image PARAM: imageData1 vtkImageData() PARAM: vtkMRMLScalarVolumeNode() referenceVolume RETURN: vtkImageData() ASK ANDRAS IS THERE IS A BETTERWAY TO FLIP THE BINARY BITS """ air = self.PolyDataToImageData(vtk.vtkPolyData(),referenceVolume,0,255) imageLogic= vtk.vtkImageLogic() imageLogic.SetOperationToXor() imageLogic.SetInput1Data(imageData) imageLogic.SetInput2Data(air) imageLogic.Update() return imageLogic.GetOutput()
def addUpdateObserver(self, inputNode, fixedNode): self.observedNode = inputNode self.fixedNode = fixedNode self.recordedModelNode = slicer.util.getNode('RecordedModel') if not self.recordedModelNode: recordedPoints = vtk.vtkPoints() recordedVertices = vtk.vtkCellArray() recordedPolyData = vtk.vtkPolyData() recordedPolyData.SetPoints(recordedPoints) recordedPolyData.SetVerts(recordedVertices) self.recordedModelNode = self.addModelToScene(recordedPolyData, "RecordedModel") self.recordedModelNode.GetModelDisplayNode().SetPointSize(3) if self.outputObserverTag == -1: self.outputObserverTag = inputNode.AddObserver('ModifiedEvent', self.updateSceneCallback)
def createScalingRuler(self, sliceViewName): # # Create the Scaling Ruler # self.points[sliceViewName] = vtk.vtkPoints() self.points[sliceViewName].SetNumberOfPoints(22) lines = [] for i in xrange(0,21): line = vtk.vtkLine() lines.append(line) # setting the points to lines for i in xrange(0,21): if (i%2 == 0): lines[i].GetPointIds().SetId(0,i) lines[i].GetPointIds().SetId(1,i+1) else: lines[i].GetPointIds().SetId(0,i-1) lines[i].GetPointIds().SetId(1,i+1) # Create a cell array to store the lines in and add the lines to it linesArray = vtk.vtkCellArray() for i in xrange(0,21): linesArray.InsertNextCell(lines[i]) # Create a polydata to store everything in linesPolyData = vtk.vtkPolyData() # Add the points to the dataset linesPolyData.SetPoints(self.points[sliceViewName]) # Add the lines to the dataset linesPolyData.SetLines(linesArray) # mapper mapper = vtk.vtkPolyDataMapper2D() if vtk.VTK_MAJOR_VERSION <= 5: mapper.SetInput(linesPolyData) else: mapper.SetInputData(linesPolyData) # actor actor = self.scalingRulerActors[sliceViewName] actor.SetMapper(mapper) # color actor actor.GetProperty().SetColor(1,1,1) actor.GetProperty().SetLineWidth(1) textActor = self.scalingRulerTextActors[sliceViewName] textProperty = textActor.GetTextProperty()
def import_obj_from_blender(self, data): slicer.util.confirmOkCancelDisplay("Received object(s) from Blender.", "linkSlicerBlender Info:") def mkVtkIdList(it): vil = vtk.vtkIdList() for i in it: vil.InsertNextId(int(i)) return vil #print(data) obj, xml = data.split("_XML_DATA_") obj_points, obj_polys = obj.split("_POLYS_") obj_points = eval(obj_points) obj_polys = eval(obj_polys) blender_faces = [] offset = 0 #unflatten the list from blender while (offset < len(obj_polys)): vertices_per_face = obj_polys[offset] offset += 1 vertex_indices = obj_polys[offset:offset + vertices_per_face] blender_faces.append(vertex_indices) offset += vertices_per_face tree = ET.ElementTree(ET.fromstring(xml)) x_scene = tree.getroot() mesh = vtk.vtkPolyData() points = vtk.vtkPoints() polys = vtk.vtkCellArray() #print(blender_faces) for i in range(len(obj_points)): points.InsertPoint(i, obj_points[i]) for i in range(len(blender_faces)): polys.InsertNextCell(mkVtkIdList(blender_faces[i])) mesh.SetPoints(points) mesh.SetPolys(polys) # Create model node and add to scene modelNode = slicer.mrmlScene.AddNewNodeByClass('vtkMRMLModelNode') modelNode.SetName( x_scene[0].get('name') ) #only expecting one obj in the xml, since sent w/ OBJ together modelNode.SetAndObservePolyData(mesh) modelNode.CreateDefaultDisplayNodes() modelNode.GetDisplayNode().SetSliceIntersectionVisibility(True) modelNode.GetDisplayNode().SetSliceIntersectionThickness(2) #update object location in scene self.update_scene(xml)
def initialize(self): self.layoutManager = slicer.app.layoutManager() self.threeDWidget = self.layoutManager.threeDWidget(0) self.threeDView = self.threeDWidget.threeDView() self.renderWindow = self.threeDView.renderWindow() self.renderers = self.renderWindow.GetRenderers() self.renderer = self.renderers.GetFirstRenderer() self.polydata = vtk.vtkPolyData() self.points = vtk.vtkPoints() self.planeSource = vtk.vtkPlaneSource() self.mapper = vtk.vtkPolyDataMapper() self.actor = vtk.vtkActor() self.renderer.AddViewProp(self.actor) self.renderWindow.AddRenderer(self.renderer)
def ImageNegation(self, imageData, referenceVolume): """ This function negates the image PARAM: imageData1 vtkImageData() PARAM: vtkMRMLScalarVolumeNode() referenceVolume RETURN: vtkImageData() ASK ANDRAS IS THERE IS A BETTERWAY TO FLIP THE BINARY BITS """ air = self.PolyDataToImageData(vtk.vtkPolyData(), referenceVolume, 0, 255) imageLogic = vtk.vtkImageLogic() imageLogic.SetOperationToXor() imageLogic.SetInput1Data(imageData) imageLogic.SetInput2Data(air) imageLogic.Update() return imageLogic.GetOutput()
def initialize(self): self.layoutManager=slicer.app.layoutManager() self.threeDWidget=self.layoutManager.threeDWidget(0) self.threeDView=self.threeDWidget.threeDView() self.renderWindow=self.threeDView.renderWindow() self.renderers=self.renderWindow.GetRenderers() self.renderer=self.renderers.GetFirstRenderer() self.polydata = vtk.vtkPolyData() self.points = vtk.vtkPoints() self.planeSource = vtk.vtkPlaneSource() self.mapper = vtk.vtkPolyDataMapper() self.actor = vtk.vtkActor() self.renderer.AddViewProp(self.actor) self.renderWindow.AddRenderer(self.renderer)
def calculateFiducialDistance(self, modelNode, fiducial): closestFiducial = slicer.util.getNode('CP') if not closestFiducial: closestFiducial = slicer.vtkMRMLMarkupsFiducialNode() closestFiducial.SetName('CP') closestFiducial.AddFiducial(0, 0, 0) closestFiducial.SetNthFiducialLabel(0, 'CP') slicer.mrmlScene.AddNode(closestFiducial) closestFiducial.SetDisplayVisibility(False) line = slicer.util.getNode('Line') if not line: line = slicer.vtkMRMLModelNode() line.SetName('Line') linePolyData = vtk.vtkPolyData() line.SetAndObservePolyData(linePolyData) modelDisplay = slicer.vtkMRMLModelDisplayNode() modelDisplay.SetSliceIntersectionVisibility(True) modelDisplay.SetColor(0,1,0) slicer.mrmlScene.AddNode(modelDisplay) line.SetAndObserveDisplayNodeID(modelDisplay.GetID()) slicer.mrmlScene.AddNode(line) cellLocator = vtk.vtkCellLocator() cellLocator.SetDataSet(modelNode.GetPolyData()) cellLocator.BuildLocator() if fiducial.GetNumberOfFiducials() > 0: ras = [0.0, 0.0, 0.0] closestPoint = [0.0, 0.0, 0.0] fiducial.GetNthFiducialPosition(0, ras) distanceSquared = vtk.mutable(0.0) subId = vtk.mutable(0) cellId = vtk.mutable(0) cell = vtk.vtkGenericCell() cellLocator.FindClosestPoint(ras, closestPoint, cell, cellId, subId, distanceSquared); distance = math.sqrt(distanceSquared) closestFiducial.SetNthFiducialPosition(0, closestPoint[0], closestPoint[1], closestPoint[2]) closestFiducial.SetDisplayVisibility(True) self.drawLineBetweenPoints(line, ras, closestPoint) self.set3dViewConernerAnnotation('Distance = ' + "%.2f" % distance + 'mm') else: logging.warning('No fiducials in list!')
def createIntermediateHardenModel(self, model): hardenModel = slicer.mrmlScene.GetNodesByName("SurfaceRegistration_" + model.GetName() + "_hardenCopy_" + str( slicer.app.applicationPid())).GetItemAsObject(0) if hardenModel is None: hardenModel = slicer.vtkMRMLModelNode() hardenPolyData = vtk.vtkPolyData() hardenPolyData.DeepCopy(model.GetPolyData()) hardenModel.SetAndObservePolyData(hardenPolyData) hardenModel.SetName( "SurfaceRegistration_" + model.GetName() + "_hardenCopy_" + str(slicer.app.applicationPid())) if model.GetParentTransformNode(): hardenModel.SetAndObserveTransformNodeID(model.GetParentTransformNode().GetID()) hardenModel.HideFromEditorsOn() slicer.mrmlScene.AddNode(hardenModel) logic = slicer.vtkSlicerTransformLogic() logic.hardenTransform(hardenModel) return hardenModel
def FiducialsToPolyData(self, fiducials, polyData): points = vtk.vtkPoints() n = fiducials.GetNumberOfFiducials() for fiducialIndex in range(0, n): p = [0, 0, 0] fiducials.GetNthFiducialPosition(fiducialIndex, p) points.InsertNextPoint(p) tempPolyData = vtk.vtkPolyData() tempPolyData.SetPoints(points) vertex = vtk.vtkVertexGlyphFilter() vertex.SetInputData(tempPolyData) vertex.Update() polyData.ShallowCopy(vertex.GetOutput())
def PointsToSurfacePolyData( self, inPoints, reverse ): # Create a polydata object from the points pointsPolyData = vtk.vtkPolyData() pointsPolyData.SetPoints( inPoints ) # Create the surface filter from the polydata surfaceFilter = vtk.vtkSurfaceReconstructionFilter() surfaceFilter.SetInputData( pointsPolyData ) surfaceFilter.Update() # Do the contouring filter, and reverse to ensure it works properly contourFilter = vtk.vtkContourFilter() contourFilter.SetValue( 0, 0.0 ) contourFilter.SetInputData( surfaceFilter.GetOutput() ) contourFilter.Update() # Reverse the normals if necessary reverseFilter = vtk.vtkReverseSense() reverseFilter.SetInputData( contourFilter.GetOutput() ) reverseFilter.SetReverseCells( reverse ) reverseFilter.SetReverseNormals( reverse ) reverseFilter.Update() # Reset the scaling to let the surface match the points fiducialBounds = [ 0, 0, 0, 0, 0, 0 ] pointsPolyData.GetBounds( fiducialBounds ) tissueBounds = [ 0, 0, 0, 0, 0, 0 ] reverseFilter.GetOutput().GetBounds( tissueBounds ) scaleX = ( fiducialBounds[1] - fiducialBounds[0] ) / ( tissueBounds[1] - tissueBounds[0] ) scaleY = ( fiducialBounds[3] - fiducialBounds[2] ) / ( tissueBounds[3] - tissueBounds[2] ) scaleZ = ( fiducialBounds[5] - fiducialBounds[4] ) / ( tissueBounds[5] - tissueBounds[4] ) transform = vtk.vtkTransform() transform.Translate( fiducialBounds[0], fiducialBounds[2], fiducialBounds[4] ) transform.Scale( scaleX, scaleY, scaleZ ) transform.Translate( - tissueBounds[0], - tissueBounds[2], - tissueBounds[4] ) transformFilter = vtk.vtkTransformPolyDataFilter() transformFilter.SetInputData( reverseFilter.GetOutput() ) transformFilter.SetTransform( transform ) transformFilter.Update() return transformFilter.GetOutput()
def FiducialsToPolyData(self, fiducials, polyData): points = vtk.vtkPoints() n = fiducials.GetNumberOfFiducials() for fiducialIndex in range( 0, n ): p = [0, 0, 0] fiducials.GetNthFiducialPosition( fiducialIndex, p ) points.InsertNextPoint( p ) tempPolyData = vtk.vtkPolyData() tempPolyData.SetPoints( points ) vertex = vtk.vtkVertexGlyphFilter() vertex.SetInputData( tempPolyData ) vertex.Update() polyData.ShallowCopy( vertex.GetOutput() )
def WriteVTKPoints(self,vtkpoints,OutputFileName): # get data structures to convert to pixel ijk space outnode = self.outputSelector.currentNode() ras2ijk = vtk.vtkMatrix4x4() outnode.GetRASToIJKMatrix(ras2ijk) spacing = outnode.GetSpacing() origin = outnode.GetOrigin() # write in meters MillimeterMeterConversion = .001; # loop over points an store in vtk data structure # write in pixel coordinates scalevtkPoints = vtk.vtkPoints() vtkvertices= vtk.vtkCellArray() for idpoint in range(vtkpoints.GetNumberOfPoints()): currentpoint = vtkpoints.GetPoint(idpoint) ijkpoint = ras2ijk.MultiplyPoint( (currentpoint[0],currentpoint[1],currentpoint[2],1.) ) print 'ijkpoint %d' % idpoint, ijkpoint vtkvertices.InsertNextCell( 1 ); vtkvertices.InsertCellPoint( scalevtkPoints.InsertNextPoint( [ MillimeterMeterConversion * (ijkpoint[0]*spacing[0] + origin[0]) , MillimeterMeterConversion * (ijkpoint[1]*spacing[1] + origin[1]) , MillimeterMeterConversion * (ijkpoint[2]*spacing[2] + origin[2]) ] ) ) #vtkvertices.InsertNextCell( 1 ); vtkvertices.InsertCellPoint( idpoint ) # loop over points an store in vtk data structure scalerasPoints = vtk.vtkPoints() rasvertices= vtk.vtkCellArray() for idpoint in range(vtkpoints.GetNumberOfPoints()): point = MillimeterMeterConversion * numpy.array(vtkpoints.GetPoint(idpoint)) rasvertices.InsertNextCell( 1 ); rasvertices.InsertCellPoint( scalerasPoints.InsertNextPoint(point) ) #rasvertices.InsertNextCell( 1 ); rasvertices.InsertCellPoint( idpoint ) for datapointsmeter,vertexofpoints,typeid in [(scalerasPoints,rasvertices,'ras'),(scalevtkPoints,vtkvertices,'vtk')]: # set polydata polydata = vtk.vtkPolyData() polydata.SetPoints(datapointsmeter) polydata.SetVerts( vertexofpoints ) # write to file print "WriteVTKPoints: writing",OutputFileName polydatawriter = vtk.vtkDataSetWriter() polydatawriter.SetFileName( "%s%s.vtk" % (OutputFileName,typeid )) polydatawriter.SetInput(polydata) polydatawriter.Update()
def handLine(self,whichHand='Left'): """Create a line to show the path from the hand to the table """ handLineName = 'DropLine-%s' % whichHand handLineNode = slicer.util.getNode(handLineName) if not handLineNode: points = vtk.vtkPoints() polyData = vtk.vtkPolyData() polyData.SetPoints(points) lines = vtk.vtkCellArray() polyData.SetLines(lines) linesIDArray = lines.GetData() linesIDArray.Reset() linesIDArray.InsertNextTuple1(0) polygons = vtk.vtkCellArray() polyData.SetPolys( polygons ) idArray = polygons.GetData() idArray.Reset() idArray.InsertNextTuple1(0) for point in ( (0,0,0), (1,1,1) ): pointIndex = points.InsertNextPoint(*point) linesIDArray.InsertNextTuple1(pointIndex) linesIDArray.SetTuple1( 0, linesIDArray.GetNumberOfTuples() - 1 ) lines.SetNumberOfCells(1) # Create handLineNode model node handLineNode = slicer.vtkMRMLModelNode() handLineNode.SetScene(slicer.mrmlScene) handLineNode.SetName("DropLine-%s" % whichHand) handLineNode.SetAndObservePolyData(polyData) # Create display node modelDisplay = slicer.vtkMRMLModelDisplayNode() modelDisplay.SetColor(1,1,0) # yellow modelDisplay.SetScene(slicer.mrmlScene) slicer.mrmlScene.AddNode(modelDisplay) handLineNode.SetAndObserveDisplayNodeID(modelDisplay.GetID()) # Add to slicer.mrmlScene modelDisplay.SetInputPolyData(handLineNode.GetPolyData()) slicer.mrmlScene.AddNode(handLineNode) return handLineNode
def handLine(self, whichHand='Left'): """Create a line to show the path from the hand to the table """ handLineName = 'DropLine-%s' % whichHand handLineNode = slicer.util.getNode(handLineName) if not handLineNode: points = vtk.vtkPoints() polyData = vtk.vtkPolyData() polyData.SetPoints(points) lines = vtk.vtkCellArray() polyData.SetLines(lines) linesIDArray = lines.GetData() linesIDArray.Reset() linesIDArray.InsertNextTuple1(0) polygons = vtk.vtkCellArray() polyData.SetPolys(polygons) idArray = polygons.GetData() idArray.Reset() idArray.InsertNextTuple1(0) for point in ((0, 0, 0), (1, 1, 1)): pointIndex = points.InsertNextPoint(*point) linesIDArray.InsertNextTuple1(pointIndex) linesIDArray.SetTuple1(0, linesIDArray.GetNumberOfTuples() - 1) lines.SetNumberOfCells(1) # Create handLineNode model node handLineNode = slicer.vtkMRMLModelNode() handLineNode.SetScene(slicer.mrmlScene) handLineNode.SetName("DropLine-%s" % whichHand) handLineNode.SetAndObservePolyData(polyData) # Create display node modelDisplay = slicer.vtkMRMLModelDisplayNode() modelDisplay.SetColor(1, 1, 0) # yellow modelDisplay.SetScene(slicer.mrmlScene) slicer.mrmlScene.AddNode(modelDisplay) handLineNode.SetAndObserveDisplayNodeID(modelDisplay.GetID()) # Add to slicer.mrmlScene modelDisplay.SetInputPolyData(handLineNode.GetPolyData()) slicer.mrmlScene.AddNode(handLineNode) return handLineNode
def createPolyData(self): """make an empty single-polyline polydata""" polyData = vtk.vtkPolyData() polyData.SetPoints(self.xyPoints) lines = vtk.vtkCellArray() polyData.SetLines(lines) idArray = lines.GetData() idArray.Reset() idArray.InsertNextTuple1(0) polygons = vtk.vtkCellArray() polyData.SetPolys(polygons) idArray = polygons.GetData() idArray.Reset() idArray.InsertNextTuple1(0) return polyData
def createIntermediateHardenModel(self, model): hardenModel = slicer.mrmlScene.GetNodesByName( "SurfaceRegistration_" + model.GetName() + "_hardenCopy_" + str(slicer.app.applicationPid())).GetItemAsObject(0) if hardenModel is None: hardenModel = slicer.vtkMRMLModelNode() hardenPolyData = vtk.vtkPolyData() hardenPolyData.DeepCopy(model.GetPolyData()) hardenModel.SetAndObservePolyData(hardenPolyData) hardenModel.SetName("SurfaceRegistration_" + model.GetName() + "_hardenCopy_" + str(slicer.app.applicationPid())) if model.GetParentTransformNode(): hardenModel.SetAndObserveTransformNodeID( model.GetParentTransformNode().GetID()) hardenModel.HideFromEditorsOn() slicer.mrmlScene.AddNode(hardenModel) logic = slicer.vtkSlicerTransformLogic() logic.hardenTransform(hardenModel) return hardenModel
def __init__(self, sliceWidget): super(PaintEffectTool, self).__init__(sliceWidget) # create a logic instance to do the non-gui work self.logic = PaintEffectLogic(self.sliceWidget.sliceLogic()) # configuration variables self.delayedPaint = True self.parameterNode = self.editUtil.getParameterNode() self.sphere = not (0 == int( self.parameterNode.GetParameter("PaintEffect,sphere"))) self.smudge = not (0 == int( self.parameterNode.GetParameter("PaintEffect,smudge"))) self.pixelMode = not (0 == int( self.parameterNode.GetParameter("PaintEffect,pixelMode"))) self.radius = float( self.parameterNode.GetParameter("PaintEffect,radius")) # interaction state variables self.position = [0, 0, 0] self.paintCoordinates = [] self.feedbackActors = [] self.lastRadius = 0 # scratch variables self.rasToXY = vtk.vtkMatrix4x4() # initialization self.brush = vtk.vtkPolyData() self.createGlyph(self.brush) self.mapper = vtk.vtkPolyDataMapper2D() self.actor = vtk.vtkActor2D() if vtk.VTK_MAJOR_VERSION <= 5: self.mapper.SetInput(self.brush) else: self.mapper.SetInputData(self.brush) self.actor.SetMapper(self.mapper) self.actor.VisibilityOff() self.renderer.AddActor2D(self.actor) self.actors.append(self.actor) self.processEvent()
def __init__(self): self.controlPointsMarkupNode = None self.curveModelNode = None self.tubeRadius = 5.0 self.tubeResolution = 20 self.numberOfIntermediatePoints = 20 self.curvePoly = vtk.vtkPolyData() self.curvePoints = vtk.vtkPoints() self.curvePoly.SetPoints(self.curvePoints) self.curvePointsLocator = vtk.vtkPointLocator() self.curvePointsLocator.SetDataSet(self.curvePoly) self.interpolationMethod = InterpolationLinear self.pointInterpolationFunction = self.getInterpolatedPointsLinear self.closed = False
def generateResectionVolume(self, fiducialNode, modelNode): if (fiducialNode != None): self.FiducialNode = fiducialNode self.PolyData = vtk.vtkPolyData() self.updatePoints() self.Delaunay = vtk.vtkDelaunay3D() if (vtk.VTK_MAJOR_VERSION <= 5): self.Delaunay.SetInput(self.PolyData) else: self.Delaunay.SetInputData(self.PolyData) self.Delaunay.Update() self.SurfaceFilter = vtk.vtkDataSetSurfaceFilter() self.SurfaceFilter.SetInputConnection( self.Delaunay.GetOutputPort()) self.SurfaceFilter.Update() self.Smoother = vtk.vtkButterflySubdivisionFilter() self.Smoother.SetInputConnection( self.SurfaceFilter.GetOutputPort()) self.Smoother.SetNumberOfSubdivisions(3) self.Smoother.Update() if modelNode.GetDisplayNodeID() == None: modelDisplayNode = slicer.mrmlScene.CreateNodeByClass( "vtkMRMLModelDisplayNode") modelDisplayNode.SetColor(0, 0, 1) # Blue modelDisplayNode.BackfaceCullingOff() modelDisplayNode.SetOpacity(0.3) # Between 0-1, 1 being opaque slicer.mrmlScene.AddNode(modelDisplayNode) modelNode.SetAndObserveDisplayNodeID(modelDisplayNode.GetID()) if (vtk.VTK_MAJOR_VERSION <= 5): modelNode.SetAndObservePolyData(self.Smoother.GetOutput()) else: modelNode.SetPolyDataConnection(self.Smoother.GetOutputPort()) modelNode.Modified() self.tag = self.FiducialNode.AddObserver( 'ModifiedEvent', self.updateResectionVolume)
def createPolyDataFromPointArray(pointArray): """Create vtkPolyData from a numpy array. Performs deep copy.""" from __main__ import vtk, slicer number_of_points = pointArray.shape[0] # Points points = vtk.vtkPoints() points.SetNumberOfPoints(number_of_points) import vtk.util.numpy_support pointArrayDestination = vtk.util.numpy_support.vtk_to_numpy( points.GetData()) pointArrayDestination[:] = pointArray[:] # Vertices vertices = vtk.vtkCellArray() for i in range(number_of_points): vertices.InsertNextCell(1) vertices.InsertCellPoint(i) # PolyData polyData = vtk.vtkPolyData() polyData.SetPoints(points) polyData.SetVerts(vertices) return polyData
def computeSurfaceBetweenLines(self): """ Update model with a surface between base and margin lines. """ numberOfBasePoints = self.baseLine.curvePoints.GetNumberOfPoints() numberOfMarginPoints = self.marginLine.curvePoints.GetNumberOfPoints() if numberOfBasePoints == 0 or numberOfMarginPoints == 0: self.surfaceModelNode.SetAndObservePolyData(None) return boundaryPoints = vtk.vtkPoints() boundaryPoints.DeepCopy(self.baseLine.curvePoints) boundaryPoints.InsertPoints(numberOfBasePoints, numberOfMarginPoints, 0, self.marginLine.curvePoints) # Add a triangle strip between the base and margin lines strips = vtk.vtkCellArray() strips.InsertNextCell(numberOfBasePoints * 2) basePointToMarginPointScale = float(numberOfMarginPoints) / float( numberOfBasePoints) for basePointIndex in range(numberOfBasePoints): strips.InsertCellPoint(basePointIndex) strips.InsertCellPoint( int(numberOfBasePoints + basePointIndex * basePointToMarginPointScale)) clippingSurfacePolyData = vtk.vtkPolyData() clippingSurfacePolyData.SetPoints(boundaryPoints) clippingSurfacePolyData.SetStrips(strips) triangulator = vtk.vtkTriangleFilter() triangulator.SetInputData(clippingSurfacePolyData) triangulator.Update() clippingPolyData = triangulator.GetOutput() self.surfaceModelNode.SetAndObservePolyData(clippingPolyData)