def pathToPoly(self, path, poly): points = vtk.vtkPoints() cellArray = vtk.vtkCellArray() points = vtk.vtkPoints() poly.SetPoints(points) lines = vtk.vtkCellArray() poly.SetLines(lines) linesIDArray = lines.GetData() linesIDArray.Reset() linesIDArray.InsertNextTuple1(0) polygons = vtk.vtkCellArray() poly.SetPolys(polygons) idArray = polygons.GetData() idArray.Reset() idArray.InsertNextTuple1(0) for point in path: pointIndex = points.InsertNextPoint(*point) linesIDArray.InsertNextTuple1(pointIndex) linesIDArray.SetTuple1(0, linesIDArray.GetNumberOfTuples() - 1) lines.SetNumberOfCells(1)
def pathToPoly(self, path, poly): points = vtk.vtkPoints() cellArray = vtk.vtkCellArray() points = vtk.vtkPoints() poly.SetPoints(points) lines = vtk.vtkCellArray() poly.SetLines(lines) linesIDArray = lines.GetData() linesIDArray.Reset() linesIDArray.InsertNextTuple1(0) polygons = vtk.vtkCellArray() poly.SetPolys( polygons ) idArray = polygons.GetData() idArray.Reset() idArray.InsertNextTuple1(0) for point in path: pointIndex = points.InsertNextPoint(*point) linesIDArray.InsertNextTuple1(pointIndex) linesIDArray.SetTuple1( 0, linesIDArray.GetNumberOfTuples() - 1 ) lines.SetNumberOfCells(1)
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 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 nodeToPolyCardinalSpline(self, sourceNode, outputPoly, closed=False): nOfControlPoints = sourceNode.GetNumberOfFiducials() pos = [0.0, 0.0, 0.0] # One spline for each direction. aSplineX = vtk.vtkCardinalSpline() aSplineY = vtk.vtkCardinalSpline() aSplineZ = vtk.vtkCardinalSpline() if closed: aSplineX.ClosedOn() aSplineY.ClosedOn() aSplineZ.ClosedOn() else: aSplineX.ClosedOff() aSplineY.ClosedOff() aSplineZ.ClosedOff() for i in range(0, nOfControlPoints): sourceNode.GetNthFiducialPosition(i, pos) aSplineX.AddPoint(i, pos[0]) aSplineY.AddPoint(i, pos[1]) aSplineZ.AddPoint(i, pos[2]) # Interpolate x, y and z by using the three spline filters and # create new points nInterpolatedPoints = (self.interpResolution+2)*(nOfControlPoints-1) # One section is devided into self.interpResolution segments points = vtk.vtkPoints() r = [0.0, 0.0] aSplineX.GetParametricRange(r) t = r[0] p = 0 tStep = (nOfControlPoints-1.0)/(nInterpolatedPoints-1.0) nOutputPoints = 0 if closed: while t < r[1]+1.0: points.InsertPoint(p, aSplineX.Evaluate(t), aSplineY.Evaluate(t), aSplineZ.Evaluate(t)) t = t + tStep p = p + 1 ## Make sure to close the loop points.InsertPoint(p, aSplineX.Evaluate(r[0]), aSplineY.Evaluate(r[0]), aSplineZ.Evaluate(r[0])) p = p + 1 points.InsertPoint(p, aSplineX.Evaluate(r[0]+tStep), aSplineY.Evaluate(r[0]+tStep), aSplineZ.Evaluate(r[0]+tStep)) nOutputPoints = p + 1 else: while t < r[1]: points.InsertPoint(p, aSplineX.Evaluate(t), aSplineY.Evaluate(t), aSplineZ.Evaluate(t)) t = t + tStep p = p + 1 nOutputPoints = p lines = vtk.vtkCellArray() lines.InsertNextCell(nOutputPoints) for i in range(0, nOutputPoints): lines.InsertCellPoint(i) outputPoly.SetPoints(points) outputPoly.SetLines(lines)
def updateCurve(self): if self.controlPointsMarkupNode and self.curveModelNode: self.curvePoints.Reset() # clear without deallocating memory lines = vtk.vtkCellArray() self.curvePoly.SetLines(lines) if self.controlPointsMarkupNode.GetNumberOfFiducials() >= 2: self.pointInterpolationFunction(self.controlPointsMarkupNode, self.curvePoints) nInterpolatedPoints = self.curvePoints.GetNumberOfPoints() lines.InsertNextCell(nInterpolatedPoints) for i in range(nInterpolatedPoints): lines.InsertCellPoint(i) tubeFilter = vtk.vtkTubeFilter() tubeFilter.SetInputData(self.curvePoly) tubeFilter.SetRadius(self.tubeRadius) tubeFilter.SetNumberOfSides(self.tubeResolution) tubeFilter.SetCapping(not self.closed) # Triangulation is necessary to avoid discontinuous lines # in model/slice intersection display triangles = vtk.vtkTriangleFilter() triangles.SetInputConnection(tubeFilter.GetOutputPort()) triangles.Update() self.curveModelNode.SetAndObservePolyData(triangles.GetOutput()) self.curveModelNode.Modified()
def updateTipModelNode(self, tipModelNode, poly, p0, pe, radius, color, opacity): points = vtk.vtkPoints() cellArray = vtk.vtkCellArray() points.SetNumberOfPoints(2) cellArray.InsertNextCell(2) points.SetPoint(0, p0) cellArray.InsertCellPoint(0) points.SetPoint(1, pe) cellArray.InsertCellPoint(1) poly.Initialize() poly.SetPoints(points) poly.SetLines(cellArray) tubeFilter = vtk.vtkTubeFilter() tubeFilter.SetInputData(poly) tubeFilter.SetRadius(radius) tubeFilter.SetNumberOfSides(20) tubeFilter.CappingOn() tubeFilter.Update() # Sphere represents the locator tip sphere = vtk.vtkSphereSource() sphere.SetRadius(radius * 2.0) sphere.SetCenter(pe) sphere.Update() apd = vtk.vtkAppendPolyData() if vtk.VTK_MAJOR_VERSION <= 5: apd.AddInput(sphere.GetOutput()) apd.AddInput(tubeFilter.GetOutput()) else: apd.AddInputConnection(sphere.GetOutputPort()) apd.AddInputConnection(tubeFilter.GetOutputPort()) apd.Update() tipModelNode.SetAndObservePolyData(apd.GetOutput()) tipModelNode.Modified() tipDispID = tipModelNode.GetDisplayNodeID() if tipDispID == None: tipDispNode = self.scene.AddNewNodeByClass( 'vtkMRMLModelDisplayNode') tipDispNode.SetScene(self.scene) tipModelNode.SetAndObserveDisplayNodeID(tipDispNode.GetID()) tipDispID = tipModelNode.GetDisplayNodeID() tipDispNode = self.scene.GetNodeByID(tipDispID) prevState = tipDispNode.StartModify() tipDispNode.SetColor(color) tipDispNode.SetOpacity(opacity) tipDispNode.SliceIntersectionVisibilityOn() tipDispNode.SetSliceDisplayModeToIntersection() tipDispNode.EndModify(prevState)
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 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 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 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 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 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 createGlyph(self, polyData): """ create a brush circle of the right radius in XY space - assume uniform scaling between XY and RAS which is enforced by the view interactors """ sliceNode = self.sliceWidget.sliceLogic().GetSliceNode() self.rasToXY.DeepCopy(sliceNode.GetXYToRAS()) self.rasToXY.Invert() maximum, maxIndex = 0,0 for index in range(3): if abs(self.rasToXY.GetElement(0, index)) > maximum: maximum = abs(self.rasToXY.GetElement(0, index)) maxIndex = index point = [0, 0, 0, 0] point[maxIndex] = self.radius xyRadius = self.rasToXY.MultiplyPoint(point) import math xyRadius = math.sqrt( xyRadius[0]**2 + xyRadius[1]**2 + xyRadius[2]**2 ) if self.pixelMode: xyRadius = 0.01 # make a circle paint brush points = vtk.vtkPoints() lines = vtk.vtkCellArray() polyData.SetPoints(points) polyData.SetLines(lines) PI = 3.1415926 TWOPI = PI * 2 PIoverSIXTEEN = PI / 16 prevPoint = -1 firstPoint = -1 angle = 0 while angle <= TWOPI: x = xyRadius * math.cos(angle) y = xyRadius * math.sin(angle) p = points.InsertNextPoint( x, y, 0 ) if prevPoint != -1: idList = vtk.vtkIdList() idList.InsertNextId(prevPoint) idList.InsertNextId(p) polyData.InsertNextCell( vtk.VTK_LINE, idList ) prevPoint = p if firstPoint == -1: firstPoint = p angle = angle + PIoverSIXTEEN # make the last line in the circle idList = vtk.vtkIdList() idList.InsertNextId(p) idList.InsertNextId(firstPoint) polyData.InsertNextCell( vtk.VTK_LINE, idList )
def createGlyph(self, polyData): """ create a brush circle of the right radius in XY space - assume uniform scaling between XY and RAS which is enforced by the view interactors """ sliceNode = self.sliceWidget.sliceLogic().GetSliceNode() self.rasToXY.DeepCopy(sliceNode.GetXYToRAS()) self.rasToXY.Invert() maximum, maxIndex = 0, 0 for index in range(3): if abs(self.rasToXY.GetElement(0, index)) > maximum: maximum = abs(self.rasToXY.GetElement(0, index)) maxIndex = index point = [0, 0, 0, 0] point[maxIndex] = self.radius xyRadius = self.rasToXY.MultiplyPoint(point) import math xyRadius = math.sqrt(xyRadius[0]**2 + xyRadius[1]**2 + xyRadius[2]**2) if self.pixelMode: xyRadius = 0.01 # make a circle paint brush points = vtk.vtkPoints() lines = vtk.vtkCellArray() polyData.SetPoints(points) polyData.SetLines(lines) PI = 3.1415926 TWOPI = PI * 2 PIoverSIXTEEN = PI / 16 prevPoint = -1 firstPoint = -1 angle = 0 while angle <= TWOPI: x = xyRadius * math.cos(angle) y = xyRadius * math.sin(angle) p = points.InsertNextPoint(x, y, 0) if prevPoint != -1: idList = vtk.vtkIdList() idList.InsertNextId(prevPoint) idList.InsertNextId(p) polyData.InsertNextCell(vtk.VTK_LINE, idList) prevPoint = p if firstPoint == -1: firstPoint = p angle = angle + PIoverSIXTEEN # make the last line in the circle idList = vtk.vtkIdList() idList.InsertNextId(p) idList.InsertNextId(firstPoint) polyData.InsertNextCell(vtk.VTK_LINE, idList)
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 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 drawLineBetweenPoints(self, lineModel, point1, point2): # Create a vtkPoints object and store the points in it points = vtk.vtkPoints() points.InsertNextPoint(point1) points.InsertNextPoint(point2) # Create line line = vtk.vtkLine() line.GetPointIds().SetId(0,0) line.GetPointIds().SetId(1,1) lineCellArray = vtk.vtkCellArray() lineCellArray.InsertNextCell(line) # Update model data lineModel.GetPolyData().SetPoints(points) lineModel.GetPolyData().SetLines(lineCellArray)
def updatePoints(self): points = vtk.vtkPoints() cellArray = vtk.vtkCellArray() numberOfPoints = self.FiducialNode.GetNumberOfFiducials() points.SetNumberOfPoints(numberOfPoints) new_coord = [0.0, 0.0, 0.0] for i in range(numberOfPoints): self.FiducialNode.GetNthFiducialPosition(i, new_coord) points.SetPoint(i, new_coord) cellArray.InsertNextCell(numberOfPoints) for i in range(numberOfPoints): cellArray.InsertCellPoint(i) self.PolyData.SetLines(cellArray) self.PolyData.SetPoints(points)
def updatePoints(self): points = vtk.vtkPoints() cellArray = vtk.vtkCellArray() numberOfPoints = self.FiducialNode.GetNumberOfFiducials() points.SetNumberOfPoints(numberOfPoints) new_coord = [0.0, 0.0, 0.0] for i in range(numberOfPoints): self.FiducialNode.GetNthFiducialPosition(i,new_coord) points.SetPoint(i, new_coord) cellArray.InsertNextCell(numberOfPoints) for i in range(numberOfPoints): cellArray.InsertCellPoint(i) self.PolyData.SetLines(cellArray) self.PolyData.SetPoints(points)
def nodeToPoly(self, sourceNode, outputPoly, closed=False): points = vtk.vtkPoints() cellArray = vtk.vtkCellArray() nOfControlPoints = sourceNode.GetNumberOfFiducials() pos = [0.0, 0.0, 0.0] posStartEnd = [0.0, 0.0, 0.0] offset = 0 if not closed: points.SetNumberOfPoints(nOfControlPoints) cellArray.InsertNextCell(nOfControlPoints) else: posStart = [0.0, 0.0, 0.0] posEnd = [0.0, 0.0, 0.0] sourceNode.GetNthFiducialPosition(0, posStart) sourceNode.GetNthFiducialPosition(nOfControlPoints - 1, posEnd) posStartEnd[0] = (posStart[0] + posEnd[0]) / 2.0 posStartEnd[1] = (posStart[1] + posEnd[1]) / 2.0 posStartEnd[2] = (posStart[2] + posEnd[2]) / 2.0 points.SetNumberOfPoints(nOfControlPoints + 2) cellArray.InsertNextCell(nOfControlPoints + 2) points.SetPoint(0, posStartEnd) cellArray.InsertCellPoint(0) offset = 1 for i in range(nOfControlPoints): sourceNode.GetNthFiducialPosition(i, pos) points.SetPoint(offset + i, pos) cellArray.InsertCellPoint(offset + i) offset = offset + nOfControlPoints if closed: points.SetPoint(offset, posStartEnd) cellArray.InsertCellPoint(offset) outputPoly.Initialize() outputPoly.SetPoints(points) outputPoly.SetLines(cellArray)
def nodeToPoly(self, sourceNode, outputPoly, closed=False): points = vtk.vtkPoints() cellArray = vtk.vtkCellArray() nOfControlPoints = sourceNode.GetNumberOfFiducials() pos = [0.0, 0.0, 0.0] posStartEnd = [0.0, 0.0, 0.0] offset = 0 if not closed: points.SetNumberOfPoints(nOfControlPoints) cellArray.InsertNextCell(nOfControlPoints) else: posStart = [0.0, 0.0, 0.0] posEnd = [0.0, 0.0, 0.0] sourceNode.GetNthFiducialPosition(0,posStart) sourceNode.GetNthFiducialPosition(nOfControlPoints-1,posEnd) posStartEnd[0] = (posStart[0]+posEnd[0])/2.0 posStartEnd[1] = (posStart[1]+posEnd[1])/2.0 posStartEnd[2] = (posStart[2]+posEnd[2])/2.0 points.SetNumberOfPoints(nOfControlPoints+2) cellArray.InsertNextCell(nOfControlPoints+2) points.SetPoint(0,posStartEnd) cellArray.InsertCellPoint(0) offset = 1 for i in range(nOfControlPoints): sourceNode.GetNthFiducialPosition(i,pos) points.SetPoint(offset+i,pos) cellArray.InsertCellPoint(offset+i) offset = offset + nOfControlPoints if closed: points.SetPoint(offset,posStartEnd) cellArray.InsertCellPoint(offset) outputPoly.Initialize() outputPoly.SetPoints(points) outputPoly.SetLines(cellArray)
def undoPostProcessing(self): # 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.recordedDataBufferDefault)): self.addPointToPolyData(newPolyData, self.recordedDataBufferDefault[idx][0:3]) # Update recorded model and buffer self.recordedModelNode.GetPolyData().DeepCopy(newPolyData) self.recordedModelNode.GetPolyData().Modified() self.recordedDataBuffer = self.recordedDataBufferDefault
def nodesToSpline(self, sourceNode, outputPoly): numControlPoints = sourceNode.GetNumberOfFiducials() pos = [0.0, 0.0, 0.0] #Three independent splines for x, y, and z xSpline = vtk.vtkCardinalSpline() ySpline = vtk.vtkCardinalSpline() zSpline = vtk.vtkCardinalSpline() xSpline.ClosedOff() ySpline.ClosedOff() zSpline.ClosedOff() for i in range(0, numControlPoints): sourceNode.GetNthFiducialPosition(i, pos) xSpline.AddPoint(i, pos[0]) ySpline.AddPoint(i, pos[1]) zSpline.AddPoint(i, pos[2]) #There will be a self.resolution number of intermediate points interpolatedPoints = (self.Resolution + 2) * (numControlPoints - 1) points = vtk.vtkPoints() r = [0.0, 0.0] xSpline.GetParametricRange(r) t = r[0] p = 0 tStep = (numControlPoints - 1.0) / (interpolatedPoints - 1.0) numOutputPoints = 0 while t < r[1]: points.InsertPoint(p, xSpline.Evaluate(t), ySpline.Evaluate(t), zSpline.Evaluate(t)) t = t + tStep p = p + 1 numOutputPoints = p lines = vtk.vtkCellArray() lines.InsertNextCell(numOutputPoints) for i in range(0, numOutputPoints): lines.InsertCellPoint(i) outputPoly.SetPoints(points) outputPoly.SetLines(lines)
def nodesToLinear(self, sourceNode, outputPoly): points = vtk.vtkPoints() cells = vtk.vtkCellArray() numControlPoints = sourceNode.GetNumberOfFiducials() pos = [0.0, 0.0, 0.0] offset = 0 points.SetNumberOfPoints(numControlPoints) cells.InsertNextCell(numControlPoints) for i in range(numControlPoints): sourceNode.GetNthFiducialPosition(i, pos) points.SetPoint(offset + i, pos) cells.InsertCellPoint(offset + i) offset = offset + numControlPoints outputPoly.Initialize() outputPoly.SetPoints(points) outputPoly.SetLines(cells)
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)
def __init__(self): # Member variables self.outputLabels = None self.recordedDataBuffer = [] self.record = False self.reset = False self.outputObserverTag = -1 self.rigidBodyToTrackerTransformNode = None self.measurementToMeasurerTransformNode = None self.parametersToMeasurerTransformNode = None self.plus = None self.m = vtk.vtkMatrix4x4() self.direction = -1 self.ras = [0, 0, 0, 1] self.d = 0.0 self.snr = 0 self.total = 0 self.LABEL_UPDATE_RATE = 10 self.labelUpdateCount = 0 self.snrThreshold = 40 self.distanceMaximumValue = 1000.0 self.distanceMinimumValue = 0.0 self.lensMaxDistance = 0.0 self.lensMinDistance = 0.0 self.normalizingConstant = 0.0 self.min = -1000.0 self.addColours = True import Viewpoint # Viewpoint self.viewpointLogic = Viewpoint.ViewpointLogic() self.stopWatch = None # StopWatch # Create style sheets self.errorStyleSheet = "QLabel { color : #FF0000; \ font: bold 14px}" self.defaultStyleSheet = "QLabel { color : #000000; \ font: bold 14px}" # Create rainbow colour table self.colorTable=slicer.vtkMRMLColorTableNode() self.colorTable.SetTypeToRainbow () # Add MeasurementPoint self.measurementPointMarkupsFiducialNode = slicer.util.getNode('MeasurementPoint') if not self.measurementPointMarkupsFiducialNode: self.measurementPointMarkupsFiducialNode = slicer.vtkMRMLMarkupsFiducialNode() self.measurementPointMarkupsFiducialNode.SetName('MeasurementPoint') self.measurementPointMarkupsFiducialNode.AddFiducial(0, 0, 0) self.measurementPointMarkupsFiducialNode.SetNthFiducialLabel(0, '') slicer.mrmlScene.AddNode(self.measurementPointMarkupsFiducialNode) self.measurementPointMarkupsFiducialNode.GetDisplayNode().SetGlyphScale(2.0) self.measurementPointMarkupsFiducialNode.GetDisplayNode().SetGlyphType(13) # Sphere3D self.measurementPointMarkupsFiducialNode.GetDisplayNode().SetSelectedColor(1, 0, 0) # Add RecordedModel 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) # Set up coloured scalars colorArray = vtk.vtkDoubleArray() colorArray.SetNumberOfComponents(4) colorArray.SetName('Colors') self.recordedModelNode.GetPolyData().GetPointData().SetScalars(colorArray) # Create share directory self.pathToCreatedSaveDir = self.createShareDirectory() # Post-Processing default (for undo) self.recordedDataBufferDefault = []
def onApplyThreshold(self): min,max = self.getDistanceBound() newPoints = vtk.vtkPoints() newLines = vtk.vtkCellArray() newTensors = vtk.vtkFloatArray() newTensors.SetNumberOfComponents(9) newScalars = vtk.vtkFloatArray() points = self.inputPolyData.GetPoints() lines = self.inputPolyData.GetLines() tensors = self.inputPolyData.GetPointData().GetTensors() lines.InitTraversal() newId = 0 for length in self.distanceTable: if length<=self.thresholdMax.value and length>=self.thresholdMin.value: ids = vtk.vtkIdList() lines.GetNextCell(ids) newLine = vtk.vtkPolyLine() #print(ids.GetNumberOfIds()) newLine.GetPointIds().SetNumberOfIds(ids.GetNumberOfIds()) #print(((length-min)/(max-min))*100) for i in range(ids.GetNumberOfIds()): newPoints.InsertNextPoint(points.GetPoint(ids.GetId(i))) newLine.GetPointIds().SetId(i,newId) newScalars.InsertNextValue(((length-min)/(max-min))) newId += 1 tensorValue = [0]*9 if(tensors != None): for j in range(9): tensorValue[j] = tensors.GetComponent(ids.GetId(i),j) newTensors.InsertNextTuple(tensorValue) newLines.InsertNextCell(newLine) self.outputPolyData = vtk.vtkPolyData() self.outputPolyData.SetPoints(newPoints) self.outputPolyData.SetLines(newLines) self.outputPolyData.GetPointData().SetTensors(newTensors) newScalars.SetName("Length") self.outputPolyData.GetPointData().AddArray(newScalars) self.outputNode.SetAndObservePolyData(self.outputPolyData) chartViewNodes = slicer.mrmlScene.GetNodesByClass('vtkMRMLChartViewNode') chartViewNodes.InitTraversal() chartViewNode = chartViewNodes.GetNextItemAsObject() arrayNode = slicer.mrmlScene.AddNode(slicer.vtkMRMLDoubleArrayNode()) array = arrayNode.GetArray() array.SetNumberOfTuples(10) step = (max-min)/10 interMin = min interMax = min+step for i in range(10): numberOfFibers = 0 for length in self.distanceTable: if length<=interMax and length>=interMin and length<=self.thresholdMax.value and length>=self.thresholdMin.value: numberOfFibers += 1 array.SetComponent(i,0,(interMin+interMax)/2) array.SetComponent(i,1,numberOfFibers) array.SetComponent(i,2,0) interMin += step interMax += step chartNode = slicer.mrmlScene.AddNode(slicer.vtkMRMLChartNode()) chartNode.AddArray("Fiber Length",arrayNode.GetID()) chartViewNode.SetChartNodeID(chartNode.GetID()) chartNode.SetProperty('default', 'title', 'Length Distribution') chartNode.SetProperty('default', 'xAxisLabel', 'Length') chartNode.SetProperty('default', 'yAxisLabel', 'Distribution') chartNode.SetProperty('default', 'type', 'Bar')
def __init__(self, path, fiducialListNode): fids = fiducialListNode scene = slicer.mrmlScene 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 path: pointIndex = points.InsertNextPoint(*point) linesIDArray.InsertNextTuple1(pointIndex) linesIDArray.SetTuple1(0, linesIDArray.GetNumberOfTuples() - 1) lines.SetNumberOfCells(1) # Create model node model = slicer.vtkMRMLModelNode() model.SetScene(scene) model.SetName(scene.GenerateUniqueName("Path-%s" % fids.GetName())) model.SetAndObservePolyData(polyData) # Create display node modelDisplay = slicer.vtkMRMLModelDisplayNode() modelDisplay.SetColor(1, 1, 0) # yellow modelDisplay.SetScene(scene) scene.AddNode(modelDisplay) model.SetAndObserveDisplayNodeID(modelDisplay.GetID()) # Add to scene modelDisplay.SetInputPolyData(model.GetPolyData()) scene.AddNode(model) # Camera cursor sphere = vtk.vtkSphereSource() sphere.Update() # Create model node cursor = slicer.vtkMRMLModelNode() cursor.SetScene(scene) cursor.SetName(scene.GenerateUniqueName("Cursor-%s" % fids.GetName())) cursor.SetAndObservePolyData(sphere.GetOutput()) # Create display node cursorModelDisplay = slicer.vtkMRMLModelDisplayNode() cursorModelDisplay.SetColor(1, 0, 0) # red cursorModelDisplay.SetScene(scene) scene.AddNode(cursorModelDisplay) cursor.SetAndObserveDisplayNodeID(cursorModelDisplay.GetID()) # Add to scene cursorModelDisplay.SetInputPolyData(sphere.GetOutput()) scene.AddNode(cursor) # Create transform node transform = slicer.vtkMRMLLinearTransformNode() transform.SetName( scene.GenerateUniqueName("Transform-%s" % fids.GetName())) scene.AddNode(transform) cursor.SetAndObserveTransformNodeID(transform.GetID()) self.transform = transform
def __init__(self, path, fiducialListNode): fids = fiducialListNode scene = slicer.mrmlScene 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 path: pointIndex = points.InsertNextPoint(*point) linesIDArray.InsertNextTuple1(pointIndex) linesIDArray.SetTuple1( 0, linesIDArray.GetNumberOfTuples() - 1 ) lines.SetNumberOfCells(1) # Create model node model = slicer.vtkMRMLModelNode() model.SetScene(scene) model.SetName(scene.GenerateUniqueName("Path-%s" % fids.GetName())) model.SetAndObservePolyData(polyData) # Create display node modelDisplay = slicer.vtkMRMLModelDisplayNode() modelDisplay.SetColor(1,1,0) # yellow modelDisplay.SetScene(scene) scene.AddNode(modelDisplay) model.SetAndObserveDisplayNodeID(modelDisplay.GetID()) # Add to scene modelDisplay.SetInputPolyData(model.GetPolyData()) scene.AddNode(model) # Camera cursor sphere = vtk.vtkSphereSource() sphere.Update() # Create model node cursor = slicer.vtkMRMLModelNode() cursor.SetScene(scene) cursor.SetName(scene.GenerateUniqueName("Cursor-%s" % fids.GetName())) cursor.SetAndObservePolyData(sphere.GetOutput()) # Create display node cursorModelDisplay = slicer.vtkMRMLModelDisplayNode() cursorModelDisplay.SetColor(1,0,0) # red cursorModelDisplay.SetScene(scene) scene.AddNode(cursorModelDisplay) cursor.SetAndObserveDisplayNodeID(cursorModelDisplay.GetID()) # Add to scene cursorModelDisplay.SetInputPolyData(sphere.GetOutput()) scene.AddNode(cursor) # Create transform node transform = slicer.vtkMRMLLinearTransformNode() transform.SetName(scene.GenerateUniqueName("Transform-%s" % fids.GetName())) scene.AddNode(transform) cursor.SetAndObserveTransformNodeID(transform.GetID()) self.transform = transform
def tracts_to_vtkPolyData64(tracts, tracts_data={}, lines_indices=None): # if isinstance(tracts, Tractography): tracts_data = tracts.tracts_data() tracts = tracts.tracts() lengths = [len(p) for p in tracts] line_starts = ns.numpy.r_[0, ns.numpy.cumsum(lengths)] if lines_indices is None: lines_indices = [ ns.numpy.arange(length) + line_start for length, line_start in izip(lengths, line_starts) ] ids = ns.numpy.hstack([ ns.numpy.r_[c[0], c[1]] for c in izip(lengths, lines_indices) ]) ids=np.int64(ids) vtk_ids = ns.numpy_to_vtkIdTypeArray(ids, deep=True) cell_array = vtk.vtkCellArray() cell_array.SetCells(len(tracts), vtk_ids) points = ns.numpy.vstack(tracts).astype( ns.get_vtk_to_numpy_typemap()[vtk.VTK_DOUBLE] ) points_array = ns.numpy_to_vtk(points, deep=True) poly_data = vtk.vtkPolyData() vtk_points = vtk.vtkPoints() vtk_points.SetData(points_array) poly_data.SetPoints(vtk_points) poly_data.SetLines(cell_array) saved_keys = set() for key, value in tracts_data.items(): if key in saved_keys: continue if key.startswith('Active'): saved_keys.add(value) name = value value = tracts_data[value] else: name = key if len(value) == len(tracts): if value[0].ndim == 1: value_ = ns.numpy.hstack(value)[:, None] else: value_ = ns.numpy.vstack(value) elif len(value) == len(points): value_ = value else: raise ValueError( "Data in %s does not have the correct number of items") vtk_value = ns.numpy_to_vtk(np.ascontiguousarray(value_), deep=True) vtk_value.SetName(name) if key == 'ActiveScalars' or key == 'Scalars_': poly_data.GetPointData().SetScalars(vtk_value) elif key == 'ActiveVectors' or key == 'Vectors_': poly_data.GetPointData().SetVectors(vtk_value) elif key == 'ActiveTensors' or key == 'Tensors_': poly_data.GetPointData().SetTensors(vtk_value) else: poly_data.GetPointData().AddArray(vtk_value) poly_data.BuildCells() return poly_data
def nodeToPolyCardinalSpline(self, sourceNode, outputPoly, closed=False): nOfControlPoints = sourceNode.GetNumberOfFiducials() pos = [0.0, 0.0, 0.0] # One spline for each direction. aSplineX = vtk.vtkCardinalSpline() aSplineY = vtk.vtkCardinalSpline() aSplineZ = vtk.vtkCardinalSpline() if closed: aSplineX.ClosedOn() aSplineY.ClosedOn() aSplineZ.ClosedOn() else: aSplineX.ClosedOff() aSplineY.ClosedOff() aSplineZ.ClosedOff() for i in range(0, nOfControlPoints): sourceNode.GetNthFiducialPosition(i, pos) aSplineX.AddPoint(i, pos[0]) aSplineY.AddPoint(i, pos[1]) aSplineZ.AddPoint(i, pos[2]) # Interpolate x, y and z by using the three spline filters and # create new points nInterpolatedPoints = (self.interpResolution + 2) * (nOfControlPoints - 1) # One section is devided into self.interpResolution segments points = vtk.vtkPoints() r = [0.0, 0.0] aSplineX.GetParametricRange(r) t = r[0] p = 0 tStep = (nOfControlPoints - 1.0) / (nInterpolatedPoints - 1.0) nOutputPoints = 0 if closed: while t < r[1] + 1.0: points.InsertPoint(p, aSplineX.Evaluate(t), aSplineY.Evaluate(t), aSplineZ.Evaluate(t)) t = t + tStep p = p + 1 ## Make sure to close the loop points.InsertPoint(p, aSplineX.Evaluate(r[0]), aSplineY.Evaluate(r[0]), aSplineZ.Evaluate(r[0])) p = p + 1 points.InsertPoint(p, aSplineX.Evaluate(r[0] + tStep), aSplineY.Evaluate(r[0] + tStep), aSplineZ.Evaluate(r[0] + tStep)) nOutputPoints = p + 1 else: while t < r[1]: points.InsertPoint(p, aSplineX.Evaluate(t), aSplineY.Evaluate(t), aSplineZ.Evaluate(t)) t = t + tStep p = p + 1 nOutputPoints = p lines = vtk.vtkCellArray() lines.InsertNextCell(nOutputPoints) for i in range(0, nOutputPoints): lines.InsertCellPoint(i) outputPoly.SetPoints(points) outputPoly.SetLines(lines)
def tracts_to_vtkPolyData64(tracts, tracts_data={}, lines_indices=None): # if isinstance(tracts, Tractography): tracts_data = tracts.tracts_data() tracts = tracts.tracts() lengths = [len(p) for p in tracts] line_starts = ns.numpy.r_[0, ns.numpy.cumsum(lengths)] if lines_indices is None: lines_indices = [ ns.numpy.arange(length) + line_start for length, line_start in izip(lengths, line_starts) ] ids = ns.numpy.hstack( [ns.numpy.r_[c[0], c[1]] for c in izip(lengths, lines_indices)]) ids = np.int64(ids) vtk_ids = ns.numpy_to_vtkIdTypeArray(ids, deep=True) cell_array = vtk.vtkCellArray() cell_array.SetCells(len(tracts), vtk_ids) points = ns.numpy.vstack(tracts).astype( ns.get_vtk_to_numpy_typemap()[vtk.VTK_DOUBLE]) points_array = ns.numpy_to_vtk(points, deep=True) poly_data = vtk.vtkPolyData() vtk_points = vtk.vtkPoints() vtk_points.SetData(points_array) poly_data.SetPoints(vtk_points) poly_data.SetLines(cell_array) saved_keys = set() for key, value in tracts_data.items(): if key in saved_keys: continue if key.startswith('Active'): saved_keys.add(value) name = value value = tracts_data[value] else: name = key if len(value) == len(tracts): if value[0].ndim == 1: value_ = ns.numpy.hstack(value)[:, None] else: value_ = ns.numpy.vstack(value) elif len(value) == len(points): value_ = value else: raise ValueError( "Data in %s does not have the correct number of items") vtk_value = ns.numpy_to_vtk(np.ascontiguousarray(value_), deep=True) vtk_value.SetName(name) if key == 'ActiveScalars' or key == 'Scalars_': poly_data.GetPointData().SetScalars(vtk_value) elif key == 'ActiveVectors' or key == 'Vectors_': poly_data.GetPointData().SetVectors(vtk_value) elif key == 'ActiveTensors' or key == 'Tensors_': poly_data.GetPointData().SetTensors(vtk_value) else: poly_data.GetPointData().AddArray(vtk_value) poly_data.BuildCells() return poly_data
def createTumorFromMarkups(self): logging.debug("createTumorFromMarkups") # self.tumorMarkups_Needle.SetDisplayVisibility(0) # Create polydata point set from markup points points = vtk.vtkPoints() cellArray = vtk.vtkCellArray() numberOfPoints = self.tumorMarkups_Needle.GetNumberOfFiducials() if numberOfPoints > 0: self.deleteLastFiducialButton.setEnabled(True) self.deleteAllFiducialsButton.setEnabled(True) self.deleteLastFiducialDuringNavigationButton.setEnabled(True) # Surface generation algorithms behave unpredictably when there are not enough points # return if there are very few points if numberOfPoints < 1: return points.SetNumberOfPoints(numberOfPoints) new_coord = [0.0, 0.0, 0.0] for i in range(numberOfPoints): self.tumorMarkups_Needle.GetNthFiducialPosition(i, new_coord) points.SetPoint(i, new_coord) cellArray.InsertNextCell(numberOfPoints) for i in range(numberOfPoints): cellArray.InsertCellPoint(i) pointPolyData = vtk.vtkPolyData() pointPolyData.SetLines(cellArray) pointPolyData.SetPoints(points) delaunay = vtk.vtkDelaunay3D() if numberOfPoints < 10: logging.debug("use glyphs") sphere = vtk.vtkCubeSource() glyph = vtk.vtkGlyph3D() glyph.SetInputData(pointPolyData) glyph.SetSourceConnection(sphere.GetOutputPort()) # glyph.SetVectorModeToUseNormal() # glyph.SetScaleModeToScaleByVector() # glyph.SetScaleFactor(0.25) delaunay.SetInputConnection(glyph.GetOutputPort()) else: delaunay.SetInputData(pointPolyData) surfaceFilter = vtk.vtkDataSetSurfaceFilter() surfaceFilter.SetInputConnection(delaunay.GetOutputPort()) smoother = vtk.vtkButterflySubdivisionFilter() smoother.SetInputConnection(surfaceFilter.GetOutputPort()) smoother.SetNumberOfSubdivisions(3) smoother.Update() forceConvexShape = True if forceConvexShape == True: delaunaySmooth = vtk.vtkDelaunay3D() delaunaySmooth.SetInputData(smoother.GetOutput()) delaunaySmooth.Update() smoothSurfaceFilter = vtk.vtkDataSetSurfaceFilter() smoothSurfaceFilter.SetInputConnection(delaunaySmooth.GetOutputPort()) self.tumorModel_Needle.SetPolyDataConnection(smoothSurfaceFilter.GetOutputPort()) else: self.tumorModel_Needle.SetPolyDataConnection(smoother.GetOutputPort()) self.tumorModel_Needle.Modified()
def updateModelFromMarkup(self, inputMarkup, outputModel): """ Update model to enclose all points in the input markup list """ # Delaunay triangulation is robust and creates nice smooth surfaces from a small number of points, # however it can only generate convex surfaces robustly. useDelaunay = True # Create polydata point set from markup points points = vtk.vtkPoints() cellArray = vtk.vtkCellArray() numberOfPoints = inputMarkup.GetNumberOfFiducials() # Surface generation algorithms behave unpredictably when there are not enough points # return if there are very few points if useDelaunay: if numberOfPoints < 3: return else: if numberOfPoints < 10: return points.SetNumberOfPoints(numberOfPoints) new_coord = [0.0, 0.0, 0.0] for i in range(numberOfPoints): inputMarkup.GetNthFiducialPosition(i, new_coord) points.SetPoint(i, new_coord) cellArray.InsertNextCell(numberOfPoints) for i in range(numberOfPoints): cellArray.InsertCellPoint(i) pointPolyData = vtk.vtkPolyData() pointPolyData.SetLines(cellArray) pointPolyData.SetPoints(points) # Create surface from point set if useDelaunay: delaunay = vtk.vtkDelaunay3D() delaunay.SetInputData(pointPolyData) surfaceFilter = vtk.vtkDataSetSurfaceFilter() surfaceFilter.SetInputConnection(delaunay.GetOutputPort()) smoother = vtk.vtkButterflySubdivisionFilter() smoother.SetInputConnection(surfaceFilter.GetOutputPort()) smoother.SetNumberOfSubdivisions(3) smoother.Update() outputModel.SetPolyDataConnection(smoother.GetOutputPort()) else: surf = vtk.vtkSurfaceReconstructionFilter() surf.SetInputData(pointPolyData) surf.SetNeighborhoodSize(20) surf.SetSampleSpacing( 80 ) # lower value follows the small details more closely but more dense pointset is needed as input cf = vtk.vtkContourFilter() cf.SetInputConnection(surf.GetOutputPort()) cf.SetValue(0, 0.0) # Sometimes the contouring algorithm can create a volume whose gradient # vector and ordering of polygon (using the right hand rule) are # inconsistent. vtkReverseSense cures this problem. reverse = vtk.vtkReverseSense() reverse.SetInputConnection(cf.GetOutputPort()) reverse.ReverseCellsOff() reverse.ReverseNormalsOff() outputModel.SetPolyDataConnection(reverse.GetOutputPort()) # Create default model display node if does not exist yet if not outputModel.GetDisplayNode(): modelDisplayNode = slicer.mrmlScene.CreateNodeByClass( "vtkMRMLModelDisplayNode") modelDisplayNode.SetColor(0, 0, 1) # Blue modelDisplayNode.BackfaceCullingOff() modelDisplayNode.SliceIntersectionVisibilityOn() modelDisplayNode.SetOpacity(0.3) # Between 0-1, 1 being opaque slicer.mrmlScene.AddNode(modelDisplayNode) outputModel.SetAndObserveDisplayNodeID(modelDisplayNode.GetID()) outputModel.GetDisplayNode().SliceIntersectionVisibilityOn() outputModel.Modified()
def createTumorFromMarkups(self): logging.debug('createTumorFromMarkups') #self.tumorMarkups_Needle.SetDisplayVisibility(0) # Create polydata point set from markup points points = vtk.vtkPoints() cellArray = vtk.vtkCellArray() numberOfPoints = self.tumorMarkups_Needle.GetNumberOfFiducials() if numberOfPoints > 0: self.deleteLastFiducialButton.setEnabled(True) self.deleteAllFiducialsButton.setEnabled(True) self.deleteLastFiducialDuringNavigationButton.setEnabled(True) # Surface generation algorithms behave unpredictably when there are not enough points # return if there are very few points if numberOfPoints < 1: return points.SetNumberOfPoints(numberOfPoints) new_coord = [0.0, 0.0, 0.0] for i in range(numberOfPoints): self.tumorMarkups_Needle.GetNthFiducialPosition(i, new_coord) points.SetPoint(i, new_coord) cellArray.InsertNextCell(numberOfPoints) for i in range(numberOfPoints): cellArray.InsertCellPoint(i) pointPolyData = vtk.vtkPolyData() pointPolyData.SetLines(cellArray) pointPolyData.SetPoints(points) delaunay = vtk.vtkDelaunay3D() if numberOfPoints < 10: logging.debug("use glyphs") sphere = vtk.vtkCubeSource() glyph = vtk.vtkGlyph3D() glyph.SetInputData(pointPolyData) glyph.SetSourceConnection(sphere.GetOutputPort()) #glyph.SetVectorModeToUseNormal() #glyph.SetScaleModeToScaleByVector() #glyph.SetScaleFactor(0.25) delaunay.SetInputConnection(glyph.GetOutputPort()) else: delaunay.SetInputData(pointPolyData) surfaceFilter = vtk.vtkDataSetSurfaceFilter() surfaceFilter.SetInputConnection(delaunay.GetOutputPort()) smoother = vtk.vtkButterflySubdivisionFilter() smoother.SetInputConnection(surfaceFilter.GetOutputPort()) smoother.SetNumberOfSubdivisions(3) smoother.Update() forceConvexShape = True if (forceConvexShape == True): delaunaySmooth = vtk.vtkDelaunay3D() delaunaySmooth.SetInputData(smoother.GetOutput()) delaunaySmooth.Update() smoothSurfaceFilter = vtk.vtkDataSetSurfaceFilter() smoothSurfaceFilter.SetInputConnection( delaunaySmooth.GetOutputPort()) self.tumorModel_Needle.SetPolyDataConnection( smoothSurfaceFilter.GetOutputPort()) else: self.tumorModel_Needle.SetPolyDataConnection( smoother.GetOutputPort()) self.tumorModel_Needle.Modified()
def onApplyThreshold(self): min, max = self.getDistanceBound() newPoints = vtk.vtkPoints() newLines = vtk.vtkCellArray() newTensors = vtk.vtkFloatArray() newTensors.SetNumberOfComponents(9) newScalars = vtk.vtkFloatArray() points = self.inputPolyData.GetPoints() lines = self.inputPolyData.GetLines() tensors = self.inputPolyData.GetPointData().GetTensors() lines.InitTraversal() newId = 0 for length in self.distanceTable: if length <= self.thresholdMax.value and length >= self.thresholdMin.value: ids = vtk.vtkIdList() lines.GetNextCell(ids) newLine = vtk.vtkPolyLine() #print(ids.GetNumberOfIds()) newLine.GetPointIds().SetNumberOfIds(ids.GetNumberOfIds()) #print(((length-min)/(max-min))*100) for i in range(ids.GetNumberOfIds()): newPoints.InsertNextPoint(points.GetPoint(ids.GetId(i))) newLine.GetPointIds().SetId(i, newId) newScalars.InsertNextValue(((length - min) / (max - min))) newId += 1 tensorValue = [0] * 9 if (tensors != None): for j in range(9): tensorValue[j] = tensors.GetComponent( ids.GetId(i), j) newTensors.InsertNextTuple(tensorValue) newLines.InsertNextCell(newLine) self.outputPolyData = vtk.vtkPolyData() self.outputPolyData.SetPoints(newPoints) self.outputPolyData.SetLines(newLines) self.outputPolyData.GetPointData().SetTensors(newTensors) newScalars.SetName("Length") self.outputPolyData.GetPointData().AddArray(newScalars) self.outputNode.SetAndObservePolyData(self.outputPolyData) chartViewNodes = slicer.mrmlScene.GetNodesByClass( 'vtkMRMLChartViewNode') chartViewNodes.InitTraversal() chartViewNode = chartViewNodes.GetNextItemAsObject() arrayNode = slicer.mrmlScene.AddNode(slicer.vtkMRMLDoubleArrayNode()) array = arrayNode.GetArray() array.SetNumberOfTuples(10) step = (max - min) / 10 interMin = min interMax = min + step for i in range(10): numberOfFibers = 0 for length in self.distanceTable: if length <= interMax and length >= interMin and length <= self.thresholdMax.value and length >= self.thresholdMin.value: numberOfFibers += 1 array.SetComponent(i, 0, (interMin + interMax) / 2) array.SetComponent(i, 1, numberOfFibers) array.SetComponent(i, 2, 0) interMin += step interMax += step chartNode = slicer.mrmlScene.AddNode(slicer.vtkMRMLChartNode()) chartNode.AddArray("Fiber Length", arrayNode.GetID()) chartViewNode.SetChartNodeID(chartNode.GetID()) chartNode.SetProperty('default', 'title', 'Length Distribution') chartNode.SetProperty('default', 'xAxisLabel', 'Length') chartNode.SetProperty('default', 'yAxisLabel', 'Distribution') chartNode.SetProperty('default', 'type', 'Bar')
def updateRoi(self): if not self.roiModelNode: return numberOfContourPoints = 0 annulusPoints = None planePosition = None planeNormal = None if self.annulusContourCurve: contourPoints = self.annulusContourCurve.curvePoints # vtk.vtkPoints() numberOfContourPoints = contourPoints.GetNumberOfPoints() if numberOfContourPoints > 0: annulusPoints = self.annulusContourCurve.getInterpolatedPointsAsArray( ) # formerly contourPointsArray_Ras [planePosition, planeNormal] = HeartValveLib.planeFit(annulusPoints) elif self.valveModel is not None and self.leafletSegmentId is not None: annulusPoints = self.getLeafletBoundary() if annulusPoints is not None: numberOfContourPoints = annulusPoints.shape[1] [planePosition, planeNormal] = self.valveModel.getAnnulusContourPlane() if numberOfContourPoints <= 0: clippingPolyData = vtk.vtkPolyData() self.roiModelNode.SetAndObservePolyData(clippingPolyData) self.roiModelNode.Modified() return scale = float(self.roiModelNode.GetAttribute(self.PARAM_SCALE)) * 0.01 topDistance = float( self.roiModelNode.GetAttribute(self.PARAM_TOP_DISTANCE)) topScale = float(self.roiModelNode.GetAttribute( self.PARAM_TOP_SCALE)) * 0.01 bottomDistance = float( self.roiModelNode.GetAttribute(self.PARAM_BOTTOM_DISTANCE)) bottomScale = float( self.roiModelNode.GetAttribute(self.PARAM_BOTTOM_SCALE)) * 0.01 transformPlaneToWorld = vtk.vtkTransform() transformWorldToPlaneMatrix = HeartValveLib.getTransformToPlane( planePosition, planeNormal) numberOfPoints = annulusPoints.shape[1] # Concatenate a 4th line containing 1s so that we can transform the positions using # a single matrix multiplication. annulusPoints_World = np.row_stack( (annulusPoints, np.ones(numberOfPoints))) # Point positions in the plane coordinate system: annulusPoints_Plane = np.dot(transformWorldToPlaneMatrix, annulusPoints_World) # remove the last row (all ones) annulusPoints_Plane = annulusPoints_Plane[0:3, :] # Add points for middle, top, and bottom planes clippingSurfacePoints = vtk.vtkPoints() clippingSurfacePoints.Allocate( 3 * numberOfContourPoints ) # annulus contour + 2x shifted annulus contour # Middle plane annulusPoints_Plane[0, :] = ( annulusPoints_Plane[0, :] - annulusPoints_Plane[0, :].mean() ) * scale + annulusPoints_Plane[0, :].mean() annulusPoints_Plane[1, :] = ( annulusPoints_Plane[1, :] - annulusPoints_Plane[1, :].mean() ) * scale + annulusPoints_Plane[1, :].mean() for contourPoint in annulusPoints_Plane.T: clippingSurfacePoints.InsertNextPoint(contourPoint) meanPosZ = annulusPoints_Plane[:, 2].mean() # Top plane contourPointsArrayTop_Ras = np.copy(annulusPoints_Plane) contourPointsArrayTop_Ras[0, :] = ( contourPointsArrayTop_Ras[0, :] - annulusPoints_Plane[0, :].mean() ) * topScale + annulusPoints_Plane[0, :].mean() contourPointsArrayTop_Ras[1, :] = ( contourPointsArrayTop_Ras[1, :] - annulusPoints_Plane[1, :].mean() ) * topScale + annulusPoints_Plane[1, :].mean() contourPointsArrayTop_Ras[2, :] = topDistance # make the plane planar for contourPoint in contourPointsArrayTop_Ras.T: clippingSurfacePoints.InsertNextPoint(contourPoint) # Bottom plane contourPointsArrayBottom_Ras = np.copy(annulusPoints_Plane) contourPointsArrayBottom_Ras[ 0, :] = (contourPointsArrayBottom_Ras[0, :] - annulusPoints_Plane[ 0, :].mean()) * bottomScale + annulusPoints_Plane[0, :].mean() contourPointsArrayBottom_Ras[ 1, :] = (contourPointsArrayBottom_Ras[1, :] - annulusPoints_Plane[ 1, :].mean()) * bottomScale + annulusPoints_Plane[1, :].mean() contourPointsArrayBottom_Ras[ 2, :] = -bottomDistance # make the plane planar for contourPoint in contourPointsArrayBottom_Ras.T: clippingSurfacePoints.InsertNextPoint(contourPoint) # Add frustum surfaces strips = vtk.vtkCellArray() # Between middle and top strips.InsertNextCell(numberOfContourPoints * 2 + 2) firstTopPointIndex = numberOfContourPoints for i in range(numberOfContourPoints): strips.InsertCellPoint(i) strips.InsertCellPoint(i + firstTopPointIndex) strips.InsertCellPoint(0) strips.InsertCellPoint(firstTopPointIndex) # Between middle and bottom strips.InsertNextCell(numberOfContourPoints * 2 + 2) firstBottomPointIndex = numberOfContourPoints * 2 for i in range(numberOfContourPoints): strips.InsertCellPoint(i) strips.InsertCellPoint(i + firstBottomPointIndex) strips.InsertCellPoint(0) strips.InsertCellPoint(firstBottomPointIndex) # Top and bottom caps polys = vtk.vtkCellArray() polys.InsertNextCell(numberOfContourPoints) for i in range(numberOfContourPoints, numberOfContourPoints * 2): polys.InsertCellPoint(i) polys.InsertNextCell(numberOfContourPoints) for i in range(numberOfContourPoints * 2, numberOfContourPoints * 3): polys.InsertCellPoint(i) clippingSurfacePolyData = vtk.vtkPolyData() clippingSurfacePolyData.SetPoints(clippingSurfacePoints) clippingSurfacePolyData.SetStrips(strips) clippingSurfacePolyData.SetPolys(polys) triangulator = vtk.vtkTriangleFilter() triangulator.SetInputData(clippingSurfacePolyData) transformPlaneToWorldMatrix = np.linalg.inv( transformWorldToPlaneMatrix) transformPlaneToWorldMatrixVtk = vtk.vtkMatrix4x4() for colIndex in range(4): for rowIndex in range(3): transformPlaneToWorldMatrixVtk.SetElement( rowIndex, colIndex, transformPlaneToWorldMatrix[rowIndex, colIndex]) transformPlaneToWorld.SetMatrix(transformPlaneToWorldMatrixVtk) polyTransformToWorld = vtk.vtkTransformPolyDataFilter() polyTransformToWorld.SetTransform(transformPlaneToWorld) polyTransformToWorld.SetInputConnection(triangulator.GetOutputPort()) polyTransformToWorld.Update() clippingPolyData = polyTransformToWorld.GetOutput() self.roiModelNode.SetAndObservePolyData(clippingPolyData) self.roiModelNode.Modified()