def updateSphere(self, position, radius): if self.sphereModel == None: # Create new model print "Creating new sphere model..." self.sphereModel = slicer.mrmlScene.CreateNodeByClass('vtkMRMLModelNode') self.sphereModel.SetName("RobotPlacementSimulatorModel") slicer.mrmlScene.AddNode(self.sphereModel) displayNode = slicer.mrmlScene.CreateNodeByClass('vtkMRMLModelDisplayNode') slicer.mrmlScene.AddNode(displayNode) displayNode.SetOpacity(0.35) displayNode.SetColor(1.0, 0.0, 0.0) self.sphereModel.SetAndObserveDisplayNodeID(displayNode.GetID()) print "New model created" # Update model spherePolyData = vtk.vtkSphereSource() spherePolyData.SetCenter(position) spherePolyData.SetThetaResolution(20) spherePolyData.SetPhiResolution(20) spherePolyData.SetRadius(radius) spherePolyData.Update() self.sphereModel.SetAndObservePolyData(spherePolyData.GetOutput()) self.sphereModel.Modified()
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 createNeedleModelNode(self, name): locatorModel = self.scene.CreateNodeByClass('vtkMRMLModelNode') # Cylinder represents the locator stick cylinder = vtk.vtkCylinderSource() cylinder.SetRadius(1.5) cylinder.SetHeight(100) cylinder.SetCenter(0, 0, 0) cylinder.Update() # Rotate cylinder tfilter = vtk.vtkTransformPolyDataFilter() trans = vtk.vtkTransform() trans.RotateX(90.0) trans.Translate(0.0, -50.0, 0.0) trans.Update() if vtk.VTK_MAJOR_VERSION <= 5: tfilter.SetInput(cylinder.GetOutput()) else: tfilter.SetInputConnection(cylinder.GetOutputPort()) tfilter.SetTransform(trans) tfilter.Update() # Sphere represents the locator tip sphere = vtk.vtkSphereSource() sphere.SetRadius(3.0) sphere.SetCenter(0, 0, 0) sphere.Update() apd = vtk.vtkAppendPolyData() if vtk.VTK_MAJOR_VERSION <= 5: apd.AddInput(sphere.GetOutput()) apd.AddInput(tfilter.GetOutput()) else: apd.AddInputConnection(sphere.GetOutputPort()) apd.AddInputConnection(tfilter.GetOutputPort()) apd.Update() locatorModel.SetAndObservePolyData(apd.GetOutput()); self.scene.AddNode(locatorModel) locatorModel.SetScene(self.scene); locatorModel.SetName(name) locatorDisp = locatorModel.GetDisplayNodeID() if locatorDisp == None: locatorDisp = self.scene.CreateNodeByClass('vtkMRMLModelDisplayNode') self.scene.AddNode(locatorDisp) locatorDisp.SetScene(self.scene) locatorModel.SetAndObserveDisplayNodeID(locatorDisp.GetID()); color = [0, 0, 0] color[0] = 0.5 color[1] = 0.5 color[2] = 1.0 locatorDisp.SetColor(color) return locatorModel.GetID()
def test_array(self): # Test if convenience function of getting numpy array from various nodes works self.delayDisplay('Test array with scalar image') import SampleData sampleDataLogic = SampleData.SampleDataLogic() volumeNode = sampleDataLogic.downloadMRHead() voxelPos = [120,135,89] voxelValueVtk = volumeNode.GetImageData().GetScalarComponentAsDouble(voxelPos[0], voxelPos[1], voxelPos[2], 0) narray = slicer.util.arrayFromVolume(volumeNode) voxelValueNumpy = narray[voxelPos[2], voxelPos[1], voxelPos[0]] self.assertEqual(voxelValueVtk, voxelValueNumpy) self.delayDisplay('Test array with tensor image') import SampleData sampleDataLogic = SampleData.SampleDataLogic() tensorVolumeNode = sampleDataLogic.downloadDTIBrain() narray = slicer.util.array(tensorVolumeNode.GetName()) self.assertEqual(narray.shape, (85, 144, 144, 3, 3)) self.delayDisplay('Test array with model points') sphere = vtk.vtkSphereSource() modelNode = slicer.mrmlScene.AddNewNodeByClass('vtkMRMLModelNode') modelNode.SetPolyDataConnection(sphere.GetOutputPort()) narray = slicer.util.array(modelNode.GetName()) self.assertEqual(narray.shape, (50, 3)) self.delayDisplay('Testing slicer.util.test_array passed')
def updateSphere(self, position, radius): if self.sphereModel == None: # Create new model print "Creating new sphere model..." self.sphereModel = slicer.mrmlScene.CreateNodeByClass( 'vtkMRMLModelNode') self.sphereModel.SetName("RobotPlacementSimulatorModel") slicer.mrmlScene.AddNode(self.sphereModel) displayNode = slicer.mrmlScene.CreateNodeByClass( 'vtkMRMLModelDisplayNode') slicer.mrmlScene.AddNode(displayNode) displayNode.SetOpacity(0.35) displayNode.SetColor(1.0, 0.0, 0.0) self.sphereModel.SetAndObserveDisplayNodeID(displayNode.GetID()) print "New model created" # Update model spherePolyData = vtk.vtkSphereSource() spherePolyData.SetCenter(position) spherePolyData.SetThetaResolution(20) spherePolyData.SetPhiResolution(20) spherePolyData.SetRadius(radius) spherePolyData.Update() self.sphereModel.SetAndObservePolyData(spherePolyData.GetOutput()) self.sphereModel.Modified()
def test_array(self): # Test if convenience function of getting numpy array from various nodes works self.delayDisplay('Test array with scalar image') import SampleData sampleDataLogic = SampleData.SampleDataLogic() volumeNode = sampleDataLogic.downloadMRHead() voxelPos = [120, 135, 89] voxelValueVtk = volumeNode.GetImageData().GetScalarComponentAsDouble( voxelPos[0], voxelPos[1], voxelPos[2], 0) narray = slicer.util.arrayFromVolume(volumeNode) voxelValueNumpy = narray[voxelPos[2], voxelPos[1], voxelPos[0]] self.assertEqual(voxelValueVtk, voxelValueNumpy) self.delayDisplay('Test array with tensor image') import SampleData sampleDataLogic = SampleData.SampleDataLogic() tensorVolumeNode = sampleDataLogic.downloadDTIBrain() narray = slicer.util.array(tensorVolumeNode.GetName()) self.assertEqual(narray.shape, (85, 144, 144, 3, 3)) self.delayDisplay('Test array with model points') sphere = vtk.vtkSphereSource() modelNode = slicer.mrmlScene.AddNewNodeByClass('vtkMRMLModelNode') modelNode.SetPolyDataConnection(sphere.GetOutputPort()) narray = slicer.util.array(modelNode.GetName()) self.assertEqual(narray.shape, (50, 3)) self.delayDisplay('Testing slicer.util.test_array passed')
def updateTipModelNode(self, tipModelNode, poly, p0, pe, radius, color, opacity): points = vtk.vtkPoints() cellArray = vtk.vtkCellArray() points.SetNumberOfPoints(2) cellArray.InsertNextCell(2) points.SetPoint(0, p0) cellArray.InsertCellPoint(0) points.SetPoint(1, pe) cellArray.InsertCellPoint(1) poly.Initialize() poly.SetPoints(points) poly.SetLines(cellArray) tubeFilter = vtk.vtkTubeFilter() tubeFilter.SetInputData(poly) tubeFilter.SetRadius(radius) tubeFilter.SetNumberOfSides(20) tubeFilter.CappingOn() tubeFilter.Update() # Sphere represents the locator tip sphere = vtk.vtkSphereSource() sphere.SetRadius(radius * 2.0) sphere.SetCenter(pe) sphere.Update() apd = vtk.vtkAppendPolyData() if vtk.VTK_MAJOR_VERSION <= 5: apd.AddInput(sphere.GetOutput()) apd.AddInput(tubeFilter.GetOutput()) else: apd.AddInputConnection(sphere.GetOutputPort()) apd.AddInputConnection(tubeFilter.GetOutputPort()) apd.Update() tipModelNode.SetAndObservePolyData(apd.GetOutput()) tipModelNode.Modified() tipDispID = tipModelNode.GetDisplayNodeID() if tipDispID == None: tipDispNode = self.scene.AddNewNodeByClass( 'vtkMRMLModelDisplayNode') tipDispNode.SetScene(self.scene) tipModelNode.SetAndObserveDisplayNodeID(tipDispNode.GetID()) tipDispID = tipModelNode.GetDisplayNodeID() tipDispNode = self.scene.GetNodeByID(tipDispID) prevState = tipDispNode.StartModify() tipDispNode.SetColor(color) tipDispNode.SetOpacity(opacity) tipDispNode.SliceIntersectionVisibilityOn() tipDispNode.SetSliceDisplayModeToIntersection() tipDispNode.EndModify(prevState)
def __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 onDeleteAllFiducialsClicked(self): self.tumorMarkups_Needle.RemoveAllMarkups() self.deleteLastFiducialButton.setEnabled(False) self.deleteAllFiducialsButton.setEnabled(False) self.deleteLastFiducialDuringNavigationButton.setEnabled(False) sphereSource = vtk.vtkSphereSource() sphereSource.SetRadius(0.001) self.tumorModel_Needle.SetPolyDataConnection(sphereSource.GetOutputPort()) self.tumorModel_Needle.Modified()
def onDeleteAllFiducialsClicked(self): self.tumorMarkups_Needle.RemoveAllMarkups() self.deleteLastFiducialButton.setEnabled(False) self.deleteAllFiducialsButton.setEnabled(False) self.deleteLastFiducialDuringNavigationButton.setEnabled(False) sphereSource = vtk.vtkSphereSource() sphereSource.SetRadius(0.001) self.tumorModel_Needle.SetPolyDataConnection( sphereSource.GetOutputPort()) self.tumorModel_Needle.Modified()
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 updateSphere(self,radius): sphereCenter = [0.0, 0.0, 0.0] if self.sphereSeedListSelector.currentNode(): self.sphereSeedListSelector.currentNode().GetNthFiducialPosition(0,sphereCenter) sphere = vtk.vtkSphereSource() sphere.SetCenter(sphereCenter) sphere.SetThetaResolution(20) sphere.SetPhiResolution(20) sphere.SetRadius(radius) sphere.Update() self.sphereModel.SetAndObservePolyData(sphere.GetOutput()) self.sphereModel.Modified()
def updateSphere(self, radius): sphereCenter = [0.0, 0.0, 0.0] if self.sphereSeedListSelector.currentNode(): self.sphereSeedListSelector.currentNode().GetNthFiducialPosition( 0, sphereCenter) sphere = vtk.vtkSphereSource() sphere.SetCenter(sphereCenter) sphere.SetThetaResolution(20) sphere.SetPhiResolution(20) sphere.SetRadius(radius) sphere.Update() self.sphereModel.SetAndObservePolyData(sphere.GetOutput()) self.sphereModel.Modified()
def DisplayPoints(self, polyDataLine,name): """ Will display all of the points of a given Polydata Line """ sphere= vtk.vtkSphereSource() sphere.SetRadius(0.3) sphere.Update() glyphFilter=vtk.vtkGlyph3D() glyphFilter.ScalingOff() glyphFilter.SetSourceData(sphere.GetOutput()) #object at eachPoint glyphFilter.SetInputData(polyDataLine) glyphFilter.Update() node=self.DisplayPolyData(name, glyphFilter.GetOutput()) node.SetColor(0.3,0.4,1) #Max 1 for each column node.SetAmbient(1) return node
def DisplayPoints(self, polyDataLine, name): """ Will display all of the points of a given Polydata Line """ sphere = vtk.vtkSphereSource() sphere.SetRadius(0.3) sphere.Update() glyphFilter = vtk.vtkGlyph3D() glyphFilter.ScalingOff() glyphFilter.SetSourceData(sphere.GetOutput()) #object at eachPoint glyphFilter.SetInputData(polyDataLine) glyphFilter.Update() node = self.DisplayPolyData(name, glyphFilter.GetOutput()) node.SetColor(0.3, 0.4, 1) #Max 1 for each column node.SetAmbient(1) return node
def putAtArucoCentre(self, markupList, listToAdd, heatmap_node_list, colour_list): p = slicer.mrmlScene.GetNodesByName(markupList) node = p.GetItemAsObject(0) for i in range(node.GetNumberOfFiducials()): coord = [0, 0, 0] node.GetNthFiducialPosition(i, coord) coord.append(1) # Multiply to put start point relative to aruco marker cube origin point = self.aruco_position_matrix.MultiplyPoint(coord) print 'List: ', markupList print 'Coord Number : ', i print 'Position: ', coord print 'oord wrt marker center in slicer: ', point listToAdd.append(point) # Create Models for Display names = ['center_cyl_{}'.format(i) + markupList, 'intermediate_cyl_{}'.format(i) + markupList, 'outer_cyl_{}'.format(i) + markupList] concentric_cylinders = [] cylinder_model_nodes = [] display_marker_cylinders = [] for j in range(0, 1): if slicer.mrmlScene.GetFirstNodeByName(names[j]) is None: model_node = slicer.mrmlScene.AddNewNodeByClass('vtkMRMLModelNode') model_node.SetName(names[j]) else: model_node = slicer.mrmlScene.GetFirstNodeByName(names[j]) cyl = vtk.vtkSphereSource() cyl.SetRadius(3 * (j + 1)) # cyl.SetHeight(60.0) cyl.Update() model_node.SetAndObservePolyData(cyl.GetOutput()) model_node.CreateDefaultDisplayNodes() model_node.GetDisplayNode().SetSliceIntersectionVisibility(True) model_node.GetDisplayNode().SetSliceDisplayMode(1) model_node.GetDisplayNode().SetColor(colour_list[j][0], colour_list[j][1], colour_list[j][2]) concentric_cylinders.append(cyl) cylinder_model_nodes.append(model_node) if slicer.mrmlScene.GetFirstNodeByName(names[j] + 't_form') is None: t_form_node = slicer.mrmlScene.AddNewNodeByClass('vtkMRMLTransformNode') t_form_node.SetName(names[j] + 't_form') else: t_form_node = slicer.mrmlScene.GetFirstNodeByName(names[j] + 't_form') model_node.SetAndObserveTransformNodeID(t_form_node.GetID()) display_marker_cylinders.append(t_form_node) heatmap_node_list.append(display_marker_cylinders)
def test_arrayFromModelPoints(self): # Test if retrieving point coordinates as a numpy array works self.delayDisplay('Create a model containing a sphere') sphere = vtk.vtkSphereSource() sphere.SetRadius(30.0) sphere.Update() modelNode = slicer.mrmlScene.AddNewNodeByClass('vtkMRMLModelNode') modelNode.SetAndObservePolyData(sphere.GetOutput()) modelNode.CreateDefaultDisplayNodes() a = slicer.util.arrayFromModelPoints(modelNode) self.delayDisplay('Change Y scaling') a[:,2] = a[:,2] * 2.5 modelNode.GetPolyData().Modified() self.delayDisplay('Testing slicer.util.test_arrayFromModelPoints passed')
def test_arrayFromModelPoints(self): # Test if retrieving point coordinates as a numpy array works self.delayDisplay('Create a model containing a sphere') sphere = vtk.vtkSphereSource() sphere.SetRadius(30.0) sphere.Update() modelNode = slicer.mrmlScene.AddNewNodeByClass('vtkMRMLModelNode') modelNode.SetAndObservePolyData(sphere.GetOutput()) modelNode.CreateDefaultDisplayNodes() a = slicer.util.arrayFromModelPoints(modelNode) self.delayDisplay('Change Y scaling') a[:, 2] = a[:, 2] * 2.5 modelNode.GetPolyData().Modified() self.delayDisplay( 'Testing slicer.util.test_arrayFromModelPoints passed')
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 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 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 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 createNeedleModelNode(self, name,index): locatorModel = self.scene.CreateNodeByClass('vtkMRMLModelNode') # Cylinder represents the locator stick cylinder = vtk.vtkCylinderSource() cylinder.SetRadius(1.5) cylinder.SetHeight(100) cylinder.SetCenter(0, 0, 0) cylinder.Update() # Rotate cylinder tfilter = vtk.vtkTransformPolyDataFilter() trans = vtk.vtkTransform() trans.RotateX(90.0) trans.Translate(0.0, -50.0, 0.0) trans.Update() if vtk.VTK_MAJOR_VERSION <= 5: tfilter.SetInput(cylinder.GetOutput()) else: tfilter.SetInputConnection(cylinder.GetOutputPort()) tfilter.SetTransform(trans) tfilter.Update() # Sphere represents the locator tip sphere = vtk.vtkSphereSource() sphere.SetRadius(3.0) sphere.SetCenter(0, 0, 0) sphere.Update() apd = vtk.vtkAppendPolyData() if vtk.VTK_MAJOR_VERSION <= 5: apd.AddInput(sphere.GetOutput()) apd.AddInput(tfilter.GetOutput()) else: apd.AddInputConnection(sphere.GetOutputPort()) apd.AddInputConnection(tfilter.GetOutputPort()) apd.Update() locatorModel.SetAndObservePolyData(apd.GetOutput()); self.scene.AddNode(locatorModel) locatorModel.SetScene(self.scene); needleName = "Needle_%s" % name locatorModel.SetName(needleName) locatorDisp = locatorModel.GetDisplayNodeID() if locatorDisp == None: locatorDisp = self.scene.CreateNodeByClass('vtkMRMLModelDisplayNode') self.scene.AddNode(locatorDisp) locatorDisp.SetScene(self.scene) locatorModel.SetAndObserveDisplayNodeID(locatorDisp.GetID()); color = [0, 0, 0] color[0] = 0.5 color[1] = 0.5 color[2] = 1.0 locatorDisp.SetColor(color) print name if self.colorMap.get(name): locatorDisp.SetColor(self.colorMap.get(name)) color = self.colorMap.get(name) colorName = "background:rgb({},{},{})".format(255*color[0], 255*color[1], 255*color[2]) print colorName self.widget.colorSelectors[index].setStyleSheet(colorName) #qss = qt.QString("background-color: %1").arg(col.name()); return locatorModel.GetID()
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
# This module was tested on 3D Slicer version 4.3.1
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 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 __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 test_ShadedModels1(self): """ Ideally you should have several levels of tests. At the lowest level tests should exercise the functionality of the logic with different inputs (both valid and invalid). At higher levels your tests should emulate the way the user would interact with your code and confirm that it still works the way you intended. One of the most important features of the tests is that it should alert other developers when their changes will have an impact on the behavior of your module. For example, if a developer removes a feature that you depend on, your test should break so they know that the feature is needed. """ self.delayDisplay("Starting the test") import SampleData sampleDataLogic = SampleData.SampleDataLogic() print("Getting MR Head Volume") mrHeadVolume = sampleDataLogic.downloadMRHead() resize = vtk.vtkImageResize() resize.SetInputDataObject(mrHeadVolume.GetImageData()) resize.SetOutputDimensions(256,256,128) resize.Update() tdw = slicer.qMRMLThreeDWidget() tdw.setMRMLScene(slicer.mrmlScene) tdw.setMRMLViewNode(slicer.util.getNode("*ViewNode*")) tdw.show() from vtkSlicerShadedActorModuleLogicPython import * shadedActor=vtkOpenGLShadedActor() tdv = tdw.threeDView() rw = tdv.renderWindow() rens = rw.GetRenderers() ren = rens.GetItemAsObject(0) ren.AddActor(shadedActor) mapper = vtk.vtkPolyDataMapper() shadedActor.SetMapper(mapper) shadedActor.SetVertexShaderSource(""" #version 120 attribute vec3 vertexAttribute; attribute vec2 textureCoordinateAttribute; varying vec4 interpolatedColor; varying vec3 interpolatedTextureCoordinate; void main() { interpolatedColor = vec4(0.5) + vec4(vertexAttribute, 1.); interpolatedTextureCoordinate = vec3(textureCoordinateAttribute, .5); gl_Position = vec4(vertexAttribute, 1.); } """) shadedActor.SetFragmentShaderSource(""" #version 120 varying vec4 interpolatedColor; varying vec3 interpolatedTextureCoordinate; uniform sampler3D volumeSampler; void main() { gl_FragColor = vec4 ( 1.0, 0.0, 0.0, 1.0 ); gl_FragColor = interpolatedColor; vec4 volumeSample = texture3D(volumeSampler, interpolatedTextureCoordinate); volumeSample *= 100; gl_FragColor = mix( volumeSample, interpolatedColor, 0.5); vec4 integratedRay = vec4(0.); for (int i = 0; i < 256; i++) { vec3 samplePoint = vec3(interpolatedTextureCoordinate.st, i/256.); vec4 volumeSample = texture3D(volumeSampler, samplePoint); integratedRay += volumeSample; } gl_FragColor = integratedRay; } """) shadedActor.SetTextureImageData(resize.GetOutputDataObject(0)) #shadedActor.SetTextureImageData(mrHeadVolume.GetImageData()) sphereSource = vtk.vtkSphereSource() mapper.SetInputConnection(sphereSource.GetOutputPort()) actor = vtk.vtkActor() actor.SetScale(20,20,20) actor.SetMapper(mapper) ren.AddActor(actor) rw.Render() wti = vtk.vtkWindowToImageFilter() wti.SetInput(rw) iv = vtk.vtkImageViewer() iv.SetColorLevel(128) iv.SetColorWindow(256) iv.SetInputConnection(wti.GetOutputPort()) iv.Render() extensionManager = vtk.vtkOpenGLExtensionManager() extensionManager.SetRenderWindow(rw) extensionManager.Update() print(extensionManager) print(extensionManager.GetDriverGLVendor()) print(extensionManager.GetDriverGLVersion()) print(extensionManager.GetDriverGLRenderer()) slicer.modules.ShadedModelsWidget.tdw = tdw slicer.modules.ShadedModelsWidget.iv = iv
def createNeedleModelNode(self, name): locatorModel = self.scene.CreateNodeByClass('vtkMRMLModelNode') # Cylinder represents the locator stick cylinder = vtk.vtkCylinderSource() cylinder.SetRadius(1.5) cylinder.SetHeight(100) cylinder.SetCenter(0, 0, 0) cylinder.Update() # Rotate cylinder tfilter = vtk.vtkTransformPolyDataFilter() trans = vtk.vtkTransform() trans.RotateX(90.0) trans.Translate(0.0, -50.0, 0.0) trans.Update() if vtk.VTK_MAJOR_VERSION <= 5: tfilter.SetInput(cylinder.GetOutput()) else: tfilter.SetInputConnection(cylinder.GetOutputPort()) tfilter.SetTransform(trans) tfilter.Update() # Sphere represents the locator tip sphere = vtk.vtkSphereSource() sphere.SetRadius(3.0) sphere.SetCenter(0, 0, 0) sphere.Update() apd = vtk.vtkAppendPolyData() if vtk.VTK_MAJOR_VERSION <= 5: apd.AddInput(sphere.GetOutput()) apd.AddInput(tfilter.GetOutput()) else: apd.AddInputConnection(sphere.GetOutputPort()) apd.AddInputConnection(tfilter.GetOutputPort()) apd.Update() locatorModel.SetAndObservePolyData(apd.GetOutput()) self.scene.AddNode(locatorModel) locatorModel.SetScene(self.scene) locatorModel.SetName(name) locatorDisp = locatorModel.GetDisplayNodeID() if locatorDisp == None: locatorDisp = self.scene.CreateNodeByClass( 'vtkMRMLModelDisplayNode') self.scene.AddNode(locatorDisp) locatorDisp.SetScene(self.scene) locatorModel.SetAndObserveDisplayNodeID(locatorDisp.GetID()) color = [0, 0, 0] color[0] = 0.5 color[1] = 0.5 color[2] = 1.0 locatorDisp.SetColor(color) return locatorModel.GetID()
def __init__(self, entryPointFiducialListNode, targetFiducialListNode, shape, shapeRadius, shapeHeight, shapeVolume, ablationZoneColor): entryPointFid = entryPointFiducialListNode targetFid = targetFiducialListNode scene = slicer.mrmlScene if (shape == 'sphere'): source = vtk.vtkSphereSource() source.SetRadius(shapeRadius) source.Update() elif (shape == 'cylinder'): source = vtk.vtkCylinderSource() source.SetRadius(shapeRadius) source.SetHeight(shapeHeight) source.Update() elif (shape == 'ellipsoid'): source = vtk.vtkSphereSource() source.SetRadius(shapeRadius) source.Update() else: source = vtk.vtkSphereSource() source.SetRadius(shapeRadius) source.Update() # get coordinates from current entry point fiducial currentEntryPointFiducialCoordinatesRAS = [0, 0, 0] entryPointFid.GetFiducialCoordinates(currentEntryPointFiducialCoordinatesRAS) currentTargetFiducialCoordinatesRAS = [0, 0, 0] targetFid.GetFiducialCoordinates(currentTargetFiducialCoordinatesRAS) translationTarget = [currentTargetFiducialCoordinatesRAS[0], currentTargetFiducialCoordinatesRAS[1], currentTargetFiducialCoordinatesRAS[2]] # Generate a random start and end point random.seed(8775070) startPoint = [0 for i in range(3)] startPoint[0] = currentEntryPointFiducialCoordinatesRAS[0] startPoint[1] = currentEntryPointFiducialCoordinatesRAS[1] startPoint[2] = currentEntryPointFiducialCoordinatesRAS[2] endPoint = [0 for i in range(3)] endPoint[0] = currentTargetFiducialCoordinatesRAS[0] endPoint[1] = currentTargetFiducialCoordinatesRAS[1] endPoint[2] = currentTargetFiducialCoordinatesRAS[2] # Compute a basis normalizedX = [0 for i in range(3)] normalizedY = [0 for i in range(3)] normalizedZ = [0 for i in range(3)] # The X axis is a vector from start to end math = vtk.vtkMath() math.Subtract(endPoint, startPoint, normalizedX) # length = math.Norm(normalizedX) math.Normalize(normalizedX) # The Z axis is an arbitrary vector cross X arbitrary = [0 for i in range(3)] arbitrary[0] = random.uniform(-10,10) arbitrary[1] = random.uniform(-10,10) arbitrary[2] = random.uniform(-10,10) math.Cross(normalizedX, arbitrary, normalizedZ) math.Normalize(normalizedZ) # The Y axis is Z cross X math.Cross(normalizedZ, normalizedX, normalizedY) matrix = vtk.vtkMatrix4x4() # Create the direction cosine matrix matrix.Identity() for i in range(3): matrix.SetElement(i, 0, normalizedX[i]) matrix.SetElement(i, 1, normalizedY[i]) matrix.SetElement(i, 2, normalizedZ[i]) matrix.SetElement(i, 3, currentTargetFiducialCoordinatesRAS[i]) # Apply the transforms transform = vtk.vtkTransform() transform.Concatenate(matrix) transform.RotateZ(90) ''' ps = vtk.vtkProgrammableSource() import math numPts = 80 polyLinePoints = vtk.vtkPoints() polyLinePoints.SetNumberOfPoints(numPts) R=1.0 for i in range(0,numPts): x = R*math.cos(i*2*math.pi/numPts) y = R*math.sin(i*2*math.pi/numPts) polyLinePoints.InsertPoint(i, x, y, 0) aPolyLine1 = vtk.vtkPolyLine() aPolyLine1.GetPointIds().SetNumberOfIds(numPts+1) for i in range(0,numPts): aPolyLine1.GetPointIds().SetId(i,i) # add one more cell at the end to close the circle on itself aPolyLine1.GetPointIds().SetId(numPts, 0) aPolyLineGrid = ps.GetOutput() aPolyLineGrid.Allocate(1,1) aPolyLineGrid.InsertNextCell(aPolyLine1.GetCellType(), aPolyLine1.GetPointIds()) aPolyLineGrid.SetPoints(polyLinePoints) ''' ''' #This script generates a helix double. #This is intended as the script of a 'Programmable Source' import math ps = vtk.vtkSphereSource() numPts = 80 # Points along each Helix length = 8 # Length of each Helix rounds = 3 # Number of times around phase_shift = math.pi/1.5 # Phase shift between Helixes #Get a vtk.PolyData object for the output pdo = ps.GetOutput() print "before" print pdo #This will store the points for the Helix newPts = vtk.vtkPoints() for i in range(0, numPts): #Generate Points for first Helix x = i*length/numPts y = math.sin(i*rounds*2*math.pi/numPts) z = math.cos(i*rounds*2*math.pi/numPts) newPts.InsertPoint(i, x,y,z) #Generate Points for second Helix. Add a phase offset to y and z. y = math.sin(i*rounds*2*math.pi/numPts+phase_shift) z = math.cos(i*rounds*2*math.pi/numPts+phase_shift) #Offset Helix 2 pts by 'numPts' to keep separate from Helix 1 Pts newPts.InsertPoint(i+numPts, x,y,z) #Add the points to the vtkPolyData object pdo.SetPoints(newPts) #Make two vtkPolyLine objects to hold curve construction data aPolyLine1 = vtk.vtkPolyLine() aPolyLine2 = vtk.vtkPolyLine() #Indicate the number of points along the line aPolyLine1.GetPointIds().SetNumberOfIds(numPts) aPolyLine2.GetPointIds().SetNumberOfIds(numPts) for i in range(0,numPts): #First Helix - use the first set of points aPolyLine1.GetPointIds().SetId(i, i) #Second Helix - use the second set of points #(Offset the point reference by 'numPts'). aPolyLine2.GetPointIds().SetId(i,i+numPts) #Allocate the number of 'cells' that will be added. #Two 'cells' for the Helix curves, and one 'cell' #for every 3rd point along the Helixes. links = range(0,numPts,3) pdo.Allocate(2+len(links), 1) #Add the poly line 'cell' to the vtkPolyData object. pdo.InsertNextCell(aPolyLine1.GetCellType(), aPolyLine1.GetPointIds()) pdo.InsertNextCell(aPolyLine2.GetCellType(), aPolyLine2.GetPointIds()) for i in links: #Add a line connecting the two Helixes. aLine = vtk.vtkLine() aLine.GetPointIds().SetId(0, i) aLine.GetPointIds().SetId(1, i+numPts) pdo.InsertNextCell(aLine.GetCellType(), aLine.GetPointIds()) print "after" print pdo ''' # Create model node lesionModel = slicer.vtkMRMLModelNode() lesionModel.SetScene(scene) lesionModel.SetName("Ablationzone-%s" % targetFid.GetName()) lesionModel.SetAndObservePolyData(source.GetOutput()) self.lesionModel = lesionModel # Create display node lesionModelDisplay = slicer.vtkMRMLModelDisplayNode() lesionModelDisplay.SetColor(ablationZoneColor) lesionModelDisplay.SetOpacity(0.4) lesionModelDisplay.SliceIntersectionVisibilityOn() lesionModelDisplay.SetScene(scene) scene.AddNode(lesionModelDisplay) lesionModel.SetAndObserveDisplayNodeID(lesionModelDisplay.GetID()) # Add to scene lesionModelDisplay.SetPolyData(source.GetOutput()) self.lesionModelDisplay = lesionModelDisplay self.lesionModel= lesionModel scene.AddNode(lesionModel) # Create ablationZoneTransform node ablationZoneTransform = slicer.vtkMRMLLinearTransformNode() ablationZoneTransform.SetName('AblationZoneTransform-%s' % targetFid.GetName()) scene.AddNode(ablationZoneTransform) ablationZoneTransform.ApplyTransformMatrix(transform.GetMatrix()) lesionModel.SetAndObserveTransformNodeID(ablationZoneTransform.GetID()) self.ablationZoneTransform = ablationZoneTransform
def test_ShadedModels1(self): """ Ideally you should have several levels of tests. At the lowest level tests should exercise the functionality of the logic with different inputs (both valid and invalid). At higher levels your tests should emulate the way the user would interact with your code and confirm that it still works the way you intended. One of the most important features of the tests is that it should alert other developers when their changes will have an impact on the behavior of your module. For example, if a developer removes a feature that you depend on, your test should break so they know that the feature is needed. """ self.delayDisplay("Starting the test") import SampleData sampleDataLogic = SampleData.SampleDataLogic() print("Getting MR Head Volume") mrHeadVolume = sampleDataLogic.downloadMRHead() resize = vtk.vtkImageResize() resize.SetInputDataObject(mrHeadVolume.GetImageData()) resize.SetOutputDimensions(256, 256, 128) resize.Update() tdw = slicer.qMRMLThreeDWidget() tdw.setMRMLScene(slicer.mrmlScene) tdw.setMRMLViewNode(slicer.util.getNode("*ViewNode*")) tdw.show() from vtkSlicerShadedActorModuleLogicPython import * shadedActor = vtkOpenGLShadedActor() tdv = tdw.threeDView() rw = tdv.renderWindow() rens = rw.GetRenderers() ren = rens.GetItemAsObject(0) ren.AddActor(shadedActor) mapper = vtk.vtkPolyDataMapper() shadedActor.SetMapper(mapper) shadedActor.SetVertexShaderSource(""" #version 120 attribute vec3 vertexAttribute; attribute vec2 textureCoordinateAttribute; varying vec4 interpolatedColor; varying vec3 interpolatedTextureCoordinate; void main() { interpolatedColor = vec4(0.5) + vec4(vertexAttribute, 1.); interpolatedTextureCoordinate = vec3(textureCoordinateAttribute, .5); gl_Position = vec4(vertexAttribute, 1.); } """) shadedActor.SetFragmentShaderSource(""" #version 120 varying vec4 interpolatedColor; varying vec3 interpolatedTextureCoordinate; uniform sampler3D volumeSampler; void main() { gl_FragColor = vec4 ( 1.0, 0.0, 0.0, 1.0 ); gl_FragColor = interpolatedColor; vec4 volumeSample = texture3D(volumeSampler, interpolatedTextureCoordinate); volumeSample *= 100; gl_FragColor = mix( volumeSample, interpolatedColor, 0.5); vec4 integratedRay = vec4(0.); for (int i = 0; i < 256; i++) { vec3 samplePoint = vec3(interpolatedTextureCoordinate.st, i/256.); vec4 volumeSample = texture3D(volumeSampler, samplePoint); integratedRay += volumeSample; } gl_FragColor = integratedRay; } """) shadedActor.SetTextureImageData(resize.GetOutputDataObject(0)) #shadedActor.SetTextureImageData(mrHeadVolume.GetImageData()) sphereSource = vtk.vtkSphereSource() mapper.SetInputConnection(sphereSource.GetOutputPort()) actor = vtk.vtkActor() actor.SetScale(20, 20, 20) actor.SetMapper(mapper) ren.AddActor(actor) rw.Render() wti = vtk.vtkWindowToImageFilter() wti.SetInput(rw) iv = vtk.vtkImageViewer() iv.SetColorLevel(128) iv.SetColorWindow(256) iv.SetInputConnection(wti.GetOutputPort()) iv.Render() extensionManager = vtk.vtkOpenGLExtensionManager() extensionManager.SetRenderWindow(rw) extensionManager.Update() print(extensionManager) print(extensionManager.GetDriverGLVendor()) print(extensionManager.GetDriverGLVersion()) print(extensionManager.GetDriverGLRenderer()) slicer.modules.ShadedModelsWidget.tdw = tdw slicer.modules.ShadedModelsWidget.iv = iv