def IntersectBaseModel(self): transform = vtk.vtkTransform() matrix = vtk.vtkMatrix4x4() self.transformSelector.currentNode().GetMatrixTransformToParent(matrix) transform.SetMatrix(matrix) #transform.RotateX(-90.0) # cylinder = vtk.vtkCylinderSource() # cylinder.SetCenter(np.array([0.0, 0.0, 0.0])) # cylinder.SetRadius(25) # cylinder.SetHeight(60) # cylinder.SetResolution(100) # cylinder.Update() originalCylinder_path = os.path.dirname( os.path.realpath(__file__)) + "\\Models\\OriginalCylinder.stl" originalCylinderModelNode = slicer.util.loadModel( originalCylinder_path) transformFilter = vtk.vtkTransformPolyDataFilter() transformFilter.SetInputData(originalCylinderModelNode.GetPolyData()) transformFilter.SetTransform(transform) transformFilter.ReleaseDataFlagOn() transformFilter.Update() modelNode = self.booleanModelSelector.currentNode() modelNode.SetAndObservePolyData(transformFilter.GetOutput()) modelDisplayNode = modelNode.GetModelDisplayNode() if modelDisplayNode is None: modelDisplayNode = slicer.vtkMRMLModelDisplayNode() modelDisplayNode.SetScene(slicer.mrmlScene) slicer.mrmlScene.AddNode(modelDisplayNode) modelNode.SetAndObserveDisplayNodeID(modelDisplayNode.GetID()) modelDisplayNode.SetOpacity(0.2) modelDisplayNode.SetColor(0, 1, 0) modelNode2 = self.transientModelSelector.currentNode() modelDisplayNode2 = self.transientModelSelector.currentNode( ).GetModelDisplayNode() if modelDisplayNode2 is None: modelDisplayNode2 = slicer.vtkMRMLModelDisplayNode() modelDisplayNode2.SetScene(slicer.mrmlScene) slicer.mrmlScene.AddNode(modelDisplayNode2) modelNode2.SetAndObserveDisplayNodeID(modelDisplayNode2.GetID()) modelDisplayNode2.SetOpacity(1.0) modelDisplayNode2.SetColor(0, 1, 0) cylinder_path = os.path.dirname( os.path.realpath(__file__)) + "\\Models\\cylinder.stl" slicer.util.saveNode(modelNode, cylinder_path) slicer.mrmlScene.RemoveNode(originalCylinderModelNode) self.blenderBoolean()
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 planeModel(self, scene, normal, origin, name, color): """ Create a plane model node which can be viewed in the 3D View """ #A plane source plane = vtk.vtkPlane() plane.SetOrigin(origin) plane.SetNormal(normal) planeSample = vtk.vtkSampleFunction() planeSample.SetImplicitFunction(plane) planeSample.SetModelBounds(-100,100,-100,100,-100,100) planeSample.SetSampleDimensions(100,100,100) planeSample.ComputeNormalsOff() planeContour = vtk.vtkContourFilter() planeContour.SetInput(planeSample.GetOutput()) # Create plane model node planeNode = slicer.vtkMRMLModelNode() planeNode.SetScene(scene) planeNode.SetName(name) planeNode.SetAndObservePolyData(planeContour.GetOutput()) # Create plane display model node planeModelDisplay = slicer.vtkMRMLModelDisplayNode() planeModelDisplay.SetColor(color) planeModelDisplay.SetBackfaceCulling(0) planeModelDisplay.SetScene(scene) scene.AddNode(planeModelDisplay) planeNode.SetAndObserveDisplayNodeID(planeModelDisplay.GetID()) #Add to scene planeModelDisplay.SetInputPolyData(planeContour.GetOutput()) scene.AddNode(planeNode) return plane
def setupMRMLTracking(self): if not hasattr(self, "trackingDevice"): """ set up the mrml parts or use existing """ nodes = slicer.mrmlScene.GetNodesByName('trackingDevice') if nodes.GetNumberOfItems() > 0: self.trackingDevice = nodes.GetItemAsObject(0) nodes = slicer.mrmlScene.GetNodesByName('tracker') self.tracker = nodes.GetItemAsObject(0) else: # trackingDevice cursor self.cube = vtk.vtkCubeSource() self.cube.SetXLength(30) self.cube.SetYLength(70) self.cube.SetZLength(5) self.cube.Update() # display node self.modelDisplay = slicer.vtkMRMLModelDisplayNode() self.modelDisplay.SetColor(1,1,0) # yellow slicer.mrmlScene.AddNode(self.modelDisplay) # self.modelDisplay.SetPolyData(self.cube.GetOutputPort()) # Create model node self.trackingDevice = slicer.vtkMRMLModelNode() self.trackingDevice.SetScene(slicer.mrmlScene) self.trackingDevice.SetName("trackingDevice") self.trackingDevice.SetAndObservePolyData(self.cube.GetOutputDataObject(0)) self.trackingDevice.SetAndObserveDisplayNodeID(self.modelDisplay.GetID()) slicer.mrmlScene.AddNode(self.trackingDevice) # tracker self.tracker = slicer.vtkMRMLLinearTransformNode() self.tracker.SetName('tracker') slicer.mrmlScene.AddNode(self.tracker) self.trackingDevice.SetAndObserveTransformNodeID(self.tracker.GetID())
def generate3DVisualisationNode(self, polydata, name, color=(1, 1, 1), initial_pos_x=0): #create Model Node shape_node = slicer.vtkMRMLModelNode() shape_node.SetAndObservePolyData(polydata) shape_node.SetName(name) #create display node model_display = slicer.vtkMRMLModelDisplayNode() model_display.SetColor(color[0], color[1], color[2]) model_display.AutoScalarRangeOff() model_display.SetScene(slicer.mrmlScene) model_display.SetName("Display " + name) #create transform node transform = vtk.vtkTransform() transform.Translate(initial_pos_x, 0, 0) transform_node = slicer.vtkMRMLTransformNode() transform_node.SetName("Translation " + name) transform_node.SetAndObserveTransformToParent(transform) #Add Nodes to Slicer slicer.mrmlScene.AddNode(transform_node) slicer.mrmlScene.AddNode(model_display) slicer.mrmlScene.AddNode(shape_node) #Link nodes shape_node.SetAndObserveTransformNodeID(transform_node.GetID()) shape_node.SetAndObserveDisplayNodeID(model_display.GetID())
def createSampleModelVolume(self, name, color, volumeNode=None): if volumeNode: self.assertTrue( volumeNode.IsA('vtkMRMLScalarVolumeNode') ) bounds = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0] volumeNode.GetRASBounds(bounds) x = (bounds[0] + bounds[1])/2 y = (bounds[2] + bounds[3])/2 z = (bounds[4] + bounds[5])/2 radius = min(bounds[1]-bounds[0],bounds[3]-bounds[2],bounds[5]-bounds[4]) / 3.0 else: radius = 50 x = y = z = 0 # Taken from: http://www.na-mic.org/Bug/view.php?id=1536 sphere = vtk.vtkSphereSource() sphere.SetCenter(x, y, z) sphere.SetRadius(radius) modelNode = slicer.vtkMRMLModelNode() modelNode.SetName(name) modelNode = slicer.mrmlScene.AddNode(modelNode) if vtk.VTK_MAJOR_VERSION <= 5: modelNode.SetAndObservePolyData(sphere.GetOutput()) else: modelNode.SetPolyDataConnection(sphere.GetOutputPort()) modelNode.SetHideFromEditors(0) displayNode = slicer.vtkMRMLModelDisplayNode() slicer.mrmlScene.AddNode(displayNode) displayNode.SliceIntersectionVisibilityOn() displayNode.VisibilityOn() displayNode.SetColor(color[0], color[1], color[2]) modelNode.SetAndObserveDisplayNodeID(displayNode.GetID()) return modelNode
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 __init__(self, targetFiducialListNode, radius): target = targetFiducialListNode scene = slicer.mrmlScene sphere = vtk.vtkSphereSource() sphere.SetRadius(radius) sphere.SetThetaResolution(20) sphere.SetPhiResolution(20) sphere.Update() # Create model node insertionRadiusModel = slicer.vtkMRMLModelNode() insertionRadiusModel.SetScene(scene) insertionRadiusModel.SetName("InsertionSphere-%s" % target.GetName()) insertionRadiusModel.SetAndObservePolyData(sphere.GetOutput()) # Create display node insertionRadiusModelDisplay = slicer.vtkMRMLModelDisplayNode() insertionRadiusModelDisplay.SetColor(0.8,0.8,0.8) insertionRadiusModelDisplay.SetOpacity(0.3) insertionRadiusModelDisplay.SliceIntersectionVisibilityOn() insertionRadiusModelDisplay.SetScene(scene) scene.AddNode(insertionRadiusModelDisplay) insertionRadiusModel.SetAndObserveDisplayNodeID(insertionRadiusModelDisplay.GetID()) # Add to scene insertionRadiusModelDisplay.SetPolyData(sphere.GetOutput()) scene.AddNode(insertionRadiusModel) # Create insertionRadiusTransform node insertionRadiusTransform = slicer.vtkMRMLLinearTransformNode() insertionRadiusTransform.SetName('InsertionRadiusTransform-%s' % target.GetName()) scene.AddNode(insertionRadiusTransform) # Translation transformMatrix = vtk.vtkMatrix4x4() # get coordinates from current fiducial currentFiducialCoordinatesRAS = [0, 0, 0] target.GetFiducialCoordinates(currentFiducialCoordinatesRAS) transformMatrix.SetElement(0, 3, currentFiducialCoordinatesRAS[0]) transformMatrix.SetElement(1, 3, currentFiducialCoordinatesRAS[1]) transformMatrix.SetElement(2, 3, currentFiducialCoordinatesRAS[2]) insertionRadiusTransform.ApplyTransformMatrix(transformMatrix) insertionRadiusModel.SetAndObserveTransformNodeID(insertionRadiusTransform.GetID()) self.sphere = sphere self.insertionRadiusModel = insertionRadiusModel self.insertionRadiusModelDisplay = insertionRadiusModelDisplay self.insertionRadiusTransform = insertionRadiusTransform
def initializeModelNode(node): displayNode = slicer.vtkMRMLModelDisplayNode() storageNode = slicer.vtkMRMLModelStorageNode() displayNode.SetScene(slicer.mrmlScene) storageNode.SetScene(slicer.mrmlScene) slicer.mrmlScene.AddNode(displayNode) slicer.mrmlScene.AddNode(storageNode) node.SetAndObserveDisplayNodeID(displayNode.GetID()) node.SetAndObserveStorageNodeID(storageNode.GetID())
def blenderBoolean(self): bpy.ops.wm.read_factory_settings() for scene in bpy.data.scenes: for obj in scene.objects: scene.objects.unlink(obj) # only worry about data in the startup scene for bpy_data_iter in (bpy.data.objects, bpy.data.meshes, bpy.data.lamps, bpy.data.cameras): for id_data in bpy_data_iter: bpy_data_iter.remove(id_data) dir_path = os.path.dirname(os.path.realpath(__file__)) + "\\Models\\" #dir_path = "D:\\w\\s\\DepthNetworkTracking\\Model\\" airwayPath = dir_path + "airwayNoWall.stl" cylinderPath = dir_path + "cylinder.stl" bpy.ops.import_mesh.stl(filepath=airwayPath) bpy.ops.import_mesh.stl(filepath=cylinderPath) objects = bpy.data.objects airwayNoWall = objects['airwayNoWall'] cylinder = objects['Cylinder'] airwayBoolean = airwayNoWall.modifiers.new(type="BOOLEAN", name="bool_7") airwayBoolean.object = cylinder airwayBoolean.operation = 'INTERSECT' cylinder.hide = True bpy.context.scene.objects.active = bpy.data.objects['airwayNoWall'] bpy.ops.object.modifier_apply(apply_as='DATA', modifier=airwayBoolean.name) airwayNoWall.select = False cylinder.select = True bpy.ops.object.delete() airwayNoWall.select = True airwayIsolatedPath = dir_path + "airwayIsolated.stl" bpy.ops.export_mesh.stl(filepath=airwayIsolatedPath) outputModelPath = dir_path + "airwayIsolated.STL" outputModelNode = slicer.util.loadModel(outputModelPath) modelNode2 = self.transientModelSelector.currentNode() modelDisplayNode2 = self.transientModelSelector.currentNode( ).GetModelDisplayNode() if modelDisplayNode2 is None: modelDisplayNode2 = slicer.vtkMRMLModelDisplayNode() modelDisplayNode2.SetScene(slicer.mrmlScene) slicer.mrmlScene.AddNode(modelDisplayNode2) modelNode2.SetAndObserveDisplayNodeID(modelDisplayNode2.GetID()) modelDisplayNode2.SetOpacity(0.7) modelDisplayNode2.SetColor(0, 1, 0) modelNode2.SetAndObservePolyData(outputModelNode.GetPolyData()) slicer.mrmlScene.RemoveNode(outputModelNode)
def updateModel(self): if self.AutomaticUpdate == False: return if not self.ModelNode: return if self.ModelNode.GetDisplayNodeID() == None: modelDisplayNode = slicer.vtkMRMLModelDisplayNode() modelDisplayNode.SetColor(self.ModelColor) slicer.mrmlScene.AddNode(modelDisplayNode) self.ModelNode.SetAndObserveDisplayNodeID(modelDisplayNode.GetID()) displayNodeID = self.ModelNode.GetDisplayNodeID() modelDisplayNode = slicer.mrmlScene.GetNodeByID(displayNodeID) if modelDisplayNode: if self.SliceIntersection == True: modelDisplayNode.SliceIntersectionVisibilityOn() else: modelDisplayNode.SliceIntersectionVisibilityOff() modelDisplayNode.SetOpacity(0.5) if self.CylinderSource == None: self.CylinderSource = vtk.vtkCylinderSource() self.CylinderSource.SetResolution(60) self.CylinderSource.SetRadius(self.Diameter/2.0) self.CylinderSource.SetHeight(self.Length) self.CylinderSource.SetCenter(self.Offset) self.CylinderSource.Update() ## Scale sphere to make ellipsoid #scale = vtk.vtkTransform() #scale.Scale(self.MinorAxis, self.MinorAxis, self.MajorAxis) #scaleFilter = vtk.vtkTransformPolyDataFilter() #scaleFilter.SetInputConnection(self.CylinderSource.GetOutputPort()) #scaleFilter.SetTransform(scale) #scaleFilter.Update(); # Transform #transform = vtk.vtkTransform() #self.computeTransform(pTip, pTail, self.TipOffset, transform) #transformFilter = vtk.vtkTransformPolyDataFilter() #transformFilter.SetInputConnection(scaleFilter.GetOutputPort()) #transformFilter.SetInputConnection(self.CylinderSource.GetOutputPort()) #transformFilter.SetTransform(transform) #transformFilter.Update(); #self.ModelNode.SetAndObservePolyData(transformFilter.GetOutput()) self.ModelNode.SetAndObservePolyData(self.CylinderSource.GetOutput()) self.ModelNode.Modified() if self.ModelNode.GetScene() == None: slicer.mrmlScene.AddNode(self.ModelNode)
def ExtractMesh(outputModelNode, modelNode, colorRgb, colorTolerance): fullPolyData = modelNode.GetPolyData() pointData = fullPolyData.GetPointData() redValues = pointData.GetArray('ColorRed') greenValues = pointData.GetArray('ColorGreen') blueValues = pointData.GetArray('ColorBlue') redMaxTolerance = colorRgb[0] + colorTolerance redMinTolerance = colorRgb[0] - colorTolerance greenMaxTolerance = colorRgb[1] + colorTolerance greenMinTolerance = colorRgb[1] - colorTolerance blueMaxTolerance = colorRgb[2] + colorTolerance blueMinTolerance = colorRgb[2] - colorTolerance lengthTuples = int(redValues.GetNumberOfTuples()) selectedPointIds = vtk.vtkIdTypeArray() for pointId in range(lengthTuples): if redValues.GetValue( pointId) >= redMinTolerance and redValues.GetValue( pointId) <= redMaxTolerance and greenValues.GetValue( pointId) >= greenMinTolerance and greenValues.GetValue( pointId ) <= greenMaxTolerance and blueValues.GetValue( pointId ) >= blueMinTolerance and blueValues.GetValue( pointId) <= blueMaxTolerance: selectedPointIds.InsertNextValue(pointId) selectedPointIds.InsertNextValue(pointId) selectionNode = vtk.vtkSelectionNode() selectionNode.SetFieldType(vtk.vtkSelectionNode.POINT) selectionNode.SetContentType(vtk.vtkSelectionNode.INDICES) selectionNode.SetSelectionList(selectedPointIds) selectionNode.GetProperties().Set(vtk.vtkSelectionNode.CONTAINING_CELLS(), 1) selection = vtk.vtkSelection() selection.AddNode(selectionNode) extractSelection = vtk.vtkExtractSelection() extractSelection.SetInputData(0, fullPolyData) extractSelection.SetInputData(1, selection) extractSelection.Update() convertToPolydata = vtk.vtkDataSetSurfaceFilter() convertToPolydata.SetInputConnection(extractSelection.GetOutputPort()) convertToPolydata.Update() outputModelNode.SetAndObservePolyData(convertToPolydata.GetOutput()) if not outputModelNode.GetDisplayNode(): md2 = slicer.vtkMRMLModelDisplayNode() slicer.mrmlScene.AddNode(md2) outputModelNode.SetAndObserveDisplayNodeID(md2.GetID())
def loadModels(self, skullModel, skullMarkersModel, pointerModel): self.skullModel=skullModel self.skullMarkersModel=skullMarkersModel self.pointerModel=pointerModel self.skull.SetName("SkullModel") self.skull.SetAndObservePolyData(self.skullModel.GetPolyData()) slicer.mrmlScene.AddNode(self.skull) # Add display node modelDisplayNode = slicer.vtkMRMLModelDisplayNode() modelDisplayNode.SetColor(1,1,1) # White modelDisplayNode.BackfaceCullingOff() modelDisplayNode.SliceIntersectionVisibilityOn() modelDisplayNode.SetSliceIntersectionThickness(4) modelDisplayNode.SetOpacity(1) # Between 0-1, 1 being opaque slicer.mrmlScene.AddNode(modelDisplayNode) self.skull.SetAndObserveDisplayNodeID(modelDisplayNode.GetID()) self.skullMarkers.SetName("SkullMarkersModel") self.skullMarkers.SetAndObservePolyData(self.skullMarkersModel.GetPolyData()) slicer.mrmlScene.AddNode(self.skullMarkers) # Add display node modelDisplayNode = slicer.vtkMRMLModelDisplayNode() modelDisplayNode.SetColor(1,0,0) # White modelDisplayNode.BackfaceCullingOff() modelDisplayNode.SliceIntersectionVisibilityOn() modelDisplayNode.SetSliceIntersectionThickness(4) modelDisplayNode.SetOpacity(1) # Between 0-1, 1 being opaque slicer.mrmlScene.AddNode(modelDisplayNode) self.skullMarkers.SetAndObserveDisplayNodeID(modelDisplayNode.GetID()) self.pointer.SetName("PointerModel") self.pointer.SetAndObservePolyData(self.pointerModel.GetPolyData()) slicer.mrmlScene.AddNode(self.pointer) # Add display node modelDisplayNode = slicer.vtkMRMLModelDisplayNode() modelDisplayNode.SetColor(0,0,0) # White modelDisplayNode.BackfaceCullingOff() modelDisplayNode.SliceIntersectionVisibilityOn() modelDisplayNode.SetSliceIntersectionThickness(4) modelDisplayNode.SetOpacity(1) # Between 0-1, 1 being opaque slicer.mrmlScene.AddNode(modelDisplayNode) self.pointer.SetAndObserveDisplayNodeID(modelDisplayNode.GetID())
def DisplayPolyData(self, nameOfNode, polyData, overwrite=True): """ Function that Overwrites/Creates a Node to display Polydata """ n=self.CreateNewNode(nameOfNode, "vtkMRMLModelNode", overwrite=True) outputMouldModelDisplayNode = slicer.vtkMRMLModelDisplayNode() slicer.mrmlScene.AddNode(outputMouldModelDisplayNode) outputMouldModelDisplayNode.BackfaceCullingOff() n.SetAndObserveDisplayNodeID(outputMouldModelDisplayNode.GetID()) n.SetAndObservePolyData(polyData) return outputMouldModelDisplayNode
def DisplayPolyData(self, nameOfNode, polyData, overwrite=True): """ Function that Overwrites/Creates a Node to display Polydata """ n = self.CreateNewNode(nameOfNode, "vtkMRMLModelNode", overwrite=True) outputMouldModelDisplayNode = slicer.vtkMRMLModelDisplayNode() slicer.mrmlScene.AddNode(outputMouldModelDisplayNode) outputMouldModelDisplayNode.BackfaceCullingOff() n.SetAndObserveDisplayNodeID(outputMouldModelDisplayNode.GetID()) n.SetAndObservePolyData(polyData) return outputMouldModelDisplayNode
def updateAblationVolume(self): if self.AutomaticUpdate == False: return if self.SourceNode and self.DestinationNode: pTip = [0.0, 0.0, 0.0] pTail = [0.0, 0.0, 0.0] #self.SourceNode.GetNthFiducialPosition(0,pTip) self.SourceNode.GetPosition1(pTip) #self.SourceNode.GetNthFiducialPosition(1,pTail) self.SourceNode.GetPosition2(pTail) if self.DestinationNode.GetDisplayNodeID() == None: modelDisplayNode = slicer.vtkMRMLModelDisplayNode() modelDisplayNode.SetColor(self.ModelColor) slicer.mrmlScene.AddNode(modelDisplayNode) self.DestinationNode.SetAndObserveDisplayNodeID(modelDisplayNode.GetID()) displayNodeID = self.DestinationNode.GetDisplayNodeID() modelDisplayNode = slicer.mrmlScene.GetNodeByID(displayNodeID) if modelDisplayNode != None and self.SliceIntersection == True: modelDisplayNode.SliceIntersectionVisibilityOn() else: modelDisplayNode.SliceIntersectionVisibilityOff() if self.SphereSource == None: self.SphereSource = vtk.vtkSphereSource() self.SphereSource.SetThetaResolution(20) self.SphereSource.SetPhiResolution(20) self.SphereSource.Update() # Scale sphere to make ellipsoid scale = vtk.vtkTransform() scale.Scale(self.MinorAxis, self.MinorAxis, self.MajorAxis) scaleFilter = vtk.vtkTransformPolyDataFilter() scaleFilter.SetInputConnection(self.SphereSource.GetOutputPort()) scaleFilter.SetTransform(scale) scaleFilter.Update(); # Transform transform = vtk.vtkTransform() self.computeTransform(pTip, pTail, self.TipOffset, transform) transformFilter = vtk.vtkTransformPolyDataFilter() transformFilter.SetInputConnection(scaleFilter.GetOutputPort()) transformFilter.SetTransform(transform) transformFilter.Update(); self.DestinationNode.SetAndObservePolyData(transformFilter.GetOutput()) self.DestinationNode.Modified() if self.DestinationNode.GetScene() == None: slicer.mrmlScene.AddNode(self.DestinationNode)
def defineSphere(self): sphereSource = vtk.vtkSphereSource() sphereSource.SetRadius(100.0) model = slicer.vtkMRMLModelNode() model.SetAndObservePolyData(sphereSource.GetOutput()) modelDisplay = slicer.vtkMRMLModelDisplayNode() modelDisplay.SetColor(0.5,0.5,0.5) slicer.mrmlScene.AddNode(modelDisplay) model.SetAndObserveDisplayNodeID(modelDisplay.GetID()) modelDisplay.SetInputPolyDataConnection(sphereSource.GetOutputPort()) return model
def createModelNode(self, name, color): scene = slicer.mrmlScene modelNode = slicer.vtkMRMLModelNode() modelNode.SetScene(scene) modelNode.SetName(name) modelDisplay = slicer.vtkMRMLModelDisplayNode() modelDisplay.SetColor(color) modelDisplay.SetScene(scene) scene.AddNode(modelDisplay) modelNode.SetAndObserveDisplayNodeID(modelDisplay.GetID()) scene.AddNode(modelNode) return modelNode
def addModelToScene(self, polyData, name): scene = slicer.mrmlScene node = slicer.vtkMRMLModelNode() node.SetScene(scene) node.SetName(name) node.SetAndObservePolyData(polyData) modelDisplay = slicer.vtkMRMLModelDisplayNode() modelDisplay.SetColor(0, 1, 0) modelDisplay.SetScene(scene) scene.AddNode(modelDisplay) node.SetAndObserveDisplayNodeID(modelDisplay.GetID()) scene.AddNode(node) return node
def enableSliceIntersection(self, state): if self.DestinationNode.GetDisplayNodeID() == None: modelDisplayNode = slicer.vtkMRMLModelDisplayNode() modelDisplayNode.SetColor(self.ModelColor) slicer.mrmlScene.AddNode(modelDisplayNode) self.DestinationNode.SetAndObserveDisplayNodeID(modelDisplayNode.GetID()) displayNodeID = self.DestinationNode.GetDisplayNodeID() displayNode = slicer.mrmlScene.GetNodeByID(displayNodeID) if displayNode != None: if state: displayNode.SliceIntersectionVisibilityOn() else: displayNode.SliceIntersectionVisibilityOff()
def gradeScrew(self, screwModel, transformFid, fidName, screwIndex): #Reset screws #self.clearGrade() #Crop out head of screw croppedScrew = self.cropScrew(screwModel, 'head') #Clone screw model poly data inputModel = slicer.vtkMRMLModelNode() inputModel.SetAndObservePolyData(croppedScrew) inputModel.SetAndObserveTransformNodeID(transformFid.GetID()) slicer.mrmlScene.AddNode(inputModel) slicer.vtkSlicerTransformLogic.hardenTransform(inputModel) #Create new model for output output = slicer.vtkMRMLModelNode() output.SetName('Grade model-%s' % fidName) slicer.mrmlScene.AddNode(output) #Parameters for ProbeVolumeWithModel parameters = {} parameters["InputVolume"] = self.__inputScalarVol.GetID() parameters["InputModel"] = inputModel.GetID() parameters["OutputModel"] = output.GetID() probe = slicer.modules.probevolumewithmodel slicer.cli.run(probe, None, parameters, wait_for_completion=True) #Hide original screw modelDisplay = screwModel.GetDisplayNode() modelDisplay.SetColor(0,1,0) modelDisplay.VisibilityOff() #Highlight screwh head headModel = slicer.vtkMRMLModelNode() headModel.SetName('Head %s' % fidName) headModel.SetAndObservePolyData(self.cropScrew(screwModel, 'shaft')) headModel.SetAndObserveTransformNodeID(transformFid.GetID()) slicer.mrmlScene.AddNode(headModel) headDisplay = slicer.vtkMRMLModelDisplayNode() headDisplay.SetColor(0,1,0) slicer.mrmlScene.AddNode(headDisplay) headModel.SetAndObserveDisplayNodeID(headDisplay.GetID()) #Remove clone slicer.mrmlScene.RemoveNode(inputModel) #Grade and chart screw self.contact(output, screwModel, fidName, screwIndex)
def gradeScrew(self, screwModel, transformFid, fidName, screwIndex): #Reset screws #self.clearGrade() #Crop out head of screw croppedScrew = self.cropScrew(screwModel, 'head') #Clone screw model poly data inputModel = slicer.vtkMRMLModelNode() inputModel.SetAndObservePolyData(croppedScrew) inputModel.SetAndObserveTransformNodeID(transformFid.GetID()) slicer.mrmlScene.AddNode(inputModel) slicer.vtkSlicerTransformLogic.hardenTransform(inputModel) #Create new model for output output = slicer.vtkMRMLModelNode() output.SetName('Grade model-%s' % fidName) slicer.mrmlScene.AddNode(output) #Parameters for ProbeVolumeWithModel parameters = {} parameters["InputVolume"] = self.__inputScalarVol.GetID() parameters["InputModel"] = inputModel.GetID() parameters["OutputModel"] = output.GetID() probe = slicer.modules.probevolumewithmodel slicer.cli.run(probe, None, parameters, wait_for_completion=True) #Hide original screw modelDisplay = screwModel.GetDisplayNode() modelDisplay.SetColor(0, 1, 0) modelDisplay.VisibilityOff() #Highlight screwh head headModel = slicer.vtkMRMLModelNode() headModel.SetName('Head %s' % fidName) headModel.SetAndObservePolyData(self.cropScrew(screwModel, 'shaft')) headModel.SetAndObserveTransformNodeID(transformFid.GetID()) slicer.mrmlScene.AddNode(headModel) headDisplay = slicer.vtkMRMLModelDisplayNode() headDisplay.SetColor(0, 1, 0) slicer.mrmlScene.AddNode(headDisplay) headModel.SetAndObserveDisplayNodeID(headDisplay.GetID()) #Remove clone slicer.mrmlScene.RemoveNode(inputModel) #Grade and chart screw self.contact(output, screwModel, fidName, screwIndex)
def addPolyDataToScene(self,polyData,name): print "addPolyDataToScene" self.outputDisplayNode = slicer.vtkMRMLModelDisplayNode() self.outputDisplayNode.SetName(name+"Display") self.outputDisplayNode.SetColor(0,0,1.0) self.outputDisplayNode.SetOpacity(0.5) slicer.mrmlScene.AddNode(self.outputDisplayNode) self.outputModelNode = slicer.vtkMRMLModelNode() self.outputModelNode.SetAndObservePolyData(polyData) self.outputModelNode.SetAndObserveDisplayNodeID(self.outputDisplayNode.GetID()) if (self.transformGridToTargetNode): self.outputModelNode.SetAndObserveTransformNodeID(self.transformGridToTargetNode.GetID()) self.outputModelNode.SetName(name) slicer.mrmlScene.AddNode(self.outputModelNode)
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 lineModel(self, scene, point1, point2, name, color): """ Create a line to reflect the puncture path""" #Line mode source line = vtk.vtkLineSource() line.SetPoint1(point1)#(point1[0][0], point1[0][1], point1[0][2]) line.SetPoint2(point2)#(point2[0][0], point2[0][1], point2[0][2]) # Create model node lineModel = slicer.vtkMRMLModelNode() lineModel.SetScene(scene) lineModel.SetName(name) lineModel.SetAndObservePolyData(line.GetOutput()) # Create display node lineModelDisplay = slicer.vtkMRMLModelDisplayNode() lineModelDisplay.SetColor(color) lineModelDisplay.SetScene(scene) scene.AddNode(lineModelDisplay) lineModel.SetAndObserveDisplayNodeID(lineModelDisplay.GetID()) #Add to scene # lineModelDisplay.SetInputPolyData(line.GetOutput()) lineModelDisplay.SetInputPolyDataConnection(line.GetOutputPort()) scene.AddNode(lineModel) return line
def addPolyDataToScene(self, polyData, name): print "addPolyDataToScene" self.outputDisplayNode = slicer.vtkMRMLModelDisplayNode() self.outputDisplayNode.SetName(name + "Display") self.outputDisplayNode.SetColor(0, 0, 1.0) self.outputDisplayNode.SetOpacity(0.5) slicer.mrmlScene.AddNode(self.outputDisplayNode) self.outputModelNode = slicer.vtkMRMLModelNode() self.outputModelNode.SetAndObservePolyData(polyData) self.outputModelNode.SetAndObserveDisplayNodeID( self.outputDisplayNode.GetID()) if (self.transformGridToTargetNode): self.outputModelNode.SetAndObserveTransformNodeID( self.transformGridToTargetNode.GetID()) self.outputModelNode.SetName(name) slicer.mrmlScene.AddNode(self.outputModelNode)
def ExtractMesh(outputModelNode, modelNode, colorRgb, colorTolerance): fullPolyData = modelNode.GetPolyData() pointData=fullPolyData.GetPointData() redValues = pointData.GetArray('ColorRed') greenValues = pointData.GetArray('ColorGreen') blueValues = pointData.GetArray('ColorBlue') redMaxTolerance = colorRgb[0] + colorTolerance redMinTolerance = colorRgb[0] - colorTolerance greenMaxTolerance = colorRgb[1] + colorTolerance greenMinTolerance = colorRgb[1] - colorTolerance blueMaxTolerance = colorRgb[2] + colorTolerance blueMinTolerance = colorRgb[2] - colorTolerance lengthTuples = int(redValues.GetNumberOfTuples()) selectedPointIds = vtk.vtkIdTypeArray() for pointId in range(lengthTuples): if redValues.GetValue(pointId) >= redMinTolerance and redValues.GetValue(pointId) <= redMaxTolerance and greenValues.GetValue(pointId) >= greenMinTolerance and greenValues.GetValue(pointId) <= greenMaxTolerance and blueValues.GetValue(pointId) >= blueMinTolerance and blueValues.GetValue(pointId) <= blueMaxTolerance: selectedPointIds.InsertNextValue(pointId) selectedPointIds.InsertNextValue(pointId) selectionNode = vtk.vtkSelectionNode() selectionNode.SetFieldType(vtk.vtkSelectionNode.POINT) selectionNode.SetContentType(vtk.vtkSelectionNode.INDICES) selectionNode.SetSelectionList(selectedPointIds) selectionNode.GetProperties().Set(vtk.vtkSelectionNode.CONTAINING_CELLS(), 1); selection = vtk.vtkSelection() selection.AddNode(selectionNode) extractSelection = vtk.vtkExtractSelection() extractSelection.SetInputData(0,fullPolyData) extractSelection.SetInputData(1,selection); extractSelection.Update(); convertToPolydata = vtk.vtkDataSetSurfaceFilter() convertToPolydata.SetInputConnection(extractSelection.GetOutputPort()) convertToPolydata.Update() outputModelNode.SetAndObservePolyData(convertToPolydata.GetOutput()) if not outputModelNode.GetDisplayNode(): md2 = slicer.vtkMRMLModelDisplayNode() slicer.mrmlScene.AddNode(md2) outputModelNode.SetAndObserveDisplayNodeID(md2.GetID())
def createOptionalPathModel(self, pos, holeInfoList, intNumOfOptionalPath): if intNumOfOptionalPath == 1: self.setOptionalPathVisibility(1) pathListRAS = [] for i in range(len(holeInfoList)): pathListRAS.append(self.templateRAS[holeInfoList[i][3]]) print "pathListRAS: ", pathListRAS #(not generate path -> pass, otherwise go on) self.optModelNode = slicer.mrmlScene.GetNodeByID(self.optionalPathModelNodeID) if self.optModelNode == None: self.optModelNode = slicer.vtkMRMLModelNode() self.optModelNode.SetName('AllOptionalPaths') slicer.mrmlScene.AddNode(self.optModelNode) self.optionalPathModelNodeID = self.optModelNode.GetID() self.dnodeOpt = slicer.vtkMRMLModelDisplayNode() self.dnodeOpt.SetColor(0.96,0.92,0.56) slicer.mrmlScene.AddNode(self.dnodeOpt) self.optModelNode.SetAndObserveDisplayNodeID(self.dnodeOpt.GetID()) optModelAppend = vtk.vtkAppendPolyData() #for path in pathListRAS: for index in range(len(pathListRAS)): optLineSource = vtk.vtkLineSource() optLineSource.SetPoint1(pos) optLineSource.SetPoint2(pathListRAS[index]) optTubeFilter = vtk.vtkTubeFilter() optTubeFilter.SetInputConnection(optLineSource.GetOutputPort()) optTubeFilter.SetRadius(1.0) optTubeFilter.SetNumberOfSides(10) optTubeFilter.CappingOn() optTubeFilter.Update() if vtk.VTK_MAJOR_VERSION <= 5: optModelAppend.AddInput(optTubeFilter.GetOutput()) else: optModelAppend.AddInputData(optTubeFilter.GetOutput()) optModelAppend.Update() self.optModelNode.SetAndObservePolyData(optModelAppend.GetOutput())
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 __init__(self): self.scene = slicer.mrmlScene self.scene.SetUndoOn() self.scene.SaveStateForUndo(self.scene.GetNodes()) self.currentSlice = Slice('/luscinia/ProstateStudy/invivo/Patient59/loupas/RadialImagesCC_imwrite/arfi_ts3_26.57.png') # yay, adding images to slicer planeSource = vtk.vtkPlaneSource() planeSource.SetCenter(self.currentSlice.x, self.currentSlice.y, self.currentSlice.z) reader = vtk.vtkPNGReader() reader.SetFileName(self.currentSlice.name) # model node self.model = slicer.vtkMRMLModelNode() self.model.SetScene(self.scene) self.model.SetName(self.currentSlice.name) self.model.SetAndObservePolyData(planeSource.GetOutput()) # model display node self.modelDisplay = slicer.vtkMRMLModelDisplayNode() self.modelDisplay.BackfaceCullingOff() # so plane can be seen from both front and back face self.modelDisplay.SetScene(self.scene) self.scene.AddNode(self.modelDisplay) # connecting model node w/ its model display node self.model.SetAndObserveDisplayNodeID(self.modelDisplay.GetID()) # adding tiff file as texture to modelDisplay self.modelDisplay.SetAndObserveTextureImageData(reader.GetOutput()) self.scene.AddNode(self.model) # now doing a linear transform to set coordinates and orientation of plane self.transform = slicer.vtkMRMLLinearTransformNode() self.scene.AddNode(self.transform) self.model.SetAndObserveTransformNodeID(self.transform.GetID()) vTransform = vtk.vtkTransform() vTransform.Scale(150, 150, 150) vTransform.RotateX(0) vTransform.RotateY(0) vTransform.RotateZ(0) self.transform.SetAndObserveMatrixTransformToParent(vTransform.GetMatrix())
def selectSlice(self, index): self.scene.Undo() self.scene.SaveStateForUndo(self.scene.GetNodes()) imgFilePrefix = './data/test' imgFileSuffix = '.tiff' # yay, adding images to slicer planeSource = vtk.vtkPlaneSource() reader = vtk.vtkTIFFReader() reader.SetFileName(imgFilePrefix + str(self.imageList[index]) + imgFileSuffix) #reader.CanReadFile('imgFilePrefix + str(self.imageList[0]) + imgFileSuffix') # model node model = slicer.vtkMRMLModelNode() model.SetScene(self.scene) model.SetName("test " + str(self.imageList[index]) + "cow") model.SetAndObservePolyData(planeSource.GetOutput()) # model display node modelDisplay = slicer.vtkMRMLModelDisplayNode() modelDisplay.BackfaceCullingOff() # so plane can be seen from both front and back face modelDisplay.SetScene(self.scene) self.scene.AddNode(modelDisplay) # connecting model node w/ its model display node model.SetAndObserveDisplayNodeID(modelDisplay.GetID()) # adding tiff file as texture to modelDisplay modelDisplay.SetAndObserveTextureImageData(reader.GetOutput()) self.scene.AddNode(model) # now doing a linear transform to set coordinates and orientation of plane transform = slicer.vtkMRMLLinearTransformNode() self.scene.AddNode(transform) model.SetAndObserveTransformNodeID(transform.GetID()) vTransform = vtk.vtkTransform() vTransform.Scale(150, 150, 150) vTransform.RotateX(self.rotateXList[index]) vTransform.RotateY(self.rotateYList[index]) vTransform.RotateZ(self.rotateZList[index]) transform.SetAndObserveMatrixTransformToParent(vTransform.GetMatrix())
def __init__(self, markupID, radius, length, position): # We use the markupID to check whether this tool's markup has # been removed in the onMarkupRemoved event self.markupID = markupID # Create a vtkCylinderSource for rendering the tool self.toolSrc = vtk.vtkCylinderSource() self.toolSrc.SetRadius(radius) self.toolSrc.SetHeight(length) # Create tool model using cylinder source self.modelNode = slicer.vtkMRMLModelNode() self.modelNode.HideFromEditorsOn() self.modelNode.SetName(slicer.mrmlScene.GenerateUniqueName("Tool")) polyData = self.toolSrc.GetOutput() self.modelNode.SetAndObservePolyData(polyData) slicer.mrmlScene.AddNode(self.modelNode) # Create a DisplayNode for this node (so that it can control its # own visibility) and have modelNode observe it self.modelDisplay = slicer.vtkMRMLModelDisplayNode() self.modelDisplay.SetColor(0, 1, 1) # cyan slicer.mrmlScene.AddNode(self.modelDisplay) self.modelNode.SetAndObserveDisplayNodeID( self.modelDisplay.GetID()) # Create a transform for our tool model that will scale it to # the proper radius, length, and position. Leave the orientation # at the default. self.transformNode = slicer.vtkMRMLLinearTransformNode() self.transformNode.HideFromEditorsOn() self.transformNode.SetName( slicer.mrmlScene.GenerateUniqueName("Transform")) self.updatePosition(position) slicer.mrmlScene.AddNode(self.transformNode) # apply the new transform to our tool self.modelNode.SetAndObserveTransformNodeID( self.transformNode.GetID()) # Set tool to be visible self.visible = True
def updateOutputNode(polydata): # clear scene scene=slicer.mrmlScene scene.Clear(0) # create fiber node fiber=slicer.vtkMRMLModelNode() fiber.SetScene(scene) fiber.SetName("QueryTract") fiber.SetAndObservePolyData(polydata) # create display model fiber node fiberDisplay=slicer.vtkMRMLModelDisplayNode() fiberDisplay.SetScene(scene) scene.AddNode(fiberDisplay) fiber.SetAndObserveDisplayNodeID(fiberDisplay.GetID()) # add to scene fiberDisplay.SetInputPolyData(polydata) scene.AddNode(fiber)
def pointModel(self, scene, point, name, color): """ Create a point model using sphere""" #Point sphere = vtk.vtkSphereSource() sphere.SetCenter(point) sphere.SetRadius(2) # Create model node pointModel = slicer.vtkMRMLModelNode() pointModel.SetScene(scene) pointModel.SetName(name) pointModel.SetAndObservePolyData(sphere.GetOutput()) #Create display node pointModelDisplay = slicer.vtkMRMLModelDisplayNode() pointModelDisplay.SetColor(color) pointModelDisplay.SetScene(scene) scene.AddNode(pointModelDisplay) pointModel.SetAndObserveDisplayNodeID(pointModelDisplay.GetID()) #Add to scene pointModelDisplay.SetInputPolyData(sphere.GetOutput()) scene.AddNode(pointModel)
def updateOutputNode(polydata): # clear scene scene = slicer.mrmlScene scene.Clear(0) # create fiber node fiber = slicer.vtkMRMLModelNode() fiber.SetScene(scene) fiber.SetName("QueryTract") fiber.SetAndObservePolyData(polydata) # create display model fiber node fiberDisplay = slicer.vtkMRMLModelDisplayNode() fiberDisplay.SetScene(scene) scene.AddNode(fiberDisplay) fiber.SetAndObserveDisplayNodeID(fiberDisplay.GetID()) # add to scene fiberDisplay.SetInputPolyData(polydata) scene.AddNode(fiber)
def AddDamageTemplateModel(self,scene,LineLandmarkTransform ): # check if already implemented if ( self.DamageTemplateModel != None ): print "removing", self.DamageTemplateModel.GetName() scene.RemoveNode(self.DamageTemplateModel) # create sphere and scale vtkSphere = vtk.vtkSphereSource() vtkSphere.SetRadius(1.) vtkSphere.SetThetaResolution(16) vtkSphere.SetPhiResolution(16) ScaleAffineTransform = vtk.vtkTransform() ScaleAffineTransform.Scale([self.AblationMinorAxis,self.AblationMajorAxis,self.AblationMinorAxis]) vtkEllipsoid= vtk.vtkTransformFilter() vtkEllipsoid.SetInput(vtkSphere.GetOutput() ) vtkEllipsoid.SetTransform( ScaleAffineTransform ) vtkEllipsoid.Update() slicertransformFilter = vtk.vtkTransformFilter() slicertransformFilter.SetInput(vtkEllipsoid.GetOutput() ) slicertransformFilter.SetTransform( LineLandmarkTransform ) slicertransformFilter.Update() dampolyData=slicertransformFilter.GetOutput(); # Create model node self.DamageTemplateModel = slicer.vtkMRMLModelNode() self.DamageTemplateModel.SetScene(scene) #self.DamageTemplateModel.SetName(scene.GenerateUniqueName("Treatment-%s" % fiducialsNode.GetName())) self.DamageTemplateModel.SetName( scene.GenerateUniqueName("Treatment") ) self.DamageTemplateModel.SetAndObservePolyData(dampolyData) # Create display node modelDisplay = slicer.vtkMRMLModelDisplayNode() modelDisplay.SetColor(1,1,0) # yellow modelDisplay.SetOpacity(0.3) modelDisplay.SetScene(scene) scene.AddNode(modelDisplay) self.DamageTemplateModel.SetAndObserveDisplayNodeID(modelDisplay.GetID()) # Add to scene modelDisplay.SetInputPolyData(self.DamageTemplateModel.GetPolyData()) scene.AddNode(self.DamageTemplateModel)
def updateScene(self): #self.scene.Undo() #self.scene.SaveStateForUndo(self.scene.GetNodes()) self.scene.RemoveNode(self.transform) self.scene.RemoveNode(self.modelDisplay) self.scene.RemoveNode(self.model) planeSource = vtk.vtkPlaneSource() planeSource.SetCenter(self.currentSlice.x, self.currentSlice.y, self.currentSlice.z) reader = vtk.vtkPNGReader() reader.SetFileName(self.currentSlice.name) # model node self.model = slicer.vtkMRMLModelNode() self.model.SetScene(self.scene) self.model.SetName(self.currentSlice.name) self.model.SetAndObservePolyData(planeSource.GetOutput()) # model display node self.modelDisplay = slicer.vtkMRMLModelDisplayNode() self.modelDisplay.BackfaceCullingOff() # so plane can be seen from both front and back face self.modelDisplay.SetScene(self.scene) self.scene.AddNode(self.modelDisplay) # connecting model node w/ its model display node self.model.SetAndObserveDisplayNodeID(self.modelDisplay.GetID()) # adding tiff file as texture to modelDisplay self.modelDisplay.SetAndObserveTextureImageData(reader.GetOutput()) self.scene.AddNode(self.model) # now doing a linear transform to set coordinates and orientation of plane self.transform = slicer.vtkMRMLLinearTransformNode() self.scene.AddNode(self.transform) self.model.SetAndObserveTransformNodeID(self.transform.GetID()) vTransform = vtk.vtkTransform() vTransform.Scale(self.currentSlice.scaling, self.currentSlice.scaling, self.currentSlice.scaling) vTransform.RotateX(self.currentSlice.xAngle) vTransform.RotateY(self.currentSlice.yAngle) vTransform.RotateZ(self.currentSlice.zAngle) self.transform.SetAndObserveMatrixTransformToParent(vTransform.GetMatrix())
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 tableCursor(self, dimensions=(900, 30, 600)): """Create the mrml structure to represent the table if needed otherwise return the current transform dimensions : left-right, up-down, in-out size of table """ transformName = 'Table-To-Camera' transformNode = slicer.util.getNode(transformName) if not transformNode: # make the mrml box = vtk.vtkCubeSource() box.SetXLength(dimensions[0]) box.SetYLength(dimensions[1]) box.SetZLength(dimensions[2]) box.SetCenter(0, -dimensions[1] / 2., 0) box.Update() # Create model node cursor = slicer.vtkMRMLModelNode() cursor.SetScene(slicer.mrmlScene) cursor.SetName("Cursor-Table") cursor.SetAndObservePolyData(box.GetOutput()) # Create display node cursorModelDisplay = slicer.vtkMRMLModelDisplayNode() cursorModelDisplay.SetColor( (0.86274509803921573, ) * 3) # 'gainsboro' cursorModelDisplay.SetOpacity(0.5) cursorModelDisplay.SetScene(slicer.mrmlScene) slicer.mrmlScene.AddNode(cursorModelDisplay) cursor.SetAndObserveDisplayNodeID(cursorModelDisplay.GetID()) # Add to slicer.mrmlScene cursorModelDisplay.SetInputPolyData(box.GetOutput()) slicer.mrmlScene.AddNode(cursor) # Create transform node transformNode = slicer.vtkMRMLLinearTransformNode() transformNode.SetName(transformName) slicer.mrmlScene.AddNode(transformNode) tableToCamera = vtk.vtkMatrix4x4() tableToCamera.SetElement(1, 3, -100) transformNode.GetMatrixTransformToParent().DeepCopy(tableToCamera) cursor.SetAndObserveTransformNodeID(transformNode.GetID()) return transformNode
def handCursor(self, whichHand='Left'): """Create the mrml structure to represent a hand cursor if needed otherwise return the current transform whichHand : 'Left' for left color, anything else for right also defines suffix for Transform and Cursor """ transformName = '%s-To-Table' % whichHand transformNode = slicer.util.getNode(transformName) if not transformNode: # make the mrml sphere = vtk.vtkSphereSource() sphere.Update() # Create model node cursor = slicer.vtkMRMLModelNode() cursor.SetScene(slicer.mrmlScene) cursor.SetName("Cursor-%s" % whichHand) cursor.SetAndObservePolyData(sphere.GetOutput()) # Create display node cursorModelDisplay = slicer.vtkMRMLModelDisplayNode() if whichHand == 'Left': color = (1, .84313725490196079, 0) # gold (wedding ring hand) else: color = (0.69411764705882351, 0.47843137254901963, 0.396078431372549) # slicer skin tone cursorModelDisplay.SetColor(color) cursorModelDisplay.SetScene(slicer.mrmlScene) slicer.mrmlScene.AddNode(cursorModelDisplay) cursor.SetAndObserveDisplayNodeID(cursorModelDisplay.GetID()) # Add to slicer.mrmlScene cursorModelDisplay.SetInputPolyData(sphere.GetOutput()) slicer.mrmlScene.AddNode(cursor) # Create transform node transformNode = slicer.vtkMRMLLinearTransformNode() transformNode.SetName(transformName) for i in xrange(3): transformNode.GetMatrixTransformToParent().SetElement(i, i, 10) slicer.mrmlScene.AddNode(transformNode) cursor.SetAndObserveTransformNodeID(transformNode.GetID()) handLineNode = self.handLine(whichHand) return transformNode, handLineNode
def tableCursor(self,dimensions=(900,30,600)): """Create the mrml structure to represent the table if needed otherwise return the current transform dimensions : left-right, up-down, in-out size of table """ transformName = 'Table-To-Camera' transformNode = slicer.util.getNode(transformName) if not transformNode: # make the mrml box = vtk.vtkCubeSource() box.SetXLength(dimensions[0]) box.SetYLength(dimensions[1]) box.SetZLength(dimensions[2]) box.SetCenter(0,-dimensions[1]/2.,0) box.Update() # Create model node cursor = slicer.vtkMRMLModelNode() cursor.SetScene(slicer.mrmlScene) cursor.SetName("Cursor-Table") cursor.SetAndObservePolyData(box.GetOutput()) # Create display node cursorModelDisplay = slicer.vtkMRMLModelDisplayNode() cursorModelDisplay.SetColor((0.86274509803921573,)*3) # 'gainsboro' cursorModelDisplay.SetOpacity(0.5) cursorModelDisplay.SetScene(slicer.mrmlScene) slicer.mrmlScene.AddNode(cursorModelDisplay) cursor.SetAndObserveDisplayNodeID(cursorModelDisplay.GetID()) # Add to slicer.mrmlScene cursorModelDisplay.SetInputPolyData(box.GetOutput()) slicer.mrmlScene.AddNode(cursor) # Create transform node transformNode = slicer.vtkMRMLLinearTransformNode() transformNode.SetName(transformName) slicer.mrmlScene.AddNode(transformNode) tableToCamera = vtk.vtkMatrix4x4() tableToCamera.SetElement(1, 3, -100) transformNode.GetMatrixTransformToParent().DeepCopy(tableToCamera) cursor.SetAndObserveTransformNodeID(transformNode.GetID()) return transformNode
def handCursor(self,whichHand='Left'): """Create the mrml structure to represent a hand cursor if needed otherwise return the current transform whichHand : 'Left' for left color, anything else for right also defines suffix for Transform and Cursor """ transformName = '%s-To-Table' % whichHand transformNode = slicer.util.getNode(transformName) if not transformNode: # make the mrml sphere = vtk.vtkSphereSource() sphere.Update() # Create model node cursor = slicer.vtkMRMLModelNode() cursor.SetScene(slicer.mrmlScene) cursor.SetName("Cursor-%s" % whichHand) cursor.SetAndObservePolyData(sphere.GetOutput()) # Create display node cursorModelDisplay = slicer.vtkMRMLModelDisplayNode() if whichHand == 'Left': color = (1,.84313725490196079,0) # gold (wedding ring hand) else: color = (0.69411764705882351, 0.47843137254901963, 0.396078431372549) # slicer skin tone cursorModelDisplay.SetColor(color) cursorModelDisplay.SetScene(slicer.mrmlScene) slicer.mrmlScene.AddNode(cursorModelDisplay) cursor.SetAndObserveDisplayNodeID(cursorModelDisplay.GetID()) # Add to slicer.mrmlScene cursorModelDisplay.SetInputPolyData(sphere.GetOutput()) slicer.mrmlScene.AddNode(cursor) # Create transform node transformNode = slicer.vtkMRMLLinearTransformNode() transformNode.SetName(transformName) for i in xrange(3): transformNode.GetMatrixTransformToParent().SetElement(i, i, 10) slicer.mrmlScene.AddNode(transformNode) cursor.SetAndObserveTransformNodeID(transformNode.GetID()) handLineNode = self.handLine(whichHand) return transformNode,handLineNode
def __init__(self, markupID, radius, length, position): # We use the markupID to check whether this tool's markup has # been removed in the onMarkupRemoved event self.markupID = markupID # Create a vtkCylinderSource for rendering the tool self.toolSrc = vtk.vtkCylinderSource() self.toolSrc.SetRadius(radius) self.toolSrc.SetHeight(length) # Create tool model using cylinder source self.modelNode = slicer.vtkMRMLModelNode() self.modelNode.HideFromEditorsOn() self.modelNode.SetName(slicer.mrmlScene.GenerateUniqueName("Tool")) polyData = self.toolSrc.GetOutput() self.modelNode.SetAndObservePolyData(polyData) slicer.mrmlScene.AddNode(self.modelNode) # Create a DisplayNode for this node (so that it can control its # own visibility) and have modelNode observe it self.modelDisplay = slicer.vtkMRMLModelDisplayNode() self.modelDisplay.SetColor(0,1,1) # cyan slicer.mrmlScene.AddNode(self.modelDisplay) self.modelNode.SetAndObserveDisplayNodeID(self.modelDisplay.GetID()) # Create a transform for our tool model that will scale it to # the proper radius, length, and position. Leave the orientation # at the default. self.transformNode = slicer.vtkMRMLLinearTransformNode() self.transformNode.HideFromEditorsOn() self.transformNode.SetName(slicer.mrmlScene.GenerateUniqueName("Transform")) self.updatePosition(position) slicer.mrmlScene.AddNode(self.transformNode) # apply the new transform to our tool self.modelNode.SetAndObserveTransformNodeID(self.transformNode.GetID()) # Set tool to be visible self.visible = True
def onHelloWorldButtonClicked(self): scene = slicer.mrmlScene inputModel = self.inputSelector.currentNode() bounds = [0, 0, 0, 0, 0, 0] inputModel.GetBounds(bounds) print('Model Name is:') print(inputModel.GetName()) X = bounds[1] - bounds[0] Y = bounds[3] - bounds[2] Z = bounds[5] - bounds[4] mid = (bounds[0] + X / 2, bounds[2] + Y / 2, bounds[4] + Z / 2) X_thick = .1 #TODO resolution input Y_thick = .1 #TODO resolution input Z_thick = .1 #TODO resolution input z_slices = int(math.ceil(Z / Z_thick)) y_slices = int(math.ceil(Y / Y_thick)) x_slices = int(math.ceil(X / X_thick)) x_thick = X / x_slices y_thick = Y / y_slices z_thick = Z / z_slices print('number of slices') print((x_slices, y_slices, z_slices)) print('midpoint') print(mid) #TODO Bounding box calculation imageSize = [x_slices, y_slices, z_slices] imageSpacing = [x_thick, y_thick, z_thick] voxelType = vtk.VTK_UNSIGNED_CHAR imageData = vtk.vtkImageData() imageData.SetDimensions(imageSize) imageData.AllocateScalars(voxelType, 1) thresholder = vtk.vtkImageThreshold() thresholder.SetInputData(imageData) thresholder.SetInValue(1) thresholder.SetOutValue(1) # Create volume node volumeNode = slicer.vtkMRMLScalarVolumeNode() volumeNode.SetSpacing(imageSpacing) volumeNode.SetImageDataConnection(thresholder.GetOutputPort()) # Add volume to scene slicer.mrmlScene.AddNode(volumeNode) displayNode = slicer.vtkMRMLScalarVolumeDisplayNode() slicer.mrmlScene.AddNode(displayNode) colorNode = slicer.util.getNode('Grey') displayNode.SetAndObserveColorNodeID(colorNode.GetID()) volumeNode.SetAndObserveDisplayNodeID(displayNode.GetID()) volumeNode.CreateDefaultStorageNode() #Transform the Volume to Fit Around the Model transform = slicer.vtkMRMLLinearTransformNode() scene.AddNode(transform) volumeNode.SetAndObserveTransformNodeID(transform.GetID()) vTransform = vtk.vtkTransform() vTransform.Translate( (-X / 2 + mid[0], -Y / 2 + mid[1], -Z / 2 + mid[2])) transform.SetAndObserveMatrixTransformToParent(vTransform.GetMatrix()) #Create a segmentation Node segmentationNode = slicer.vtkMRMLSegmentationNode() slicer.mrmlScene.AddNode(segmentationNode) segmentationNode.CreateDefaultDisplayNodes() segmentationNode.SetReferenceImageGeometryParameterFromVolumeNode( volumeNode) #Add the model as a segmentation #sphereSource = vtk.vtkSphereSource() #sphereSource.SetRadius(10) #sphereSource.SetCenter(6,30,28) #sphereSource.Update() #segmentationNode.AddSegmentFromClosedSurfaceRepresentation(sphereSource.GetOutput(), "Test") segmentID = segmentationNode.GetSegmentation().GenerateUniqueSegmentID( "Test") segmentationNode.AddSegmentFromClosedSurfaceRepresentation( inputModel.GetPolyData(), segmentID) #TODO, Unique ID segmentationNode.SetMasterRepresentationToBinaryLabelmap() modelLabelMap = segmentationNode.GetBinaryLabelmapRepresentation( segmentID) #TODO Unique ID segmentationNode.SetMasterRepresentationToBinaryLabelmap() shape = list(modelLabelMap.GetDimensions()) shape.reverse() #why reverse? labelArray = vtk.util.numpy_support.vtk_to_numpy( modelLabelMap.GetPointData().GetScalars()).reshape(shape) for n in range(1, shape[0] - 1): labelArray[n, :, :] = numpy.maximum(labelArray[n, :, :], labelArray[n - 1, :, :]) outputPolyData = vtk.vtkPolyData() slicer.vtkSlicerSegmentationsModuleLogic.GetSegmentClosedSurfaceRepresentation( segmentationNode, segmentID, outputPolyData) # Create model node model = slicer.vtkMRMLModelNode() model.SetScene(scene) model.SetName(scene.GenerateUniqueName("Model_Undercuts_Removed")) model.SetAndObservePolyData(outputPolyData) # Create display node modelDisplay = slicer.vtkMRMLModelDisplayNode() modelDisplay.SetColor(1, 1, 0) # yellow modelDisplay.SetBackfaceCulling(0) modelDisplay.SetScene(scene) scene.AddNode(modelDisplay) model.SetAndObserveDisplayNodeID(modelDisplay.GetID()) # Add to scene scene.AddNode(model)
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 createTemplateModel(self): self.templatePathVectors = [] self.templatePathOrigins = [] self.tempModelNode = slicer.mrmlScene.GetNodeByID(self.templateModelNodeID) if self.tempModelNode is None: self.tempModelNode = slicer.vtkMRMLModelNode() self.tempModelNode.SetName('NeedleGuideTemplate') slicer.mrmlScene.AddNode(self.tempModelNode) self.templateModelNodeID = self.tempModelNode.GetID() dnode = slicer.vtkMRMLModelDisplayNode() #dnode.SetColor(self.ModelColor) slicer.mrmlScene.AddNode(dnode) self.tempModelNode.SetAndObserveDisplayNodeID(dnode.GetID()) self.modelNodetag = self.tempModelNode.AddObserver(slicer.vtkMRMLTransformableNode.TransformModifiedEvent, self.onTemplateTransformUpdated) self.pathModelNode = slicer.mrmlScene.GetNodeByID(self.needlePathModelNodeID) if self.pathModelNode is None: self.pathModelNode = slicer.vtkMRMLModelNode() self.pathModelNode.SetName('NeedleGuideNeedlePath') slicer.mrmlScene.AddNode(self.pathModelNode) self.needlePathModelNodeID = self.pathModelNode.GetID() dnode = slicer.vtkMRMLModelDisplayNode() slicer.mrmlScene.AddNode(dnode) self.pathModelNode.SetAndObserveDisplayNodeID(dnode.GetID()) pathModelAppend = vtk.vtkAppendPolyData() tempModelAppend = vtk.vtkAppendPolyData() for row in self.templateConfig: p1 = numpy.array(row[0:3]) p2 = numpy.array(row[3:6]) tempLineSource = vtk.vtkLineSource() tempLineSource.SetPoint1(p1) tempLineSource.SetPoint2(p2) tempTubeFilter = vtk.vtkTubeFilter() tempTubeFilter.SetInputConnection(tempLineSource.GetOutputPort()) tempTubeFilter.SetRadius(1.0) tempTubeFilter.SetNumberOfSides(18) tempTubeFilter.CappingOn() tempTubeFilter.Update() pathLineSource = vtk.vtkLineSource() v = p2-p1 nl = numpy.linalg.norm(v) n = v/nl # normal vector l = row[6] p3 = p1 + l * n pathLineSource.SetPoint1(p1) pathLineSource.SetPoint2(p3) self.templatePathOrigins.append([row[0], row[1], row[2], 1.0]) self.templatePathVectors.append([n[0], n[1], n[2], 1.0]) self.templateMaxDepth.append(row[6]) pathTubeFilter = vtk.vtkTubeFilter() pathTubeFilter.SetInputConnection(pathLineSource.GetOutputPort()) pathTubeFilter.SetRadius(0.8) pathTubeFilter.SetNumberOfSides(18) pathTubeFilter.CappingOn() pathTubeFilter.Update() if vtk.VTK_MAJOR_VERSION <= 5: tempModelAppend.AddInput(tempTubeFilter.GetOutput()) pathModelAppend.AddInput(pathTubeFilter.GetOutput()) else: tempModelAppend.AddInputData(tempTubeFilter.GetOutput()) pathModelAppend.AddInputData(pathTubeFilter.GetOutput()) tempModelAppend.Update() self.tempModelNode.SetAndObservePolyData(tempModelAppend.GetOutput()) pathModelAppend.Update() self.pathModelNode.SetAndObservePolyData(pathModelAppend.GetOutput())
def takeUSSnapshot2(self,name): snapshotDisp = slicer.vtkMRMLModelDisplayNode() slicer.mrmlScene.AddNode(snapshotDisp) snapshotDisp.SetScene(slicer.mrmlScene) snapshotDisp.SetDisableModifiedEvent(1) snapshotDisp.SetOpacity(1.0) snapshotDisp.SetColor(1.0, 1.0, 1.0) snapshotDisp.SetAmbient(1.0) snapshotDisp.SetBackfaceCulling(0) snapshotDisp.SetDiffuse(0) snapshotDisp.SetSaveWithScene(0) snapshotDisp.SetDisableModifiedEvent(0) snapshotModel = slicer.vtkMRMLModelNode() snapshotModel.SetName(name) snapshotModel.SetDescription("Live Ultrasound Snapshot") snapshotModel.SetScene(slicer.mrmlScene) snapshotModel.SetAndObserveDisplayNodeID(snapshotDisp.GetID()) snapshotModel.SetHideFromEditors(0) snapshotModel.SetSaveWithScene(0) slicer.mrmlScene.AddNode(snapshotModel) image_RAS = slicer.util.getNode("Image_Image") dim = [0, 0, 0] imageData = image_RAS.GetImageData() imageData.GetDimensions(dim) plane = vtk.vtkPlaneSource() plane.Update() snapshotModel.SetAndObservePolyData(plane.GetOutput()) slicePolyData = snapshotModel.GetPolyData() slicePoints = slicePolyData.GetPoints() # In parent transform is saved the ReferenceToRAS transform parentTransform = vtk.vtkTransform() parentTransform.Identity() if not image_RAS.GetParentTransformNode() == None: parentMatrix = vtk.vtkMatrix4x4() parentTransformNode = image_RAS.GetParentTransformNode() parentTransformNode.GetMatrixTransformToWorld(parentMatrix) # aux=parentTransform.GetMatrix() # aux.DeepCopy(parentMatrix) # parentTransform.Update() parentTransform.SetMatrix(parentMatrix) inImageTransform = vtk.vtkTransform() inImageTransform.Identity() image_RAS.GetIJKToRASMatrix(inImageTransform.GetMatrix()) tImageToRAS = vtk.vtkTransform() tImageToRAS.Identity() tImageToRAS.PostMultiply() tImageToRAS.Concatenate(inImageTransform) tImageToRAS.Concatenate(parentTransform) tImageToRAS.Update() point1Image = [0.0, 0.0, 0.0, 1.0] point2Image = [dim[0], 0.0, 0.0, 1.0] point3Image = [0.0, dim[1], 0.0, 1.0] point4Image = [dim[0], dim[1], 0.0, 1.0] point1RAS = [0.0, 0.0, 0.0, 0.0] point2RAS = [0.0, 0.0, 0.0, 0.0] point3RAS = [0.0, 0.0, 0.0, 0.0] point4RAS = [0.0, 0.0, 0.0, 0.0] tImageToRAS.MultiplyPoint(point1Image, point1RAS) tImageToRAS.MultiplyPoint(point2Image, point2RAS) tImageToRAS.MultiplyPoint(point3Image, point3RAS) tImageToRAS.MultiplyPoint(point4Image, point4RAS) p1RAS = [point1RAS[0], point1RAS[1], point1RAS[2]] p2RAS = [point2RAS[0], point2RAS[1], point2RAS[2]] p3RAS = [point3RAS[0], point3RAS[1], point3RAS[2]] p4RAS = [point4RAS[0], point4RAS[1], point4RAS[2]] slicePoints.SetPoint(0, p1RAS) slicePoints.SetPoint(1, p2RAS) slicePoints.SetPoint(2, p3RAS) slicePoints.SetPoint(3, p4RAS) # # Add image texture. image = vtk.vtkImageData() image.DeepCopy(imageData) modelDisplayNode = snapshotModel.GetModelDisplayNode() modelDisplayNode.SetAndObserveTextureImageData(image) snapshotTexture = slicer.vtkMRMLScalarVolumeNode() snapshotTexture.SetAndObserveImageData(image) snapshotTexture.SetName(name + "_Texture") slicer.mrmlScene.AddNode(snapshotTexture) snapshotTexture.CopyOrientation( image_RAS ) snapshotTextureDisplayNode = slicer.vtkMRMLScalarVolumeDisplayNode() snapshotTextureDisplayNode.SetName(name + "_TextureDisplay") snapshotTextureDisplayNode.SetAutoWindowLevel(0); snapshotTextureDisplayNode.SetWindow(256); snapshotTextureDisplayNode.SetLevel(128); snapshotTextureDisplayNode.SetDefaultColorMap(); slicer.mrmlScene.AddNode(snapshotTextureDisplayNode) snapshotTexture.AddAndObserveDisplayNodeID( snapshotTextureDisplayNode.GetID() ) snapshotModel.SetAttribute( "TextureNodeID", snapshotTexture.GetID() ) snapshotModelDisplayNode= snapshotModel.GetModelDisplayNode() snapshotModelDisplayNode.SetAndObserveTextureImageData( snapshotTexture.GetImageData() )
def transform(self, cmd): if not hasattr(self, 'p'): self.p = numpy.zeros(3) self.dpdt = numpy.zeros(3) self.d2pdt2 = numpy.zeros(3) self.o = numpy.zeros(3) self.dodt = numpy.zeros(3) self.d2odt2 = numpy.zeros(3) p = urlparse.urlparse(cmd) q = urlparse.parse_qs(p.query) self.logMessage(q) dt = float(q['interval'][0]) self.d2pdt2 = 1000 * numpy.array( [float(q['x'][0]), float(q['y'][0]), float(q['z'][0])]) if not hasattr(self, 'g0'): self.g0 = self.d2pdt2 self.d2pdt2 = self.d2pdt2 - self.g0 self.dpdt = self.dpdt + dt * self.d2pdt2 self.p = self.p + dt * self.dpdt # TODO: integrate rotations if not hasattr(self, "idevice"): """ set up the mrml parts or use existing """ nodes = slicer.mrmlScene.GetNodesByName('idevice') if nodes.GetNumberOfItems() > 0: self.idevice = nodes.GetItemAsObject(0) nodes = slicer.mrmlScene.GetNodesByName('tracker') self.tracker = nodes.GetItemAsObject(0) else: # idevice cursor self.cube = vtk.vtkCubeSource() self.cube.SetXLength(30) self.cube.SetYLength(70) self.cube.SetZLength(5) self.cube.Update() # display node self.modelDisplay = slicer.vtkMRMLModelDisplayNode() self.modelDisplay.SetColor(1, 1, 0) # yellow slicer.mrmlScene.AddNode(self.modelDisplay) self.modelDisplay.SetPolyData(self.cube.GetOutput()) # Create model node self.idevice = slicer.vtkMRMLModelNode() self.idevice.SetScene(slicer.mrmlScene) self.idevice.SetName("idevice") self.idevice.SetAndObservePolyData(self.cube.GetOutput()) self.idevice.SetAndObserveDisplayNodeID( self.modelDisplay.GetID()) slicer.mrmlScene.AddNode(self.idevice) # tracker self.tracker = slicer.vtkMRMLLinearTransformNode() self.tracker.SetName('tracker') slicer.mrmlScene.AddNode(self.tracker) self.idevice.SetAndObserveTransformNodeID(self.tracker.GetID()) m = self.tracker.GetMatrixTransformToParent() m.Identity() up = numpy.zeros(3) up[2] = 1 d = self.d2pdt2 dd = d / numpy.sqrt(numpy.dot(d, d)) xx = numpy.cross(dd, up) yy = numpy.cross(dd, xx) for row in xrange(3): m.SetElement(row, 0, dd[row]) m.SetElement(row, 1, xx[row]) m.SetElement(row, 2, yy[row]) #m.SetElement(row,3, self.p[row]) return ("got it")
def computeSpline(self, spline, startVertexID, endVertexID, startPointPosition, endPointPosition, resolution): print ("compute spline") scene = slicer.mrmlScene dijkstra = vtk.vtkDijkstraGraphGeodesicPath() dijkstra.SetInputData(self.modelNode.GetPolyData()) dijkstra.SetStartVertex(startVertexID) dijkstra.SetEndVertex(endVertexID) dijkstra.Update() #compute step size in according to resolution vertices = dijkstra.GetOutput().GetPoints() numVertices = vertices.GetNumberOfPoints() resStepSize = float(numVertices) / (float(resolution) - 1.0)# -2 because of start and end point print (numVertices) print (resolution) print (resStepSize) equidistantIndices = [] curStep = 0 for i in range(0, int(resolution)): curStep = (i * resStepSize) - 1 equidistantIndices.append(int(curStep + 0.5)) #create spline splinePoints = [] points = vtk.vtkPoints() for index in equidistantIndices: print ("index") print (index) print ("position") position = [0, 0, 0] vertices.GetPoint(index, position) print (position) points.InsertNextPoint(position) splinePoints.append(position) spline.points = splinePoints parametricSpline = vtk.vtkParametricSpline() parametricSpline.SetPoints(points) functionSource = vtk.vtkParametricFunctionSource() functionSource.SetParametricFunction(parametricSpline) functionSource.Update() #create model node splineModel = slicer.vtkMRMLModelNode() splineModel.SetScene(scene) splineModel.SetName("splineModel-%i" % 1) #todo splineModel.SetAndObservePolyData(functionSource.GetOutput()) #create display node splineModelDisplay = slicer.vtkMRMLModelDisplayNode() splineModelDisplay.SetColor(1, 0, 0) splineModelDisplay.SetOpacity(1) splineModelDisplay.SetLineWidth(4) splineModelDisplay.SliceIntersectionVisibilityOn() splineModelDisplay.SetScene(scene) scene.AddNode(splineModelDisplay) splineModel.SetAndObserveDisplayNodeID(splineModelDisplay.GetID()) # add to scene splineModelDisplay.GetPolyData = functionSource.GetOutput() scene.AddNode(splineModel) splineModelTransform = slicer.vtkMRMLLinearTransformNode() splineModelTransform.SetName("SplineModelTransform-%i" % 1) # todo scene.AddNode(splineModelTransform)
def setupScene(self): #applet specific logging.debug('setupScene') Guidelet.setupScene(self) logging.debug('Create transforms') self.cauteryTipToCautery = slicer.util.getNode('CauteryTipToCautery') if not self.cauteryTipToCautery: self.cauteryTipToCautery = slicer.vtkMRMLLinearTransformNode() self.cauteryTipToCautery.SetName("CauteryTipToCautery") m = self.readTransformFromSettings('CauteryTipToCautery') if m: self.cauteryTipToCautery.SetMatrixTransformToParent(m) slicer.mrmlScene.AddNode(self.cauteryTipToCautery) self.cauteryModelToCauteryTip = slicer.util.getNode( 'CauteryModelToCauteryTip') if not self.cauteryModelToCauteryTip: self.cauteryModelToCauteryTip = slicer.vtkMRMLLinearTransformNode() self.cauteryModelToCauteryTip.SetName("CauteryModelToCauteryTip") m = self.readTransformFromSettings('CauteryModelToCauteryTip') if m: self.cauteryModelToCauteryTip.SetMatrixTransformToParent(m) self.cauteryModelToCauteryTip.SetMatrixTransformToParent(m) slicer.mrmlScene.AddNode(self.cauteryModelToCauteryTip) self.needleTipToNeedle = slicer.util.getNode('NeedleTipToNeedle') if not self.needleTipToNeedle: self.needleTipToNeedle = slicer.vtkMRMLLinearTransformNode() self.needleTipToNeedle.SetName("NeedleTipToNeedle") m = self.readTransformFromSettings('NeedleTipToNeedle') if m: self.needleTipToNeedle.SetMatrixTransformToParent(m) slicer.mrmlScene.AddNode(self.needleTipToNeedle) self.needleModelToNeedleTip = slicer.util.getNode( 'NeedleModelToNeedleTip') if not self.needleModelToNeedleTip: self.needleModelToNeedleTip = slicer.vtkMRMLLinearTransformNode() self.needleModelToNeedleTip.SetName("NeedleModelToNeedleTip") m = self.readTransformFromSettings('NeedleModelToNeedleTip') if m: self.needleModelToNeedleTip.SetMatrixTransformToParent(m) self.needleModelToNeedleTip.SetMatrixTransformToParent(m) slicer.mrmlScene.AddNode(self.needleModelToNeedleTip) self.cauteryCameraToCautery = slicer.util.getNode( 'CauteryCameraToCautery') if not self.cauteryCameraToCautery: self.cauteryCameraToCautery = slicer.vtkMRMLLinearTransformNode() self.cauteryCameraToCautery.SetName("CauteryCameraToCautery") m = vtk.vtkMatrix4x4() m.SetElement(0, 0, 0) m.SetElement(0, 2, -1) m.SetElement(1, 1, 0) m.SetElement(1, 0, 1) m.SetElement(2, 2, 0) m.SetElement(2, 1, -1) self.cauteryCameraToCautery.SetMatrixTransformToParent(m) slicer.mrmlScene.AddNode(self.cauteryCameraToCautery) self.CauteryToNeedle = slicer.util.getNode('CauteryToNeedle') if not self.CauteryToNeedle: self.CauteryToNeedle = slicer.vtkMRMLLinearTransformNode() self.CauteryToNeedle.SetName("CauteryToNeedle") slicer.mrmlScene.AddNode(self.CauteryToNeedle) # Create transforms that will be updated through OpenIGTLink self.cauteryToReference = slicer.util.getNode('CauteryToReference') if not self.cauteryToReference: self.cauteryToReference = slicer.vtkMRMLLinearTransformNode() self.cauteryToReference.SetName("CauteryToReference") slicer.mrmlScene.AddNode(self.cauteryToReference) self.needleToReference = slicer.util.getNode('NeedleToReference') if not self.needleToReference: self.needleToReference = slicer.vtkMRMLLinearTransformNode() self.needleToReference.SetName("NeedleToReference") slicer.mrmlScene.AddNode(self.needleToReference) # Cameras logging.debug('Create cameras') self.LeftCamera = slicer.util.getNode('Left Camera') if not self.LeftCamera: self.LeftCamera = slicer.vtkMRMLCameraNode() self.LeftCamera.SetName("Left Camera") slicer.mrmlScene.AddNode(self.LeftCamera) self.RightCamera = slicer.util.getNode('Right Camera') if not self.RightCamera: self.RightCamera = slicer.vtkMRMLCameraNode() self.RightCamera.SetName("Right Camera") slicer.mrmlScene.AddNode(self.RightCamera) # Models logging.debug('Create models') self.cauteryModel_CauteryTip = slicer.util.getNode('CauteryModel') if not self.cauteryModel_CauteryTip: if (self.parameterNode.GetParameter('TestMode') == 'True'): moduleDirectoryPath = slicer.modules.lumpnav.path.replace( 'LumpNav.py', '') slicer.util.loadModel( qt.QDir.toNativeSeparators( moduleDirectoryPath + '../../../models/temporary/cautery.stl')) self.cauteryModel_CauteryTip = slicer.util.getNode( pattern="cautery") else: slicer.modules.createmodels.logic().CreateNeedle( 100, 1.0, 2.5, 0) self.cauteryModel_CauteryTip = slicer.util.getNode( pattern="NeedleModel") self.cauteryModel_CauteryTip.GetDisplayNode().SetColor( 1.0, 1.0, 0) self.cauteryModel_CauteryTip.SetName("CauteryModel") self.needleModel_NeedleTip = slicer.util.getNode('NeedleModel') if not self.needleModel_NeedleTip: slicer.modules.createmodels.logic().CreateNeedle(80, 1.0, 2.5, 0) self.needleModel_NeedleTip = slicer.util.getNode( pattern="NeedleModel") self.needleModel_NeedleTip.GetDisplayNode().SetColor( 0.333333, 1.0, 1.0) self.needleModel_NeedleTip.SetName("NeedleModel") self.needleModel_NeedleTip.GetDisplayNode( ).SliceIntersectionVisibilityOn() # Create surface from point set logging.debug('Create surface from point set') self.tumorModel_Needle = slicer.util.getNode('TumorModel') if not self.tumorModel_Needle: self.tumorModel_Needle = slicer.vtkMRMLModelNode() self.tumorModel_Needle.SetName("TumorModel") sphereSource = vtk.vtkSphereSource() sphereSource.SetRadius(0.001) self.tumorModel_Needle.SetPolyDataConnection( sphereSource.GetOutputPort()) slicer.mrmlScene.AddNode(self.tumorModel_Needle) # Add display node modelDisplayNode = slicer.vtkMRMLModelDisplayNode() modelDisplayNode.SetColor(0, 1, 0) # Green modelDisplayNode.BackfaceCullingOff() modelDisplayNode.SliceIntersectionVisibilityOn() modelDisplayNode.SetSliceIntersectionThickness(4) modelDisplayNode.SetOpacity(0.3) # Between 0-1, 1 being opaque slicer.mrmlScene.AddNode(modelDisplayNode) self.tumorModel_Needle.SetAndObserveDisplayNodeID( modelDisplayNode.GetID()) tumorMarkups_Needle = slicer.util.getNode('T') if not tumorMarkups_Needle: tumorMarkups_Needle = slicer.vtkMRMLMarkupsFiducialNode() tumorMarkups_Needle.SetName("T") slicer.mrmlScene.AddNode(tumorMarkups_Needle) tumorMarkups_Needle.CreateDefaultDisplayNodes() tumorMarkups_Needle.GetDisplayNode().SetTextScale(0) self.setAndObserveTumorMarkupsNode(tumorMarkups_Needle) # Set up breach warning node logging.debug('Set up breach warning') self.breachWarningNode = slicer.util.getNode('LumpNavBreachWarning') if not self.breachWarningNode: self.breachWarningNode = slicer.mrmlScene.CreateNodeByClass( 'vtkMRMLBreachWarningNode') self.breachWarningNode.SetName("LumpNavBreachWarning") slicer.mrmlScene.AddNode(self.breachWarningNode) self.breachWarningNode.SetPlayWarningSound(True) self.breachWarningNode.SetWarningColor(1, 0, 0) self.breachWarningNode.SetOriginalColor( self.tumorModel_Needle.GetDisplayNode().GetColor()) self.breachWarningNode.SetAndObserveToolTransformNodeId( self.cauteryTipToCautery.GetID()) self.breachWarningNode.SetAndObserveWatchedModelNodeID( self.tumorModel_Needle.GetID()) # Set up breach warning light import BreachWarningLight logging.debug('Set up breach warning light') self.breachWarningLightLogic = BreachWarningLight.BreachWarningLightLogic( ) self.breachWarningLightLogic.setMarginSizeMm( float( self.parameterNode.GetParameter( 'BreachWarningLightMarginSizeMm'))) if (self.parameterNode.GetParameter('EnableBreachWarningLight') == 'True'): logging.debug("BreachWarningLight: active") self.breachWarningLightLogic.startLightFeedback( self.breachWarningNode, self.connectorNode) else: logging.debug("BreachWarningLight: shutdown") self.breachWarningLightLogic.shutdownLight(self.connectorNode) # Build transform tree logging.debug('Set up transform tree') self.cauteryToReference.SetAndObserveTransformNodeID( self.ReferenceToRas.GetID()) self.cauteryCameraToCautery.SetAndObserveTransformNodeID( self.cauteryToReference.GetID()) self.cauteryTipToCautery.SetAndObserveTransformNodeID( self.cauteryToReference.GetID()) self.cauteryModelToCauteryTip.SetAndObserveTransformNodeID( self.cauteryTipToCautery.GetID()) self.needleToReference.SetAndObserveTransformNodeID( self.ReferenceToRas.GetID()) self.needleTipToNeedle.SetAndObserveTransformNodeID( self.needleToReference.GetID()) self.needleModelToNeedleTip.SetAndObserveTransformNodeID( self.needleTipToNeedle.GetID()) self.cauteryModel_CauteryTip.SetAndObserveTransformNodeID( self.cauteryModelToCauteryTip.GetID()) self.needleModel_NeedleTip.SetAndObserveTransformNodeID( self.needleModelToNeedleTip.GetID()) self.tumorModel_Needle.SetAndObserveTransformNodeID( self.needleToReference.GetID()) self.tumorMarkups_Needle.SetAndObserveTransformNodeID( self.needleToReference.GetID()) # self.liveUltrasoundNode_Reference.SetAndObserveTransformNodeID(self.ReferenceToRas.GetID()) # Hide slice view annotations (patient name, scale, color bar, etc.) as they # decrease reslicing performance by 20%-100% logging.debug('Hide slice view annotations') import DataProbe dataProbeUtil = DataProbe.DataProbeLib.DataProbeUtil() dataProbeParameterNode = dataProbeUtil.getParameterNode() dataProbeParameterNode.SetParameter('showSliceViewAnnotations', '0')
def onCompute(self): slicer.app.processEvents() import time # Show the status bar self.progressBar.show() # Initilize various parameters self.bone_labels = np.fromstring(self.lineedit.text, dtype=int, sep=',') # Check to see if self.bone_labels is set to negative on and if so set to the default labels if self.bone_labels[0] == -1: # Use the minimum and maximum of the Ref_Bone_Slider (which is based on the minimum and maximum label in the first image) self.bone_labels = range(int(self.Ref_Bone_Slider.minimum), int(self.Ref_Bone_Slider.maximum) + 1) self.max_bone_label = np.max(self.bone_labels) # Find all the files in the input folder self.files = os.listdir(self.directory_path) # Sort the files to be in order now self.files.sort(key=self.alphanum_key) if self.num_files > len(self.files): self.num_files = len(self.files) # Initilize a list of file indicies if self.num_files == -1: self.file_list = range(0, len(self.files)) else: self.file_list = range(0, int(self.num_files)) # Initilize Python list to hold all of the polydata # One index for each bone label (ranges from 1 to 9) polydata_list = [] for i in range(0, self.max_bone_label + 1): polydata_list.append([]) # Load all of the images from the input folder images_list = [] for curr_file in self.file_list: # Update the status bar self.progressBar.setValue( float(curr_file) / len(self.file_list) * 100 / 10) # Use 10% of the status bar for loading the images slicer.app.processEvents() slicer.util.showStatusMessage("Loading Images...") if self.files[curr_file][-3:] == 'nii': print(str('Running file number ' + str(curr_file))) # Load the nifti (.nii) or analyze image (.img/.hdr) using SimpleITK filename = os.path.join(self.directory_path, self.files[curr_file]) image = self.load_image(filename) # It's upside-down when loaded, so add a flip filter if self.flip_image_vertically.checked == True: imflip = vtk.vtkImageFlip() try: imflip.SetInputData(image.GetOutput()) except: imflip.SetInputData(image) imflip.SetFilteredAxis(1) imflip.Update() image = imflip.GetOutput() # If the images are flipped left/right so use a flip filter if self.flip_image_horizontally.checked == True: imflip = vtk.vtkImageFlip() try: imflip.SetInputData(image.GetOutput()) except: imflip.SetInputData(image) imflip.SetFilteredAxis(0) imflip.Update() image = imflip.GetOutput() # Append the loaded image to the images_list images_list.append(image) # Temporarily push the image to Slicer (to have the correct class type for the model maker Slicer module) if self.debug_show_images.checked == True: image = sitk.ReadImage(filename) sitkUtils.PushToSlicer(image, str(curr_file), 0, overwrite=True) node = slicer.util.getNode(str(curr_file)) # If there is a non .nii file in the folder the images_list will be shorter than file_list # Redefine the file_list here self.file_list = range(0, len(images_list)) iter = 0 # For status bar # Extract the surface from each image (i.e. the polydata) for label in self.bone_labels: for curr_file in self.file_list: # Update the status bar (start at 10%) self.progressBar.setValue( 10 + float(iter) / (len(self.bone_labels) * len(self.file_list)) * 100 / 5) # Use 20% of the bar for this slicer.app.processEvents() iter = iter + 1 slicer.util.showStatusMessage("Extracting Surfaces...") polydata = self.Extract_Surface(images_list[curr_file], label) polydata_list[label].append(polydata) # Create model node ("Extract_Shapes") and add to scene if self.show_extracted_shapes.checked == True: Extract_Shapes = slicer.vtkMRMLModelNode() Extract_Shapes.SetAndObservePolyData(polydata) modelDisplay = slicer.vtkMRMLModelDisplayNode() modelDisplay.SetSliceIntersectionVisibility( True) # Show in slice view modelDisplay.SetVisibility(True) # Show in 3D view slicer.mrmlScene.AddNode(modelDisplay) Extract_Shapes.SetAndObserveDisplayNodeID( modelDisplay.GetID()) slicer.mrmlScene.AddNode(Extract_Shapes) # Save each registered bone separately? if self.Save_Extracted_Bones_Separately.checked == True: for label in self.bone_labels: for i in range(0, len(self.file_list)): path = os.path.join( self.output_directory_path, 'Bone_' + str(label) + '_position_' + str(i) + '.ply') plyWriter = vtk.vtkPLYWriter() plyWriter.SetFileName(path) plyWriter.SetInputData(polydata_list[label][i]) plyWriter.Write() print('Saved: ' + path) # If this is set to true, stop the computation after extracting and smoothing the bones if self.Skip_Registration.checked == True: # Set the status bar to 100% self.progressBar.setValue(100) slicer.app.processEvents() slicer.util.showStatusMessage("Skipping Registration Step...") # Hide the status bar self.progressBar.hide() # Reset the status message on bottom of 3D Slicer slicer.util.showStatusMessage(" ") return 0 # Update the status bar (start at 30%) self.progressBar.setValue(30 + 20) # Use 20% of the bar for this slicer.app.processEvents() slicer.util.showStatusMessage("Calculating Reference Shapes...") # Don't use the mean shapes # Use the bone shapes from volunteer 1 instead of the mean shape for each bone # Initialize a Python list to hold the reference shapes reference_shapes = [] # One index for each bone label (ranges from 1 to 9) for i in range(0, self.max_bone_label + 1): reference_shapes.append([]) # Get the bone shapes from the first volunteer and save them for label in self.bone_labels: reference_shapes[label].append(polydata_list[label][0]) ######### Register the reference shape to each bone position ######### iter_bar = 0 # For status bar for label in self.bone_labels: for i in range(0, len(self.file_list)): # Update the status bar (start at 50%) self.progressBar.setValue( 50 + float(iter_bar) / (len(self.bone_labels) * len(self.file_list)) * 100 / 5) # Use 20% of the bar for this slicer.app.processEvents() iter_bar = iter_bar + 1 slicer.util.showStatusMessage( "Registering Reference Shapes...") transformedSource = self.IterativeClosestPoint( target=polydata_list[label][i], source=reference_shapes[label][0]) # Replace the surface of file i and label with the registered reference shape for that particular bone polydata_list[label][i] = transformedSource iter_bar = 0 # For status bar ######### Register the reference bone (usually the radius for the wrist) for all the volunteers together ######### for label in self.bone_labels: for i in range(0, len(self.file_list)): # !! IMPORTANT !! Register the reference bone last (or else the bones afterwards will not register correctly) # Skip the reference label for now (register after all the other bones are registered) if label != self.ref_label: # Update the status bar (start at 70%) self.progressBar.setValue( 70 + float(iter_bar) / (len(self.bone_labels) * len(self.file_list)) * 100 / 5) # Use 20% of the bar for this slicer.app.processEvents() iter_bar = iter_bar + 1 slicer.util.showStatusMessage( "Registering Radius Together...") polydata_list[label][i] = self.IterativeClosestPoint( target=polydata_list[self.ref_label][0], source=polydata_list[self.ref_label][i], reference=polydata_list[label][i]) # Now register the reference label bones together for i in range(0, len(self.file_list)): polydata_list[self.ref_label][i] = self.IterativeClosestPoint( target=polydata_list[self.ref_label][0], source=polydata_list[self.ref_label][i], reference=polydata_list[self.ref_label][i]) ######### Save the output ######### # Should the reference bone be remove (i.e. not saved) in the final PLY surface file? if self.Remove_Ref_Bone.checked == True: index = np.argwhere(self.bone_labels == self.ref_label) self.bone_labels = np.delete(self.bone_labels, index) # Combine the surfaces of the wrist for each person and save as a .PLY file for i in range(0, len(self.file_list)): temp_combine_list = [] # Update the status bar (start at 90%) self.progressBar.setValue(90 + float(i) / len(self.file_list) * 100 / 10) # Use 10% of the bar for this slicer.app.processEvents() iter_bar = iter_bar + 1 slicer.util.showStatusMessage("Saving Output Surfaces...") total_points = [0] # Get all the bones in a Python list for volunteer 'i' for label in self.bone_labels: temp_combine_list.append(polydata_list[label][i]) # Print the number of surface points for this bone num_points = polydata_list[label][i].GetNumberOfPoints() print("Bone " + str(label) + " points: " + str(num_points)) total_points.append(total_points[-1] + num_points) print("Total Cumulative Points" + str(total_points)) # Combined the surfaces in the list into a single polydata surface combined_polydata = self.Combine_Surfaces(temp_combine_list) # Create model node ("ICP_Result") and add to scene if self.show_registered_shapes.checked == True: ICP_Result = slicer.vtkMRMLModelNode() ICP_Result.SetAndObservePolyData(combined_polydata) modelDisplay = slicer.vtkMRMLModelDisplayNode() modelDisplay.SetSliceIntersectionVisibility( True) # Show in slice view modelDisplay.SetVisibility(True) # Show in 3D view slicer.mrmlScene.AddNode(modelDisplay) ICP_Result.SetAndObserveDisplayNodeID(modelDisplay.GetID()) slicer.mrmlScene.AddNode(ICP_Result) # Write the combined polydata surface to a .PLY file plyWriter = vtk.vtkPLYWriter() path = os.path.join(self.output_directory_path, str(self.files[i][:-4]) + '_combined.ply') plyWriter.SetFileName(path) plyWriter.SetInputData(combined_polydata) plyWriter.Write() print('Saved: ' + path) # Save each registered bone separately as well? if self.Save_Registered_Bones_Separately.checked == True: for label in self.bone_labels: path = os.path.join( self.output_directory_path, 'Position_' + str(i) + '_bone_' + str(label) + '.ply') plyWriter.SetFileName(path) plyWriter.SetInputData(polydata_list[label][i]) plyWriter.Write() print('Saved: ' + path) # Set the status bar to 100% self.progressBar.setValue(100) # Hide the status bar self.progressBar.hide() # Reset the status message on bottom of 3D Slicer slicer.util.showStatusMessage(" ") return 0
def updateCurve(self): if self.AutomaticUpdate == False: return if self.SourceNode and self.DestinationNode: if self.SourceNode.GetNumberOfFiducials() < 2: if self.CurvePoly != None: self.CurvePoly.Initialize() self.CurveLength = 0.0 else: if self.CurvePoly == None: self.CurvePoly = vtk.vtkPolyData() if self.DestinationNode.GetDisplayNodeID() == None: modelDisplayNode = slicer.vtkMRMLModelDisplayNode() modelDisplayNode.SetColor(self.ModelColor) slicer.mrmlScene.AddNode(modelDisplayNode) self.DestinationNode.SetAndObserveDisplayNodeID( modelDisplayNode.GetID()) if self.InterpolationMethod == 0: if self.RingMode > 0: self.nodeToPoly(self.SourceNode, self.CurvePoly, True) else: self.nodeToPoly(self.SourceNode, self.CurvePoly, False) elif self.InterpolationMethod == 1: # Cardinal Spline if self.RingMode > 0: self.nodeToPolyCardinalSpline(self.SourceNode, self.CurvePoly, True) else: self.nodeToPolyCardinalSpline(self.SourceNode, self.CurvePoly, False) elif self.InterpolationMethod == 2: # Hermite Spline if self.RingMode > 0: self.nodeToPolyHermiteSpline(self.SourceNode, self.CurvePoly, True) else: self.nodeToPolyHermiteSpline(self.SourceNode, self.CurvePoly, False) self.CurveLength = self.calculateLineLength(self.CurvePoly) tubeFilter = vtk.vtkTubeFilter() curvatureValues = vtk.vtkDoubleArray() if self.Curvature: ## If the curvature option is ON, calculate the curvature along the curve. (meanKappa, minKappa, maxKappa) = self.computeCurvatures(self.CurvePoly, curvatureValues) self.CurvePoly.GetPointData().AddArray(curvatureValues) self.curvatureMeanKappa = meanKappa self.curvatureMinKappa = minKappa self.curvatureMaxKappa = maxKappa else: self.curvatureMeanKappa = None self.curvatureMinKappa = None self.curvatureMaxKappa = None tubeFilter.SetInputData(self.CurvePoly) tubeFilter.SetRadius(self.TubeRadius) tubeFilter.SetNumberOfSides(20) tubeFilter.CappingOn() tubeFilter.Update() # self.DestinationNode.SetAndObservePolyData(tubeFilter.GetOutput()) self.DestinationNode.SetAndObservePolyData(self.CurvePoly) self.DestinationNode.Modified() if self.DestinationNode.GetScene() == None: slicer.mrmlScene.AddNode(self.DestinationNode) displayNode = self.DestinationNode.GetDisplayNode() if displayNode: if self.Curvature: displayNode.SetActiveScalarName('Curvature') else: displayNode.SetActiveScalarName('')
def runSegmentation(self, elList, volume, parentPath, deetoExe, models, createVTK): ### CHECK that both the fiducials and ct volume have been selected if (len(elList) == 0): # notify error slicer.util.showStatusMessage("Error, no electrode list selected") return if (volume == None): # notify error slicer.util.showStatusMessage("Error, no volume selected") return ### COMPUTE THE THRESHOLD the 45% of points not null(0.0) im = volume.GetImageData() # linearize the 3D image in a vector vector = vtk.util.numpy_support.vtk_to_numpy( im.GetPointData().GetScalars()) # eliminate 0.0 value from the vector n_vector = vector[vector != 0] # sort the intensity values n_vector.sort() # compute the threshold as the 45% of points not null threshold = n_vector[int(n_vector.size * 0.45)] ### CREATE A NEW FIDUCIAL LIST CALLED ...... [TODO] mlogic = slicer.modules.markups.logic() ### ### [TODO] Accrocchio, non so come cambiare questi parametri solo ### per il nodo corrente, invece che di default mlogic.SetDefaultMarkupsDisplayNodeTextScale(1.3) mlogic.SetDefaultMarkupsDisplayNodeGlyphScale(1.5) mlogic.SetDefaultMarkupsDisplayNodeColor(0.39, 0.78, 0.78) # AZZURRO mlogic.SetDefaultMarkupsDisplayNodeSelectedColor(0.39, 1.0, 0.39) # VERDONE fidNode = slicer.util.getNode(mlogic.AddNewFiducialNode("recon")) # Save the volume as has been modified self.tmpVolumeFile = parentPath + "/Tmp/tmp.nii.gz" self.saveNode(volume, self.tmpVolumeFile) # Set the parameters of the progess bar and show it self.pb.setRange(0, len(elList)) self.pb.show() self.pb.setValue(0) slicer.app.processEvents() # For each electrode "e": for i in xrange(len(elList)): tFlag = "-l" if (elList[i].tailCheckBox.isChecked() == True) else "-t" hFlag = "-h" if (elList[i].headCheckBox.isChecked() == True) else "-e" # Construct the cmdLine to run the segmentation on "e" cmdLine = [str(deetoExe), '-s', str(threshold), '-ct', str(self.tmpVolumeFile), \ hFlag, str(-1 * elList[i].entry[0]), str(-1 * elList[i].entry[1]), \ str(elList[i].entry[2]), tFlag, \ str(-1 * elList[i].target[0]), str(-1 * elList[i].target[1]), \ str(elList[i].target[2]), '-m'] + \ map(str, models[elList[i].model.currentText][:-1]) print cmdLine # RUN the command line cmdLine. # [NOTE] : I have used Popen since subprocess.check_output wont work at the moment # It Looks a problem of returning code from deetoS points = subprocess.Popen( cmdLine, stdout=subprocess.PIPE).communicate()[0].splitlines() # print points ### For each of the point returned by deeto we add it to the new markup fiducial name = elList[i].name.text for p in range(0, (len(points) - 1), 3): a = fidNode.AddFiducial(float(points[p]), float(points[p + 1]), float(points[p + 2])) fidNode.SetNthFiducialLabel(a, name + str((p / 3) + 1)) ### For each electrode we create a line from the start point to the last + 3mm ### Look for two points p1 and p3 starting from p1 and p2 (first and last point segmented last = len(points) - 1 p1 = [float(points[0]), float(points[1]), float(points[2])] p2 = [ float(points[last - 2]), float(points[last - 1]), float(points[last]) ] delta = math.sqrt( math.pow((p1[0] - p2[0]), 2) + math.pow((p1[1] - p2[1]), 2) + math.pow((p1[2] - p2[2]), 2)) p3 = [0.0, 0.0, 0.0] p3[0] = p2[0] + (p2[0] - p1[0]) / delta * 3 # distance 3mm p3[1] = p2[1] + (p2[1] - p1[1]) / delta * 3 # distance 3mm p3[2] = p2[2] + (p2[2] - p1[2]) / delta * 3 # distance 3mm if createVTK.checked: ### Create a vtk line lineSource = vtk.vtkLineSource() lineSource.SetPoint1(p1) lineSource.SetPoint2(p3) lineSource.SetResolution(100) ## why? lineSource.Update() ### Create a model of the line to add to the scene model = slicer.vtkMRMLModelNode() model.SetName(name + "_direction") model.SetAndObservePolyData(lineSource.GetOutput()) modelDisplay = slicer.vtkMRMLModelDisplayNode() modelDisplay.SetSliceIntersectionVisibility( True) # Hide in slice view modelDisplay.SetVisibility(True) # Show in 3D view modelDisplay.SetColor(1, 0, 0) modelDisplay.SetLineWidth(2) slicer.mrmlScene.AddNode(modelDisplay) model.SetAndObserveDisplayNodeID(modelDisplay.GetID()) slicer.mrmlScene.AddNode(model) # Lock all markup mlogic.SetAllMarkupsLocked(fidNode, True) # update progress bar self.pb.setValue(i + 1) slicer.app.processEvents() self.pb.hide()