示例#1
0
    def onCircularROIBtn(self):
        self.markups = slicer.util.getNode("F")
        self.sphere = vtk.vtkSphereSource()

        self.UpdateSphere(0, 0)

        scene = slicer.mrmlScene

        # Create model node
        model = slicer.vtkMRMLModelNode()
        model.SetAndObservePolyData(self.sphere.GetOutput())
        # self.modelDisplay.SetColor(1, 1, 0)  # yellows
        # self.modelDisplay.SetBackfaceCulling(0)

        # Create display node
        self.modelDisplay = slicer.vtkMRMLModelDisplayNode()
        self.modelDisplay.SetSliceIntersectionVisibility(True)
        self.modelDisplay.SetVisibility(True)
        scene.AddNode(self.modelDisplay)
        model.SetAndObserveDisplayNodeID(self.modelDisplay.GetID())

        # Add to scene
        self.modelDisplay.SetInputPolyDataConnection(model.GetPolyDataConnection())
        scene.AddNode(model)

        self.markups.AddObserver("ModifiedEvent", self.UpdateSphere, 2)
示例#2
0
  def merge_models(self, modelA, modelB, modelC):

    scene = slicer.mrmlScene

    # Create model node
    mergedModel = slicer.vtkMRMLModelNode()
    mergedModel.SetScene(scene)
    mergedModel.SetName(modelName)
    dnode = slicer.vtkMRMLModelDisplayNode()
    snode = slicer.vtkMRMLModelStorageNode()
    mergedModel.SetAndObserveDisplayNodeID(dnode.GetID())
    mergedModel.SetAndObserveStorageNodeID(snode.GetID())
    scene.AddNode(dnode)
    scene.AddNode(snode)
    scene.AddNode(mergedModel)

    # Get transformed poly data from input models
    modelA_polydata = self.getTransformedPolyDataFromModel(self.modelA)
    modelB_polydata = self.getTransformedPolyDataFromModel(self.modelB)
    modelC_polydata = self.getTransformedPolyDataFromModel(self.modelC)
    
    # Append poly data
    appendFilter = vtk.vtkAppendPolyData()
    appendFilter.AddInputData(modelA_polydata)
    appendFilter.AddInputData(modelB_polydata)
    appendFilter.AddInputData(modelC_polydata)
    appendFilter.Update();

    # Output
    mergedModel.SetAndObservePolyData(appendFilter.GetOutput());
    mergedModel.SetAndObserveDisplayNodeID(dnode.GetID());

    return mergedModel
  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
示例#4
0
 def copyAndHardenModel(self,originalModel):
   # copy model
   outputModel = slicer.vtkMRMLModelNode()
   fullPolyData = originalModel.GetPolyData()
   outputModel.SetAndObservePolyData(fullPolyData)
   md2 = slicer.vtkMRMLModelDisplayNode()
   slicer.mrmlScene.AddNode(outputModel)
   slicer.mrmlScene.AddNode(md2)
   outputModel.SetAndObserveDisplayNodeID(md2.GetID())
   md2.SetVisibility(0)
   # apply transforms tree to copied model
   parent_transform = originalModel.GetParentTransformNode()
   try:
       t = slicer.util.getNode('DefinedTransform')
       identityTransform = vtk.vtkMatrix4x4()
       t.SetMatrixTransformToParent(identityTransform)
   except:
       t=slicer.vtkMRMLLinearTransformNode()
       t.SetName('DefinedTransform')
       slicer.mrmlScene.AddNode(t)
   t.SetAndObserveTransformNodeID(parent_transform.GetID())
   t.HardenTransform()
   outputModel.SetAndObserveTransformNodeID(t.GetID())
   outputModel.HardenTransform()
   return outputModel,t
示例#5
0
    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())
        lineModelDisplay.SetInputPolyDataConnection(line.GetOutputPort())
        scene.AddNode(lineModel)
        return line
示例#6
0
    def arrowModel(self, scene, point1, point2, name, color):
        """ Create a line to reflect the puncture path"""
        #Line mode source

        arrow = vtk.vtkLineSource()
        #arrow.SetShaftRadius(0.01)
        #arrow.SetTipLength(.9)
        arrow.SetPoint1(point1)  #(point1[0][0], point1[0][1], point1[0][2])
        arrow.SetPoint2(point2)  #(point2[0][0], point2[0][1], point2[0][2])

        tubes = vtk.vtkTubeFilter()
        tubes.SetInputConnection(arrow.GetOutputPort())
        tubes.SetRadius(0.8)
        tubes.SetNumberOfSides(6)

        # Create model node

        arrowModel = slicer.vtkMRMLModelNode()
        arrowModel.SetScene(scene)
        arrowModel.SetName(name)
        arrowModel.SetAndObservePolyData(tubes.GetOutput())

        # Create display node

        arrowModelDisplay = slicer.vtkMRMLModelDisplayNode()
        arrowModelDisplay.SetColor(color)
        arrowModelDisplay.SetScene(scene)
        scene.AddNode(arrowModelDisplay)
        arrowModel.SetAndObserveDisplayNodeID(arrowModelDisplay.GetID())
        arrowModelDisplay.SetInputPolyDataConnection(tubes.GetOutputPort())
        scene.AddNode(arrowModel)
        return arrow
示例#7
0
    def createSampleModelNode(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: https://mantisarchive.slicer.org/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)
        modelNode.SetPolyDataConnection(sphere.GetOutputPort())
        modelNode.SetHideFromEditors(0)

        displayNode = slicer.vtkMRMLModelDisplayNode()
        slicer.mrmlScene.AddNode(displayNode)
        displayNode.Visibility2DOn()
        displayNode.VisibilityOn()
        displayNode.SetColor(color[0], color[1], color[2])
        modelNode.SetAndObserveDisplayNodeID(displayNode.GetID())

        return modelNode
示例#8
0
    def onApplyButtonClicked(self):
        """
        Real algorithm should be in class VascularWallLogic.
        """
        logging.info("applyButton is clicked.")

        # Create models for sphere

        self.sphere = vtk.vtkSphereSource()
        # Model node
        model = slicer.vtkMRMLModelNode()
        model.SetAndObservePolyData(self.sphere.GetOutput())

        # Display node
        self.modelDisplay = slicer.vtkMRMLModelDisplayNode()
        self.modelDisplay.SetSliceIntersectionVisibility(True)
        self.modelDisplay.SetVisibility(self.showCheckBox.isChecked())
        self.modelDisplay.SetOpacity(0.5)
        self.modelDisplay.SetRepresentation(1)
        slicer.mrmlScene.AddNode(self.modelDisplay)
        model.SetAndObserveDisplayNodeID(self.modelDisplay.GetID())

        # Add to scene
        self.modelDisplay.SetInputPolyDataConnection(
            model.GetPolyDataConnection())
        slicer.mrmlScene.AddNode(model)

        # Callback
        self.UpdateSphere(0, 0)
        self.rulerSelector.currentNode().AddObserver(
            'ModifiedEvent', self.UpdateSphere)
示例#9
0
    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())
        planeContour.SetInputData(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())
        planeModelDisplay.SetInputPolyDataConnection(
            planeContour.GetOutputPort())

        scene.AddNode(planeNode)

        return plane
示例#10
0
 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())
示例#11
0
 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())
示例#12
0
    def showColorMap(self):

        # Get PolyData from Segment 1
        self.segment1.CreateClosedSurfaceRepresentation()
        ss1 = self.segment1.GetSegmentation()
        str1 = ss1.GetNthSegmentID(0)
        pl1 = vtk.vtkPolyData()
        pl1 = self.segment1.GetClosedSurfaceRepresentation(str1)

        # Get PolyData from Segment 2
        self.segment2.CreateClosedSurfaceRepresentation()
        ss2 = self.segment2.GetSegmentation()
        str2 = ss2.GetNthSegmentID(0)
        pl2 = vtk.vtkPolyData()
        pl2 = self.segment2.GetClosedSurfaceRepresentation(str2)

        # Compute distance
        distanceFilter = vtk.vtkDistancePolyDataFilter()
        distanceFilter.SetInputData(0, pl1)
        distanceFilter.SetInputData(1, pl2)
        distanceFilter.SignedDistanceOff()
        distanceFilter.Update()

        # Center 3D view
        #slicer.app.layoutManager().tableWidget(0).setVisible(False)
        layoutManager = slicer.app.layoutManager()
        threeDWidget = layoutManager.threeDWidget(0)
        threeDView = threeDWidget.threeDView()
        threeDView.resetFocalPoint()

        # Output model
        model = slicer.vtkMRMLModelNode()
        slicer.mrmlScene.AddNode(model)
        model.SetName('DistanceModelNode')
        model.SetAndObservePolyData(distanceFilter.GetOutput())
        self.distanceColorMap_display = slicer.vtkMRMLModelDisplayNode()
        slicer.mrmlScene.AddNode(self.distanceColorMap_display)
        model.SetAndObserveDisplayNodeID(self.distanceColorMap_display.GetID())
        self.distanceColorMap_display.SetActiveScalarName('Distance')
        self.distanceColorMap_display.SetAndObserveColorNodeID(
            'vtkMRMLColorTableNodeFileDivergingBlueRed.txt')
        self.distanceColorMap_display.SetScalarVisibility(True)
        self.distanceColorMap_display.SetScalarRangeFlag(
            0)  # Set scalar range mode to Manual
        self.distanceColorMap_display.SetScalarRange(0.0, 10.0)

        [rmin, rmax] = self.distanceColorMap_display.GetScalarRange()
        print(rmin)
        print(rmax)

        # Scalar bar
        self.updateScalarBarRange(0.0, 10.0)
        self.updateScalarBarVisibility(True)

        # Deactivate visibility of segments (deberia actualizarse el checkbox del GUI pero no lo consigo)
        self.updateSegment1Visibility(False)
        self.updateSegment2Visibility(False)
示例#13
0
    def onApplyButton(self):
        print("Transducer parameters >> /n")
        print("ROC:" + str(self.ROC.value))
        print("Width:" + str(self.width.value))
        print("ROC:" + str(self.freq.value))

        skull, skull_actor = hlp.read_skull_vtk(
            "/Users/home/Desktop/Simulation/Simulation/SMA_matlab_skull_transform0.vtk",
            0.5, [0.8, 0.8, 0.8])

        model = slicer.vtkMRMLModelNode()
        model.SetAndObservePolyData(skull)

        ## set model node properties
        modelDisplay = slicer.vtkMRMLModelDisplayNode()
        modelDisplay.SetColor(0.8, 0.8, 0.8)
        modelDisplay.BackfaceCullingOff()
        modelDisplay.SetOpacity(0.5)
        modelDisplay.SetPointSize(3)

        ## mode node display
        modelDisplay.SetSliceIntersectionVisibility(True)
        modelDisplay.SetVisibility(True)
        slicer.mrmlScene.AddNode(modelDisplay)
        model.SetAndObserveDisplayNodeID(modelDisplay.GetID())
        modelDisplay.SetInputPolyDataConnection(model.GetPolyDataConnection())

        ## model node set name
        slicer.mrmlScene.AddNode(model).SetName("Skull")

        ## read vtk object convert to vtkimage
        result_image = hlp.vtk_grid2image(
            "/Users/home/Desktop/Simulation/Simulation/SMA_full_0.vtk")
        result_volume = slicer.vtkMRMLScalarVolumeNode()
        result_volume.SetAndObserveImageData(result_image)

        ## image to 2D scene
        defaultVolumeDisplayNode = slicer.mrmlScene.CreateNodeByClass(
            "vtkMRMLScalarVolumeDisplayNode")
        defaultVolumeDisplayNode.AutoWindowLevelOn()
        defaultVolumeDisplayNode.SetVisibility(True)
        defaultVolumeDisplayNode.AddWindowLevelPresetFromString(
            "ColdToHotRainbow")
        slicer.mrmlScene.AddDefaultNode(defaultVolumeDisplayNode)
        result_volume.SetAndObserveDisplayNodeID(
            defaultVolumeDisplayNode.GetID())
        defaultVolumeDisplayNode.SetInputImageDataConnection(
            result_volume.GetImageDataConnection())

        ## volume node set name
        slicer.mrmlScene.AddNode(result_volume).SetName("simulation_result")

        ## volume rendering
        hlp.showVolumeRendering(result_volume)
        slicer.mrmlScene.AddObserver(slicer.vtkMRMLScene.NodeAddedEvent,
                                     hlp.onNodeAdded)
 def defineSphere(self):
     sphereSource = vtk.vtkSphereSource()
     sphereSource.SetRadius(100.0)
     model = slicer.vtkMRMLModelNode()
     model.SetAndObservePolyData(sphereSource.GetOutput())
     modelDisplay = slicer.vtkMRMLModelDisplayNode()
     slicer.mrmlScene.AddNode(modelDisplay)
     model.SetAndObserveDisplayNodeID(modelDisplay.GetID())
     modelDisplay.SetInputPolyDataConnection(sphereSource.GetOutputPort())
     return model
示例#15
0
 def createAndConfigureClippingModelDisplayNode(self):
   self.clippingModelDisplayNode = slicer.vtkMRMLModelDisplayNode()
   self.clippingModelDisplayNode.SetSliceIntersectionThickness(3)
   self.clippingModelDisplayNode.SetColor(self.labelValueToRGB(self.outputLabelValue) if self.outputLabelValue
                                          else [0.200, 0.800, 0.000])
   self.clippingModelDisplayNode.BackfaceCullingOff()
   self.clippingModelDisplayNode.SliceIntersectionVisibilityOn()
   self.clippingModelDisplayNode.SetOpacity(0.3)
   slicer.mrmlScene.AddNode(self.clippingModelDisplayNode)
   self.clippingModelNode.SetAndObserveDisplayNodeID(self.clippingModelDisplayNode.GetID())
示例#16
0
  def drawCone(self, coneSource, coneDimensions, center):
    coneModelNode = slicer.vtkMRMLModelNode()
    slicer.mrmlScene.AddNode(coneModelNode)
    coneModelNode.SetName('ConeModel')
    coneModelNodeToUpdate = coneModelNode
    coneSource.Update()
    coneModelNodeToUpdate.SetAndObservePolyData(coneSource.GetOutput())

    if coneModelNodeToUpdate.GetDisplayNode() is None:
      displayNode = slicer.vtkMRMLModelDisplayNode()
      slicer.mrmlScene.AddNode(displayNode)
      displayNode.SetName('ConeModelDisplay')
      coneModelNodeToUpdate.SetAndObserveDisplayNodeID(displayNode.GetID())

    return coneModelNode
示例#17
0
 def __init__(self):
   self.sendDataOK = False
   self.OSC_active = False
   self.line = slicer.util.getNode('Line')
   if not self.line:
     self.line = slicer.vtkMRMLModelNode()
     self.line.SetName('Line')
     linePolyData = vtk.vtkPolyData()
     self.line.SetAndObservePolyData(linePolyData)      
     modelDisplay = slicer.vtkMRMLModelDisplayNode()
     modelDisplay.SetSliceIntersectionVisibility(True)
     modelDisplay.SetColor(0,1,0)
     slicer.mrmlScene.AddNode(modelDisplay)      
     self.line.SetAndObserveDisplayNodeID(modelDisplay.GetID())      
     slicer.mrmlScene.AddNode(self.line)
示例#18
0
  def createAndConfigureSegmentModelDisplayNode(self):
    self.segmentModelNode = slicer.vtkMRMLModelNode()
    prefix = "{}-".format(self.seriesNumber) if self.seriesNumber else ""
    self.segmentModelNode.SetName('%sSurfaceCut-MODEL' % prefix)
    slicer.mrmlScene.AddNode(self.segmentModelNode)

    self.segmentModelDisplayNode = slicer.vtkMRMLModelDisplayNode()
    self.segmentModelDisplayNode.SetSliceIntersectionThickness(3)
    # self.refreshViewNodeIDs
    self.segmentModelDisplayNode.SetColor(self.labelValueToRGB(self.outputLabelValue) if self.outputLabelValue
                                           else [0.200, 0.800, 0.000])
    self.segmentModelDisplayNode.BackfaceCullingOff()
    self.segmentModelDisplayNode.SliceIntersectionVisibilityOn()
    self.segmentModelDisplayNode.SetOpacity(0.3)
    slicer.mrmlScene.AddNode(self.segmentModelDisplayNode)
    self.segmentModelNode.SetAndObserveDisplayNodeID(self.segmentModelDisplayNode.GetID())
示例#19
0
  def renderSegmentedData(self, modelNode, outputModelNode, selectedTexture):
	
    fullPolyData = modelNode.GetPolyData()
    pointData=fullPolyData.GetPointData()
	
    data = np.load('C:/Users/Brand/OneDrive/Documents/CISC 472/test segmentation_model/classified_texture.pkl')
    size_of_data = data.shape
    print(size_of_data)
    print(int(data[1][0]))
    print(' ')
    print(selectedTexture)
	
    segmentedPointIds = vtk.vtkIdTypeArray()

    print('begin classifiacation')
    for point in range(size_of_data[1]):
      if int(data[1][point]) == selectedTexture:
        segmentedPointIds.InsertNextValue(int(data[0][point]))
        segmentedPointIds.InsertNextValue(int(data[0][point]))
		
    print('calssification done')
    selectionNode = vtk.vtkSelectionNode()
    selectionNode.SetFieldType(vtk.vtkSelectionNode.POINT)
    selectionNode.SetContentType(vtk.vtkSelectionNode.INDICES)
    selectionNode.SetSelectionList(segmentedPointIds)
    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()) 
	
    print('done?')
    return 0	
示例#20
0
  def drawPlane(self, m, V_norm):
    scene = slicer.mrmlScene

    #create a plane to cut,here it cuts in the XZ direction (xz normal=(1,0,0);XY =(0,0,1),YZ =(0,1,0)
    planex=vtk.vtkPlane()
    planex.SetOrigin(m[0],m[1],m[2])
    planex.SetNormal(V_norm[0],V_norm[1],V_norm[2])

    renderer = slicer.app.layoutManager().threeDWidget(0).threeDView().renderWindow().GetRenderers().GetFirstRenderer()
    viewSize = renderer.ComputeVisiblePropBounds()
    #viewSize = (-50.0, 50.0, -50.0, 50.0, -50.0, 50.0)


    planexSample = vtk.vtkSampleFunction()
    planexSample.SetImplicitFunction(planex)
    planexSample.SetModelBounds(viewSize)
    #planexSample.SetSampleDimensions(200,200,200)
    planexSample.ComputeNormalsOff()
    plane1 = vtk.vtkContourFilter()
    plane1.SetInputConnection(planexSample.GetOutputPort())


    # Create model Plane A node
    planeA = slicer.vtkMRMLModelNode()
    planeA.SetScene(scene)
    planeA.SetName("X-Y Plane")
    planeA.SetAndObservePolyData(plane1.GetOutput())

    # Create display model Plane A node
    planeAModelDisplay = slicer.vtkMRMLModelDisplayNode()
    planeAModelDisplay.SetColor(0.145,0.77,0.596)
    
    planeAModelDisplay.BackfaceCullingOff()
    planeAModelDisplay.SetScene(scene)
    scene.AddNode(planeAModelDisplay)
    planeA.SetAndObserveDisplayNodeID(planeAModelDisplay.GetID())

    #Add to scene
    planeAModelDisplay.SetInputPolyDataConnection(plane1.GetOutputPort())
    scene.AddNode(planeA)

    # adjust center of 3d view to plane
    layoutManager = slicer.app.layoutManager()
    threeDWidget = layoutManager.threeDWidget(0)
    threeDView = threeDWidget.threeDView()
    threeDView.resetFocalPoint()
示例#21
0
  def run(self):
    """
    Run the actual algorithm
    """
    #generating Nodes for displaying a new model
    modelNode = slicer.vtkMRMLModelNode()
    dispNode  = slicer.vtkMRMLModelDisplayNode()
    transform = slicer.vtkMRMLLinearTransformNode()
    
    #Display node characteristics
    dispNode.SetVisibility(True)
    dispNode.SetSliceIntersectionVisibility(True)
    dispNode.SetOpacity(1)
    dispNode.SetColor(1, 1, 0)
    dispNode.SetScene(slicer.mrmlScene)

    #generate sphere data
    sphere = vtk.vtkSphereSource()
    sphere.SetCenter(10,10,10)
    sphere.SetRadius(40)
    sphere.Update()
    
    #adding necessary nodes to the Scene
    slicer.mrmlScene.AddNode(dispNode)
    slicer.mrmlScene.AddNode(transform)
    slicer.mrmlScene.AddNode(modelNode)
    
    #model node name and associations!
    modelNode.SetName("SphereModelNode")
    modelNode.SetScene(slicer.mrmlScene)
    modelNode.SetAndObserveTransformNodeID(transform.GetID())
    modelNode.SetAndObserveDisplayNodeID(dispNode.GetID())

    apd = vtk.vtkAppendPolyData()
    apd.AddInputData(sphere.GetOutput())
    apd.Update()
    
    #adding model node poly data! Here there are  sphere's data!!!    
    modelNode.SetAndObservePolyData(apd.GetOutput())
    #update the scene
    slicer.mrmlScene.Modified()
    

    return True
示例#22
0
  def plotLineZaxis(self):

    # Create a vtkPoints object and store the points in it
    self.pos = [0.0, 0.0, 0.0, 0.0]  
    self.targetFiducial.GetNthFiducialWorldCoordinates(0, self.pos)
    targetP = [self.pos[i] for i in (0,1,2)]

    self.surfPoint = [0.0, 0.0, 0.0, 0.0]  
    self.surfaceFiducial.GetNthFiducialWorldCoordinates(0, self.surfPoint)
    surfaceP = [self.surfPoint[i] for i in (0,1,2)]

    self.zVector = np.subtract(targetP,surfaceP)

    points = vtk.vtkPoints()
    points.InsertNextPoint(targetP)

    points.InsertNextPoint(surfaceP)

    # Create line
    line = vtk.vtkLine()
    line.GetPointIds().SetId(0,0)
    line.GetPointIds().SetId(1,1)
    lineCellArray = vtk.vtkCellArray()
    lineCellArray.InsertNextCell(line)

    self.lineNode = slicer.vtkMRMLModelNode()
    self.lineNode.SetName('LineZ')
    linePolyData = vtk.vtkPolyData()
    self.lineNode.SetAndObservePolyData(linePolyData)
    modelDisplay = slicer.vtkMRMLModelDisplayNode()
    modelDisplay.SetSliceIntersectionVisibility(True)
    modelDisplay.SetColor(1,1,1)
    slicer.mrmlScene.AddNode(modelDisplay)

    self.lineNode.SetAndObserveDisplayNodeID(modelDisplay.GetID())
    slicer.mrmlScene.AddNode(self.lineNode)

    self.lineNode.GetPolyData().SetPoints(points)
    self.lineNode.GetPolyData().SetLines(lineCellArray)

    #self.lineNode.SetAndObserveTransformNodeID(self.boxToReference.GetID())
    self.drawPlane(surfaceP, self.zVector)
    self.definePlaneAxis(surfaceP, self.zVector)
示例#23
0
    def TextureMappedPlane(self, obj, event):

        # use dummy image data here
        e = vtk.vtkImageEllipsoidSource()

        scene = slicer.mrmlScene

        # Create model node
        model = slicer.vtkMRMLModelNode()
        model.SetScene(scene)
        model.SetName(scene.GenerateUniqueName("2DImageModel"))

        planeSource = vtk.vtkPlaneSource()
        model.SetAndObservePolyData(planeSource.GetOutput())

        # 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())

        modelDisplay.SetSliceIntersectionVisibility(True)
        modelDisplay.SetVisibility(True)

        # Add to scene
        modelDisplay.SetTextureImageDataConnection(e.GetOutputPort())
        # modelDisplay.SetInputPolyDataConnection(model.GetPolyDataConnection())
        scene.AddNode(model)

        transform = slicer.vtkMRMLLinearTransformNode()
        scene.AddNode(transform)
        model.SetAndObserveTransformNodeID(transform.GetID())

        vTransform = vtk.vtkTransform()
        vTransform.Scale(50, 50, 50)
        vTransform.RotateX(30)
        # transform.SetAndObserveMatrixTransformToParent(vTransform.GetMatrix())
        transform.SetMatrixTransformToParent(vTransform.GetMatrix())
示例#24
0
 def setupMRMLTracking(self):
     """
     For the tracking endpoint this creates a kind of 'cursor' in the scene.
     Adds "trackingDevice" (model node) to 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())
示例#25
0
    def drawPlane(self, m, V_norm):

        scene = slicer.mrmlScene
        #create a plane to cut,here it cuts in the XZ direction (xz normal=(1,0,0);XY =(0,0,1),YZ =(0,1,0)
        planex = vtk.vtkPlane()
        planex.SetOrigin(m[0], m[1], m[2])
        planex.SetNormal(V_norm[0], V_norm[1], V_norm[2])
        renderer = slicer.app.layoutManager().threeDWidget(
            0).threeDView().renderWindow().GetRenderers().GetFirstRenderer()
        viewSize = renderer.ComputeVisiblePropBounds()
        planexSample = vtk.vtkSampleFunction()
        planexSample.SetImplicitFunction(planex)
        planexSample.SetModelBounds(viewSize)
        planexSample.SetSampleDimensions(50, 50, 50)
        planexSample.ComputeNormalsOff()
        plane1 = vtk.vtkContourFilter()
        plane1.SetInputConnection(planexSample.GetOutputPort())
        # Create model Plane A node
        planeA = slicer.vtkMRMLModelNode()
        planeA.SetScene(scene)
        planeA.SetName("Symmetry Plane")
        planeA.SetAndObservePolyData(plane1.GetOutput())
        # Create display model Plane A node
        planeAModelDisplay = slicer.vtkMRMLModelDisplayNode()
        planeAModelDisplay.SetColor(0, 170, 127)
        planeAModelDisplay.BackfaceCullingOff()
        planeAModelDisplay.SetScene(scene)
        scene.AddNode(planeAModelDisplay)
        planeA.SetAndObserveDisplayNodeID(planeAModelDisplay.GetID())
        #Add to scene
        planeAModelDisplay.SetInputPolyDataConnection(plane1.GetOutputPort())
        scene.AddNode(planeA)
        # adjust center of 3d view to plane
        layoutManager = slicer.app.layoutManager()
        threeDWidget = layoutManager.threeDWidget(0)
        threeDView = threeDWidget.threeDView()
        threeDView.resetFocalPoint()

        return plane1
示例#26
0
    def __init__(self):
        self.coord = []
        self.resNameRegion = []
        self.segmentationNode = slicer.vtkMRMLModelDisplayNode()
        self.index = []
        self.position = []
        self.visu = []

        self.subject_index = 0
        self.min_column = 1
        self.max_column = 79

        self.path_to_json = './Resources/nodeGraph_3D.json'
        self.jep = JEP.json_extract_properties()

        # Initialize an empty filtered VisuHierarchy Map
        self.filteredVisuHierarchy = {}
        self.visuHierarchyMap = []
        self.checked_regions = []
        self.node_color_map = None
        self.connect_color_map = None
        self.user_table = None
        self.vtk_spheres = []
        self.line_actors = []
        self.tube_actors = []
        self.header = False
        self.connection_d = False
        self.connection_matrix = None
        self.node_size = 7
        self.min_size = 1
        self.max_size = 7
        self.min_strength = 0
        self.max_strength = 7
        self.node_min = 0
        self.node_max = 0.6
        self.line_min = 0
        self.line_max = 1
        self.f = 0.000033
        self.C = 10.0
示例#27
0
    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())
        pointModelDisplay.SetInputPolyDataConnection(sphere.GetOutputPort())

        scene.AddNode(pointModel)
示例#28
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
        if vtk.VTK_MAJOR_VERSION <= 5:
            # shall not be needed.
            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()))
        if vtk.VTK_MAJOR_VERSION <= 5:
            cursor.SetAndObservePolyData(sphere.GetOutput())
        else:
            cursor.SetPolyDataConnection(sphere.GetOutputPort())

        # 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
        if vtk.VTK_MAJOR_VERSION <= 5:
            # Shall not be needed.
            cursorModelDisplay.SetInputPolyData(sphere.GetOutput())
        scene.AddNode(cursor)

        # Create transform node
        transform = slicer.vtkMRMLLinearTransformNode()
        transform.SetName(
            scene.GenerateUniqueName("Transform-%s" % fids.GetName()))
        scene.AddNode(transform)
        cursor.SetAndObserveTransformNodeID(transform.GetID())

        self.transform = transform
  def __init__(self):
    self.toolTipToTool = slicer.util.getNode('toolTipToTool')
    self.pointerTipToReference = None
    self.targetCreatedTransformed = False
    self.firstFiducial = True

    if not self.toolTipToTool:
      self.toolTipToTool=slicer.vtkMRMLLinearTransformNode()
      self.toolTipToTool.SetName("toolTipToTool")
      m = vtk.vtkMatrix4x4()
      m.SetElement( 0, 0, 1 ) # Row 1
      m.SetElement( 0, 1, 0 )
      m.SetElement( 0, 2, 0 )
      m.SetElement( 0, 3, 0 )      
      m.SetElement( 1, 0, 0 )  # Row 2
      m.SetElement( 1, 1, 1 )
      m.SetElement( 1, 2, 0 )
      m.SetElement( 1, 3, 0 )       
      m.SetElement( 2, 0, 0 )  # Row 3
      m.SetElement( 2, 1, 0 )
      m.SetElement( 2, 2, 1 )
      m.SetElement( 2, 3, 0 )
      self.toolTipToTool.SetMatrixTransformToParent(m)
      slicer.mrmlScene.AddNode(self.toolTipToTool)

         
    self.line = slicer.util.getNode('Line')
    if not self.line:
      self.line = slicer.vtkMRMLModelNode()
      self.line.SetName('Line')
      linePolyData = vtk.vtkPolyData()
      self.line.SetAndObservePolyData(linePolyData)      
      modelDisplay = slicer.vtkMRMLModelDisplayNode()
      modelDisplay.SetSliceIntersectionVisibility(True)
      modelDisplay.SetColor(0,1,0)
      slicer.mrmlScene.AddNode(modelDisplay)      
      self.line.SetAndObserveDisplayNodeID(modelDisplay.GetID())      
      slicer.mrmlScene.AddNode(self.line)
      
    # VTK objects
    self.transformPolyDataFilter = vtk.vtkTransformPolyDataFilter()
    self.cellLocator = vtk.vtkCellLocator()

    # 3D View
    threeDWidget = slicer.app.layoutManager().threeDWidget(0)
    self.threeDView = threeDWidget.threeDView()
    
    self.callbackObserverTag = -1
    self.observerTag=None

    # Output Distance Label
    self.outputDistanceLabel=None

    
    import Viewpoint # Viewpoint Module must have been added to Slicer 
    self.viewpointLogic = Viewpoint.ViewpointLogic()

    # Camera transformations
    self.needleCameraToNeedle = slicer.util.getNode('needleCameraToNeedle')
    if not self.needleCameraToNeedle:
      self.needleCameraToNeedle=slicer.vtkMRMLLinearTransformNode()
      self.needleCameraToNeedle.SetName("needleCameraToNeedle")
      matrixNeedleCamera = vtk.vtkMatrix4x4()
      matrixNeedleCamera.SetElement( 0, 0, -0.05 ) # Row 1
      matrixNeedleCamera.SetElement( 0, 1, 0.09 )
      matrixNeedleCamera.SetElement( 0, 2, -0.99 )
      matrixNeedleCamera.SetElement( 0, 3, 60.72 )      
      matrixNeedleCamera.SetElement( 1, 0, -0.01 )  # Row 2
      matrixNeedleCamera.SetElement( 1, 1, 1 )
      matrixNeedleCamera.SetElement( 1, 2, 0.09 )
      matrixNeedleCamera.SetElement( 1, 3, 12.17 )       
      matrixNeedleCamera.SetElement( 2, 0, 1 )  # Row 3
      matrixNeedleCamera.SetElement( 2, 1, 0.01 )
      matrixNeedleCamera.SetElement( 2, 2, -0.05 )
      matrixNeedleCamera.SetElement( 2, 3, -7.26 )
      self.needleCameraToNeedle.SetMatrixTransformToParent(matrixNeedleCamera)
      slicer.mrmlScene.AddNode(self.needleCameraToNeedle)

    self.pointerCameraToPointer = slicer.util.getNode('pointerCameraToPointer')
    if not self.pointerCameraToPointer:
      self.pointerCameraToPointer=slicer.vtkMRMLLinearTransformNode()
      self.pointerCameraToPointer.SetName("pointerCameraToPointer")
      matrixPointerCamera = vtk.vtkMatrix4x4()
      matrixPointerCamera.SetElement( 0, 0, -0.05 ) # Row 1
      matrixPointerCamera.SetElement( 0, 1, 0.09 )
      matrixPointerCamera.SetElement( 0, 2, -0.99 )
      matrixPointerCamera.SetElement( 0, 3, 121.72 )      
      matrixPointerCamera.SetElement( 1, 0, -0.01 )  # Row 2
      matrixPointerCamera.SetElement( 1, 1, 1 )
      matrixPointerCamera.SetElement( 1, 2, 0.09 )
      matrixPointerCamera.SetElement( 1, 3, 17.17 )       
      matrixPointerCamera.SetElement( 2, 0, 1 )  # Row 3
      matrixPointerCamera.SetElement( 2, 1, 0.01 )
      matrixPointerCamera.SetElement( 2, 2, -0.05 )
      matrixPointerCamera.SetElement( 2, 3, -7.26 )
      self.pointerCameraToPointer.SetMatrixTransformToParent(matrixPointerCamera)
      slicer.mrmlScene.AddNode(self.pointerCameraToPointer)

    # Tranformations to fix models orientation
    self.needleModelToNeedleTip = slicer.util.getNode('needleModelToNeedleTip')
    if not self.needleModelToNeedleTip:
      self.needleModelToNeedleTip=slicer.vtkMRMLLinearTransformNode()
      self.needleModelToNeedleTip.SetName("needleModelToNeedleTip")
      matrixNeedleModel = vtk.vtkMatrix4x4()
      matrixNeedleModel.SetElement( 0, 0, -1 ) # Row 1
      matrixNeedleModel.SetElement( 0, 1, 0 )
      matrixNeedleModel.SetElement( 0, 2, 0 )
      matrixNeedleModel.SetElement( 0, 3, 0 )      
      matrixNeedleModel.SetElement( 1, 0, 0 )  # Row 2
      matrixNeedleModel.SetElement( 1, 1, 1 )
      matrixNeedleModel.SetElement( 1, 2, 0 )
      matrixNeedleModel.SetElement( 1, 3, 0 )       
      matrixNeedleModel.SetElement( 2, 0, 0 )  # Row 3
      matrixNeedleModel.SetElement( 2, 1, 0 )
      matrixNeedleModel.SetElement( 2, 2, -1 )
      matrixNeedleModel.SetElement( 2, 3, 0 )
      self.needleModelToNeedleTip.SetMatrixTransformToParent(matrixNeedleModel)
      slicer.mrmlScene.AddNode(self.needleModelToNeedleTip)

    self.pointerModelToPointerTip = slicer.util.getNode('pointerModelToPointerTip')
    if not self.pointerModelToPointerTip:
      self.pointerModelToPointerTip=slicer.vtkMRMLLinearTransformNode()
      self.pointerModelToPointerTip.SetName("pointerModelToPointerTip")
      matrixPointerModel = vtk.vtkMatrix4x4()
      matrixPointerModel.SetElement( 0, 0, 0 ) # Row 1
      matrixPointerModel.SetElement( 0, 1, 0 )
      matrixPointerModel.SetElement( 0, 2, 1 )
      matrixPointerModel.SetElement( 0, 3, 0 )      
      matrixPointerModel.SetElement( 1, 0, 0 )  # Row 2
      matrixPointerModel.SetElement( 1, 1, 1 )
      matrixPointerModel.SetElement( 1, 2, 0 )
      matrixPointerModel.SetElement( 1, 3, 0 )       
      matrixPointerModel.SetElement( 2, 0, -1 )  # Row 3
      matrixPointerModel.SetElement( 2, 1, 0 )
      matrixPointerModel.SetElement( 2, 2, 0 )
      matrixPointerModel.SetElement( 2, 3, 0 )
      self.pointerModelToPointerTip.SetMatrixTransformToParent(matrixPointerModel)
      slicer.mrmlScene.AddNode(self.pointerModelToPointerTip)


    self.fRBLToSLPR = slicer.util.getNode('FRBLToSLPR')    
    if not self.fRBLToSLPR:
      self.fRBLToSLPR = slicer.vtkMRMLLinearTransformNode()
      self.fRBLToSLPR.SetName('FRBLToSLPR')
      slicer.mrmlScene.AddNode(self.fRBLToSLPR)
      
    # Create fiducials to orientate model
    self.fiducialsFRBL = slicer.util.getNode('FiducialsFRBL')    
    if not self.fiducialsFRBL:
      self.fiducialsFRBL = slicer.vtkMRMLMarkupsFiducialNode()
      self.fiducialsFRBL.SetName('FiducialsFRBL')
      slicer.mrmlScene.AddNode(self.fiducialsFRBL)
      self.fiducialsFRBL.SetDisplayVisibility(False)
      
    self.fiducialsSLPR = slicer.util.getNode('FiducialsSLPR')    
    if not self.fiducialsSLPR:
      self.fiducialsSLPR = slicer.vtkMRMLMarkupsFiducialNode()
      self.fiducialsSLPR.SetName('FiducialsSLPR')
      self.fiducialsSLPR.AddFiducial(0, 100, 0)
      self.fiducialsSLPR.SetNthFiducialLabel(0, 'S')
      self.fiducialsSLPR.AddFiducial(-100, 0, 0)
      self.fiducialsSLPR.SetNthFiducialLabel(1, 'L')
      self.fiducialsSLPR.AddFiducial(0, -100, 0)
      self.fiducialsSLPR.SetNthFiducialLabel(2, 'P')
      self.fiducialsSLPR.AddFiducial(100, 0, 0)
      self.fiducialsSLPR.SetNthFiducialLabel(3, 'R')   
      slicer.mrmlScene.AddNode(self.fiducialsSLPR)
      self.fiducialsSLPR.SetDisplayVisibility(False)
示例#30
0
    def createModels(self):
        self.deleteModels()
        self.labelScores = []
        self.selectedLableList = []
        if self.calcinationType == 0 and self.volumeNode and self.roiNode:
            #print 'in Heart Create Models'

            slicer.vtkSlicerCropVolumeLogic().CropVoxelBased(self.roiNode, self.volumeNode, self.croppedNode)
            croppedImage    = sitk.ReadImage( sitkUtils.GetSlicerITKReadWriteAddress(self.croppedNode.GetName()))
            thresholdImage  = sitk.BinaryThreshold(croppedImage,self.ThresholdMin, self.ThresholdMax, 1, 0)
            connectedCompImage  =sitk.ConnectedComponent(thresholdImage, True)
            relabelImage  =sitk.RelabelComponent(connectedCompImage)
            labelStatFilter =sitk.LabelStatisticsImageFilter()
            labelStatFilter.Execute(croppedImage, relabelImage)
            if relabelImage.GetPixelID() != sitk.sitkInt16:
                relabelImage = sitk.Cast( relabelImage, sitk.sitkInt16 )
            sitk.WriteImage( relabelImage, sitkUtils.GetSlicerITKReadWriteAddress(self.labelsNode.GetName()))

            nLabels = labelStatFilter.GetNumberOfLabels()
            #print "Number of labels = ", nLabels
            self.totalScore = 0
            count = 0
            for n in range(0,nLabels):
                max = labelStatFilter.GetMaximum(n);
                size = labelStatFilter.GetCount(n)
                score = self.computeScore(max)

                if size*self.voxelVolume > self.MaximumLesionSize:
                    continue

                if size*self.voxelVolume < self.MinimumLesionSize:
                    nLabels = n+1
                    break
                
                #print "label = ", n, "  max = ", max, " score = ", score, " voxels = ", size
                self.labelScores.append(score)
                self.selectedLableList.append(0)
                self.marchingCubes.SetInputData(self.labelsNode.GetImageData())
                self.marchingCubes.SetValue(0, n)
                self.marchingCubes.Update()
                    
                self.transformPolyData.SetInputData(self.marchingCubes.GetOutput())
                mat = vtk.vtkMatrix4x4()
                self.labelsNode.GetIJKToRASMatrix(mat)
                trans = vtk.vtkTransform()
                trans.SetMatrix(mat)
                self.transformPolyData.SetTransform(trans)
                self.transformPolyData.Update()
                poly = vtk.vtkPolyData()
                poly.DeepCopy(self.transformPolyData.GetOutput())
                    
                modelNode = slicer.vtkMRMLModelNode()
                slicer.mrmlScene.AddNode(modelNode)
                dnode = slicer.vtkMRMLModelDisplayNode()
                slicer.mrmlScene.AddNode(dnode)
                modelNode.AddAndObserveDisplayNodeID(dnode.GetID())
                modelNode.SetAndObservePolyData(poly)

                ct=slicer.mrmlScene.GetNodeByID('vtkMRMLColorTableNodeLabels')
                rgb = [0,0,0]
                ct.GetLookupTable().GetColor(count+1,rgb)
                dnode.SetColor(rgb)

                self.addLabel(count, rgb, score)

                self.modelNodes.append(modelNode)
                self.selectedLables[poly] = n
                count = count+1
                #a = slicer.util.array(tn.GetID())
                #sa = sitk.GetImageFromArray(a)
            self.scoreField.setText(self.totalScore)
        else:
            print "not implemented"
示例#31
0
    def createModels(self):
        self.deleteModels()
        for sr in self.summary_reports:
            self.labelScores[sr]=[]
        self.selectedLabelList = []
        if self.calcificationType == 0 and self.volumeNode and self.roiNode:
            #print 'in Heart Create Models'

            slicer.vtkSlicerCropVolumeLogic().CropVoxelBased(self.roiNode, self.volumeNode, self.croppedNode)
            croppedImage    = sitk.ReadImage( sitkUtils.GetSlicerITKReadWriteAddress(self.croppedNode.GetName()))
            thresholdImage  = sitk.BinaryThreshold(croppedImage,self.ThresholdMin, self.ThresholdMax, 1, 0)
            connectedCompImage  =sitk.ConnectedComponent(thresholdImage, True)
            relabelImage  =sitk.RelabelComponent(connectedCompImage)
            labelStatFilter =sitk.LabelStatisticsImageFilter()
            labelStatFilter.Execute(croppedImage, relabelImage)
            if relabelImage.GetPixelID() != sitk.sitkInt16:
                relabelImage = sitk.Cast( relabelImage, sitk.sitkInt16 )
            sitk.WriteImage( relabelImage, sitkUtils.GetSlicerITKReadWriteAddress(self.labelsNode.GetName()))

            nLabels = labelStatFilter.GetNumberOfLabels()
            #print "Number of labels = ", nLabels
            self.totalScore = 0
            count = 0
            #Computation of the score follows this paper:
            #C. H McCollough, Radiology, 243(2), 2007
            
            for n in range(0,nLabels):
                max = labelStatFilter.GetMaximum(n)
                mean = labelStatFilter.GetMean(n)
                size = labelStatFilter.GetCount(n)
                volume = size*self.voxelVolume
                if volume > self.MaximumLesionSize:
                    continue

                if volume < self.MinimumLesionSize:
                    nLabels = n+1
                    break
                
                density_score = self.computeDensityScore(max)

                #Agatston score is \sum_i area_i * density_score_i
                #For now we assume that all the plaques have the same density score
                score = size*(self.sx*self.sy)*density_score
                
                mass_score = mean*volume

                #print "label = ", n, "  max = ", max, " score = ", score, " voxels = ", size
                self.labelScores["Agatston Score"].append(score)
                self.labelScores["Mass Score"].append(mass_score)
                self.labelScores["Volume"].append(volume)
                self.selectedLabelList.append(0)
                self.marchingCubes.SetInputData(self.labelsNode.GetImageData())
                self.marchingCubes.SetValue(0, n)
                self.marchingCubes.Update()
                    
                self.transformPolyData.SetInputData(self.marchingCubes.GetOutput())
                mat = vtk.vtkMatrix4x4()
                self.labelsNode.GetIJKToRASMatrix(mat)
                trans = vtk.vtkTransform()
                trans.SetMatrix(mat)
                self.transformPolyData.SetTransform(trans)
                self.transformPolyData.Update()
                poly = vtk.vtkPolyData()
                poly.DeepCopy(self.transformPolyData.GetOutput())
                    
                modelNode = slicer.vtkMRMLModelNode()
                slicer.mrmlScene.AddNode(modelNode)
                dnode = slicer.vtkMRMLModelDisplayNode()
                slicer.mrmlScene.AddNode(dnode)
                modelNode.AddAndObserveDisplayNodeID(dnode.GetID())
                modelNode.SetAndObservePolyData(poly)

                ct=slicer.mrmlScene.GetNodeByID('vtkMRMLColorTableNodeLabels')
                rgb = [0,0,0]
                ct.GetLookupTable().GetColor(count+1,rgb)
                dnode.SetColor(rgb)
                #Enable Slice intersection
                dnode.SetSliceDisplayMode(0)
                dnode.SetSliceIntersectionVisibility(1)

                self.addLabel(count, rgb, [score,mass_score,volume,mean,max])
                count = count+1

                self.modelNodes.append(modelNode)
                self.selectedLabels[poly] = n
                #a = slicer.util.array(tn.GetID())
                #sa = sitk.GetImageFromArray(a)
            for sr in self.summary_reports:
                self.scoreField[sr].setText(self.totalScores[sr])
        else:
            print ("not implemented")
示例#32
0
文件: slicr.py 项目: blezek/SlicerWeb
  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)
    print (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" )
示例#33
0
 def setAndObserveDisplayNode(node):
     displayNode = slicer.vtkMRMLModelDisplayNode()
     slicer.mrmlScene.AddNode(displayNode)
     node.SetAndObserveDisplayNodeID(displayNode.GetID())
     return displayNode
  def __init__(self):
    self.toolTipToTool = slicer.util.getNode('toolTipToTool')
    if not self.toolTipToTool:
      self.toolTipToTool=slicer.vtkMRMLLinearTransformNode()
      self.toolTipToTool.SetName("toolTipToTool")
      m = vtk.vtkMatrix4x4()
      m.SetElement( 0, 0, 1 ) # Row 1
      m.SetElement( 0, 1, 0 )
      m.SetElement( 0, 2, 0 )
      m.SetElement( 0, 3, 0 )      
      m.SetElement( 1, 0, 0 )  # Row 2
      m.SetElement( 1, 1, 1 )
      m.SetElement( 1, 2, 0 )
      m.SetElement( 1, 3, 0 )       
      m.SetElement( 2, 0, 0 )  # Row 3
      m.SetElement( 2, 1, 0 )
      m.SetElement( 2, 2, 1 )
      m.SetElement( 2, 3, 0 )
      self.toolTipToTool.SetMatrixTransformToParent(m)
      slicer.mrmlScene.AddNode(self.toolTipToTool)

    self.toolToReference = slicer.util.getNode('toolToReference')
    if not self.toolToReference:
      self.toolToReference=slicer.vtkMRMLLinearTransformNode()
      self.toolToReference.SetName("toolToReference")
      matrixRef = vtk.vtkMatrix4x4()
      matrixRef.SetElement( 0, 0, 1 ) # Row 1
      matrixRef.SetElement( 0, 1, 0 )
      matrixRef.SetElement( 0, 2, 0 )
      matrixRef.SetElement( 0, 3, 0 )      
      matrixRef.SetElement( 1, 0, 0 )  # Row 2
      matrixRef.SetElement( 1, 1, 1 )
      matrixRef.SetElement( 1, 2, 0 )
      matrixRef.SetElement( 1, 3, 0 )       
      matrixRef.SetElement( 2, 0, 0 )  # Row 3
      matrixRef.SetElement( 2, 1, 0 )
      matrixRef.SetElement( 2, 2, 1 )
      matrixRef.SetElement( 2, 3, 0 )
      self.toolToReference.SetMatrixTransformToParent(matrixRef)
      slicer.mrmlScene.AddNode(self.toolToReference)
   
    self.tipFiducial = slicer.util.getNode('Tip')
    if not self.tipFiducial:
      self.tipFiducial = slicer.vtkMRMLMarkupsFiducialNode()  
      self.tipFiducial.SetName('Tip')
      self.tipFiducial.AddFiducial(0, 0, 0)
      self.tipFiducial.SetNthFiducialLabel(0, '')
      slicer.mrmlScene.AddNode(self.tipFiducial)
      self.tipFiducial.SetDisplayVisibility(True)
      self.tipFiducial.GetDisplayNode().SetGlyphType(1) # Vertex2D
      self.tipFiducial.GetDisplayNode().SetTextScale(1.3)
      self.tipFiducial.GetDisplayNode().SetSelectedColor(1,1,1)

    self.targetFiducial = slicer.util.getNode('Target')
    if not self.targetFiducial:
      self.targetFiducial = slicer.vtkMRMLMarkupsFiducialNode()  
      self.targetFiducial.SetName('Target')
      self.targetFiducial.AddFiducial(0, 0, 0)
      self.targetFiducial.SetNthFiducialLabel(0, '')
      slicer.mrmlScene.AddNode(self.targetFiducial)
      self.targetFiducial.SetDisplayVisibility(True)
      self.targetFiducial.GetDisplayNode().SetGlyphType(1) # Vertex2D
      self.targetFiducial.GetDisplayNode().SetTextScale(1.3)
      self.targetFiducial.GetDisplayNode().SetSelectedColor(1,1,1)
      
    self.line = slicer.util.getNode('Line')
    if not self.line:
      self.line = slicer.vtkMRMLModelNode()
      self.line.SetName('Line')
      linePolyData = vtk.vtkPolyData()
      self.line.SetAndObservePolyData(linePolyData)      
      modelDisplay = slicer.vtkMRMLModelDisplayNode()
      modelDisplay.SetSliceIntersectionVisibility(True)
      modelDisplay.SetColor(0,1,0)
      slicer.mrmlScene.AddNode(modelDisplay)      
      self.line.SetAndObserveDisplayNodeID(modelDisplay.GetID())      
      slicer.mrmlScene.AddNode(self.line)
      
    # VTK objects
    self.transformPolyDataFilter = vtk.vtkTransformPolyDataFilter()
    self.cellLocator = vtk.vtkCellLocator()
    
    # 3D View
    threeDWidget = slicer.app.layoutManager().threeDWidget(0)
    self.threeDView = threeDWidget.threeDView()
    
    self.callbackObserverTag = -1
    self.observerTag=None

    # Output Distance Label
    self.outputDistanceLabel=None

    import Viewpoint # Viewpoint Module must have been added to Slicer 
    self.viewpointLogic = Viewpoint.ViewpointLogic()

    # Camera transformations
    self.needleCameraToNeedle = slicer.util.getNode('needleCameraToNeedle')
    if not self.needleCameraToNeedle:
      self.needleCameraToNeedle=slicer.vtkMRMLLinearTransformNode()
      self.needleCameraToNeedle.SetName("needleCameraToNeedle")
      matrixNeedleCamera = vtk.vtkMatrix4x4()
      matrixNeedleCamera.SetElement( 0, 0, -0.05 ) # Row 1
      matrixNeedleCamera.SetElement( 0, 1, 0.09 )
      matrixNeedleCamera.SetElement( 0, 2, -0.99 )
      matrixNeedleCamera.SetElement( 0, 3, 60.72 )      
      matrixNeedleCamera.SetElement( 1, 0, -0.01 )  # Row 2
      matrixNeedleCamera.SetElement( 1, 1, 1 )
      matrixNeedleCamera.SetElement( 1, 2, 0.09 )
      matrixNeedleCamera.SetElement( 1, 3, 12.17 )       
      matrixNeedleCamera.SetElement( 2, 0, 1 )  # Row 3
      matrixNeedleCamera.SetElement( 2, 1, 0.01 )
      matrixNeedleCamera.SetElement( 2, 2, -0.05 )
      matrixNeedleCamera.SetElement( 2, 3, -7.26 )
      self.needleCameraToNeedle.SetMatrixTransformToParent(matrixNeedleCamera)
      slicer.mrmlScene.AddNode(self.needleCameraToNeedle)

    self.pointerCameraToPointer = slicer.util.getNode('pointerCameraToPointer')
    if not self.pointerCameraToPointer:
      self.pointerCameraToPointer=slicer.vtkMRMLLinearTransformNode()
      self.pointerCameraToPointer.SetName("pointerCameraToPointer")
      matrixPointerCamera = vtk.vtkMatrix4x4()
      matrixPointerCamera.SetElement( 0, 0, -0.05 ) # Row 1
      matrixPointerCamera.SetElement( 0, 1, 0.09 )
      matrixPointerCamera.SetElement( 0, 2, -0.99 )
      matrixPointerCamera.SetElement( 0, 3, 121.72 )      
      matrixPointerCamera.SetElement( 1, 0, -0.01 )  # Row 2
      matrixPointerCamera.SetElement( 1, 1, 1 )
      matrixPointerCamera.SetElement( 1, 2, 0.09 )
      matrixPointerCamera.SetElement( 1, 3, 17.17 )       
      matrixPointerCamera.SetElement( 2, 0, 1 )  # Row 3
      matrixPointerCamera.SetElement( 2, 1, 0.01 )
      matrixPointerCamera.SetElement( 2, 2, -0.05 )
      matrixPointerCamera.SetElement( 2, 3, -7.26 )
      self.pointerCameraToPointer.SetMatrixTransformToParent(matrixPointerCamera)
      slicer.mrmlScene.AddNode(self.pointerCameraToPointer)
示例#35
0
    def new_electrode(self):
        """
        Create new electrode model and paired,hidden transform.
        """
        if self.curr_electrode:
            # Get Current Electrode
            self.curr_electrode = self.input_selector.currentNode()
            self.save_electrode_properties(self.curr_electrode)

            # Harden transform
            # logic=slicer.vtkSlicerTransformLogic()
            # logic.hardenTransform(self.curr_electrode)
            electrode_transform = slicer.util.getNode(
                "Transform_" + self.curr_electrode.GetName())
            self.curr_electrode.SetAndObserveTransformNodeID(
                electrode_transform.GetID())

        # Set up new electrode
        origin = [0, 0, 0]
        terminus = [0, 0, 200]

        # This section takes care of the "Electrode"
        line = vtk.vtkLineSource()
        line.SetPoint1(origin)
        line.SetPoint2(terminus)
        line.Update()

        tube_filter = vtk.vtkTubeFilter()
        tube_filter.SetCapping(True)
        tube_filter.SetRadius(1.1)
        tube_filter.SetNumberOfSides(20)

        tube_filter.SetInputDataObject(line.GetOutput())
        tube_filter.Update()

        electrode = tube_filter.GetOutput()

        new_electrode = slicer.vtkMRMLModelNode()
        new_electrode.SetAndObservePolyData(electrode)

        slicer.mrmlScene.AddNode(new_electrode)

        electrode_display_node = slicer.vtkMRMLModelDisplayNode()
        slicer.mrmlScene.AddNode(electrode_display_node)

        electrode_display_node.SetName("NeedleModelDisplay")
        electrode_display_node.SetColor(0.0, 1.0, 1.0)

        new_electrode.SetAndObserveDisplayNodeID(
            electrode_display_node.GetID())
        electrode_display_node.SetAmbient(0.2)
        electrode_display_node.SetSliceIntersectionVisibility(True)

        new_electrode.SetAndObserveTransformNodeID(
            slicer.util.getNode("Arc").GetID())
        self.curr_electrode = new_electrode
        electrode_transform = slicer.vtkMRMLLinearTransformNode()
        electrode_transform.SetName("Transform_" +
                                    self.curr_electrode.GetName())
        electrode_transform.SetHideFromEditors(True)
        slicer.mrmlScene.AddNode(electrode_transform)
        self.save_electrode_properties(new_electrode)
        self.input_selector.setCurrentNodeID(new_electrode.GetID())
示例#36
0
    def createModels(self):
        # Reset previous model and labels
        self.deleteModels()
        for sr in self.summary_reports:
            self.labelScores[sr] = []
        self.selectedLabelList = []

        if self.calcificationType == 0 and self.volumeNode and self.roiNode:
            slicer.vtkSlicerCropVolumeLogic().CropVoxelBased(
                self.roiNode, self.volumeNode, self.croppedNode)
            croppedImage = sitk.ReadImage(
                sitkUtils.GetSlicerITKReadWriteAddress(
                    self.croppedNode.GetName()))
            thresholdImage = sitk.BinaryThreshold(croppedImage,
                                                  self.ThresholdMin,
                                                  self.ThresholdMax, 1, 0)
            connectedCompImage = sitk.ConnectedComponent(thresholdImage, True)
            relabelImage = sitk.RelabelComponent(connectedCompImage)
            labelStatFilter = sitk.LabelStatisticsImageFilter()
            labelStatFilter.Execute(croppedImage, relabelImage)
            if relabelImage.GetPixelID() != sitk.sitkInt16:
                relabelImage = sitk.Cast(relabelImage, sitk.sitkInt16)
            sitk.WriteImage(
                relabelImage,
                sitkUtils.GetSlicerITKReadWriteAddress(
                    self.labelsNode.GetName()))

            prod_spacing = np.prod(croppedImage.GetSpacing())

            nLabels = labelStatFilter.GetNumberOfLabels()
            self.totalScore = 0
            count = 0
            for n in range(0, nLabels):
                max = labelStatFilter.GetMaximum(n)
                mean = labelStatFilter.GetMean(n)
                size = labelStatFilter.GetCount(n)
                volume = size * self.voxelVolume

                # current label is discarted if volume not meet the maximum allowed threshold
                if volume > self.MaximumLesionSize:
                    continue

                # As ordered, we stop here if the volume of the current label is less than threshold
                if volume < self.MinimumLesionSize:
                    nLabels = n + 1
                    break
                score2d, volume, mass_score = self.agatston_computation(
                    n, relabelImage, croppedImage, prod_spacing)
                # Agatston 3d:
                # -----------
                density_score = self.computeDensityScore(max)
                score3d = size * (self.sx * self.sy) * density_score
                mass_score = mean * volume

                # self.labelScores["Agatston Score"].append(score)
                self.labelScores["Agatston Score 3D"].append(score3d)
                self.labelScores["Agatston Score 2D"].append(score2d)
                self.labelScores["Mass Score"].append(mass_score)
                self.labelScores["Volume"].append(volume)
                self.selectedLabelList.append(0)

                # generate the contour
                marchingCubes = vtk.vtkDiscreteMarchingCubes()
                marchingCubes.SetInputData(self.labelsNode.GetImageData())
                marchingCubes.SetValue(0, count + 1)
                marchingCubes.Update()

                transformPolyData = vtk.vtkTransformPolyDataFilter()
                transformPolyData.SetInputData(marchingCubes.GetOutput())
                mat = vtk.vtkMatrix4x4()
                self.labelsNode.GetIJKToRASMatrix(mat)
                trans = vtk.vtkTransform()
                trans.SetMatrix(mat)
                transformPolyData.SetTransform(trans)
                transformPolyData.Update()
                poly = vtk.vtkPolyData()
                poly.DeepCopy(transformPolyData.GetOutput())

                modelNode = slicer.vtkMRMLModelNode()
                slicer.mrmlScene.AddNode(modelNode)
                dnode = slicer.vtkMRMLModelDisplayNode()
                slicer.mrmlScene.AddNode(dnode)
                modelNode.AddAndObserveDisplayNodeID(dnode.GetID())
                modelNode.SetAndObservePolyData(poly)

                ct = slicer.mrmlScene.GetNodeByID(
                    'vtkMRMLColorTableNodeLabels')
                rgb = [0, 0, 0]
                ct.GetLookupTable().GetColor(count + 1, rgb)
                dnode.SetColor(rgb)
                # Enable Slice intersection
                dnode.SetSliceDisplayMode(0)
                dnode.SetSliceIntersectionVisibility(1)

                # self.addLabel(count, rgb, [score, mass_score, volume, mean, max])
                self.addLabel(
                    count, rgb,
                    [score2d, score3d, mass_score, volume, mean, max])
                count = count + 1

                self.modelNodes.append(modelNode)
                self.selectedLabels[poly] = n

            for sr in self.summary_reports:
                self.scoreField[sr].setText(self.totalScores[sr])
示例#37
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)

    import vtk.util.numpy_support as VN
    pointsArray = VN.vtk_to_numpy(points.GetData())
    self.planePosition, self.planeNormal = self.planeFit(pointsArray.T)

    # 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
    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.SetPolyDataConnection(sphere.GetOutputPort())

    # 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
    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
示例#38
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
    if vtk.VTK_MAJOR_VERSION <= 5:
      # shall not be needed.
      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()))
    if vtk.VTK_MAJOR_VERSION <= 5:
      cursor.SetAndObservePolyData(sphere.GetOutput())
    else:
      cursor.SetPolyDataConnection(sphere.GetOutputPort())

    # 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
    if vtk.VTK_MAJOR_VERSION <= 5:
      # Shall not be needed.
      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
示例#39
0
    def run(self, list, filepath, filename, downsample, signals, sensor,
            useSensorLimits, index):
        self.filename = filename
        self.index = index
        browser = slicer.vtkMRMLSequenceBrowserNode()
        browser.SetName(filename + ' (' + index + ')')
        slicer.mrmlScene.AddNode(browser)

        if useSensorLimits:
            colorMap = self.createColorMap(sensor["sensorMin"],
                                           sensor["sensorMax"])
        else:
            colorMap = self.createColorMap(sensor["dataMin"],
                                           sensor["dataMax"])

        num_of_fiducials = min(list.GetNumberOfFiducials(),
                               len(sensor["indices"]))
        counter = 0

        points = vtk.vtkPoints()

        #Get the first row data
        colors = self.getRowAsArray(signals, sensor, counter, num_of_fiducials)

        arr = [0, 0, 0]

        for i in range(0, num_of_fiducials):
            list.GetNthFiducialPosition(i, arr)
            points.InsertNextPoint(arr[0], arr[1], arr[2])

        self.polydata = vtk.vtkPolyData()
        self.polydata.SetPoints(points)
        self.polydata.GetPointData().SetScalars(colors)

        sphereSource = vtk.vtkSphereSource()
        sphereSource.SetRadius(3)

        self.glyph3D = vtk.vtkGlyph3D()
        self.glyph3D.SetColorModeToColorByScalar()
        self.glyph3D.SetSourceConnection(sphereSource.GetOutputPort())
        self.glyph3D.SetInputData(self.polydata)
        self.glyph3D.ScalingOff()
        self.glyph3D.Update()

        self.display = slicer.vtkMRMLModelDisplayNode()
        self.display.SetScalarVisibility(1)
        self.display.SetActiveScalarName("EDF Magnitude")
        self.display.SetName("EDF Magnitude (" + index + ")")
        slicer.mrmlScene.AddNode(self.display)

        model = slicer.vtkMRMLModelNode()
        model.SetName("EDF Magnitude (" + index + ")")
        slicer.mrmlScene.AddNode(model)

        model.SetAndObservePolyData(self.glyph3D.GetOutput())
        model.SetAndObserveDisplayNodeID(self.display.GetID())
        self.display.SetScalarRangeFlag(0)
        self.display.SetAndObserveColorNodeID(colorMap.GetID())

        #Add the Sequence Nodes
        self.addSequence(browser, model, "Model (" + index + ")")
        self.addSequence(browser, self.display, "ModelDisplay (" + index + ")")

        # Get the remaining rows
        while counter < len(signals):
            counter += 1
            if counter % downsample != 0:
                continue
            model.SetAndObservePolyData(self.glyph3D.GetOutput())
            newArr = self.getRowAsArray(signals, sensor, counter,
                                        num_of_fiducials)
            self.polydata.GetPointData().AddArray(newArr)
            self.glyph3D.Modified()
            self.glyph3D.Update()
            self.display.SetActiveScalarName("EDF Magnitude " + str(counter))
            browser.SaveProxyNodesState()  #update the sequence

        return True
示例#40
0
    def visualizeNewSrep(self, filename):
        # 1. parse header file
        tree = ET.parse(filename)
        upFileName = ''
        crestFileName = ''
        downFileName = ''
        nCols = 0
        nRows = 0
        for child in tree.getroot():
            if child.tag == 'upSpoke':
                upFileName = child.text
            elif child.tag == 'downSpoke':
                downFileName = child.text
            elif child.tag == 'crestSpoke':
                crestFileName = child.text
            elif child.tag == 'nRows':
                nRows = (int)(child.text)
            elif child.tag == 'nCols':
                nCols = (int)(child.text)

        reader = vtk.vtkXMLPolyDataReader()
        reader.SetFileName(upFileName)
        reader.Update()

        upSpokes = reader.GetOutput()

        upPointData = upSpokes.GetPointData()
        medial_polyData = upSpokes  # this is poly data for skeleton

        scene = slicer.mrmlScene

        # base line of medial sheet
        fidDisplayNode = slicer.vtkMRMLMarkupsDisplayNode()
        scene.AddNode(fidDisplayNode)
        fidNode = slicer.vtkMRMLMarkupsFiducialNode()
        fidDisplayNode.SetGlyphScale(0.01)
        fidDisplayNode.SetSelectedColor(1.0, 1.0, 0.0)
        fidDisplayNode.SetTextScale(0.0)
        scene.AddNode(fidNode)
        fidNode.SetAndObserveDisplayNodeID(fidDisplayNode.GetID())
        # \TODO come up with better name later

        # prepare for arrows for upspokes
        upSpoke_points = vtk.vtkPoints()
        upSpoke_lines = vtk.vtkCellArray()

        arr_length = upPointData.GetArray('spokeLength')
        arr_dirs = upPointData.GetArray('spokeDirection')
        for i in range(upSpokes.GetNumberOfPoints()):
            pt = [0] * 3
            upSpokes.GetPoint(i, pt)
            # base point of up arrows
            id0 = upSpoke_points.InsertNextPoint(pt)

            # head of up arrows
            spoke_length = arr_length.GetValue(i)
            baseIdx = i * 3
            dirX = arr_dirs.GetValue(baseIdx)
            dirY = arr_dirs.GetValue(baseIdx + 1)
            dirZ = arr_dirs.GetValue(baseIdx + 2)
            pt1 = [0] * 3
            pt1[0] = pt[0] + spoke_length * dirX
            pt1[1] = pt[1] + spoke_length * dirY
            pt1[2] = pt[2] + spoke_length * dirZ
            id1 = upSpoke_points.InsertNextPoint(pt1)

            up_arrow = vtk.vtkLine()
            up_arrow.GetPointIds().SetId(0, id0)
            up_arrow.GetPointIds().SetId(1, id1)
            upSpoke_lines.InsertNextCell(up_arrow)

            fidNode.AddFiducial(pt[0], pt[1], pt[2])

        boundary_point_ids = []

        # model node for medial mesh
        medial_model = slicer.vtkMRMLModelNode()
        medial_model.SetScene(scene)
        medial_model.SetName("Medial Mesh")
        medial_model.SetAndObservePolyData(reader.GetOutput())
        # model display node for the medial mesh
        medial_model_display = slicer.vtkMRMLModelDisplayNode()
        medial_model_display.SetColor(0, 0.5, 0)
        medial_model_display.SetScene(scene)
        medial_model_display.SetLineWidth(3.0)
        medial_model_display.SetRepresentation(1)
        medial_model_display.SetBackfaceCulling(0)
        scene.AddNode(medial_model_display)
        medial_model.SetAndObserveDisplayNodeID(medial_model_display.GetID())
        scene.AddNode(medial_model)

        # model node for up spoke (poly data for arrows)
        upSpoke_polyData = vtk.vtkPolyData()
        upSpoke_polyData.SetPoints(upSpoke_points)
        upSpoke_polyData.SetLines(upSpoke_lines)

        upSpoke_model = slicer.vtkMRMLModelNode()
        upSpoke_model.SetScene(scene)
        upSpoke_model.SetName("Top Spoke")
        upSpoke_model.SetAndObservePolyData(upSpoke_polyData)
        # model display node for the top spoke
        # cyan for the top spoke
        upSpoke_model_display = slicer.vtkMRMLModelDisplayNode()
        upSpoke_model_display.SetColor(0, 1, 1)
        upSpoke_model_display.SetScene(scene)
        upSpoke_model_display.SetLineWidth(3.0)
        upSpoke_model_display.SetBackfaceCulling(0)
        scene.AddNode(upSpoke_model_display)
        upSpoke_model.SetAndObserveDisplayNodeID(upSpoke_model_display.GetID())
        scene.AddNode(upSpoke_model)

        # prepare for down spokes
        reader.SetFileName(downFileName)
        reader.Update()
        downSpokes = reader.GetOutput()

        downSpoke_polyData = vtk.vtkPolyData()
        downSpoke_lines = vtk.vtkCellArray()
        downSpoke_points = vtk.vtkPoints()

        downPointData = downSpokes.GetPointData()
        arr_length = downPointData.GetArray('spokeLength')
        arr_dirs = downPointData.GetArray('spokeDirection')
        for i in range(downSpokes.GetNumberOfPoints()):
            # tail of arrows
            pt_tail = [0] * 3
            downSpokes.GetPoint(i, pt_tail)
            id0 = downSpoke_points.InsertNextPoint(pt_tail)

            # head of arrows
            pt_head = [0] * 3
            spoke_length = arr_length.GetValue(i)
            baseIdx = i * 3
            dirX = arr_dirs.GetValue(baseIdx)
            dirY = arr_dirs.GetValue(baseIdx + 1)
            dirZ = arr_dirs.GetValue(baseIdx + 2)
            pt_head[0] = pt_tail[0] + spoke_length * dirX
            pt_head[1] = pt_tail[1] + spoke_length * dirY
            pt_head[2] = pt_tail[2] + spoke_length * dirZ
            id1 = downSpoke_points.InsertNextPoint(pt_head)

            # connection between head and tail
            con = vtk.vtkLine()
            con.GetPointIds().SetId(0, id0)
            con.GetPointIds().SetId(1, id1)
            downSpoke_lines.InsertNextCell(con)

        downSpoke_polyData.SetPoints(downSpoke_points)
        downSpoke_polyData.SetLines(downSpoke_lines)

        downSpoke_model = slicer.vtkMRMLModelNode()
        downSpoke_model.SetScene(scene)
        downSpoke_model.SetName("Bottom Spoke")
        downSpoke_model.SetAndObservePolyData(downSpoke_polyData)
        # model display node for the down spoke
        downSpoke_model_display = slicer.vtkMRMLModelDisplayNode()
        downSpoke_model_display.SetColor(1, 0, 1)
        downSpoke_model_display.SetScene(scene)
        downSpoke_model_display.SetLineWidth(3.0)
        downSpoke_model_display.SetBackfaceCulling(0)
        scene.AddNode(downSpoke_model_display)
        downSpoke_model.SetAndObserveDisplayNodeID(
            downSpoke_model_display.GetID())
        scene.AddNode(downSpoke_model)

        # crest spoke
        new_reader = vtk.vtkXMLPolyDataReader()
        new_reader.SetFileName(crestFileName)
        new_reader.Update()
        foldCurve_polyData = new_reader.GetOutput()
        foldPointData = foldCurve_polyData.GetPointData()
        arr_length = foldPointData.GetArray('spokeLength')
        arr_dirs = foldPointData.GetArray('spokeDirection')
        crest_arrows_polydata = vtk.vtkPolyData()
        crest_arrows_points = vtk.vtkPoints()
        crest_arrows_lines = vtk.vtkCellArray()
        for i in range(foldCurve_polyData.GetNumberOfPoints()):
            # tail of crest arrows
            pt_tail = [0] * 3
            foldCurve_polyData.GetPoint(i, pt_tail)
            id0 = crest_arrows_points.InsertNextPoint(pt_tail)

            # head of crest arrows
            pt_head = [0] * 3
            spoke_length = arr_length.GetValue(i)
            baseIdx = i * 3
            dirX = arr_dirs.GetValue(baseIdx)
            dirY = arr_dirs.GetValue(baseIdx + 1)
            dirZ = arr_dirs.GetValue(baseIdx + 2)
            pt_head[0] = pt_tail[0] + spoke_length * dirX
            pt_head[1] = pt_tail[1] + spoke_length * dirY
            pt_head[2] = pt_tail[2] + spoke_length * dirZ
            id1 = crest_arrows_points.InsertNextPoint(pt_head)

            crest_line = vtk.vtkLine()
            crest_line.GetPointIds().SetId(0, id0)
            crest_line.GetPointIds().SetId(1, id1)
            crest_arrows_lines.InsertNextCell(crest_line)

        crest_arrows_polydata.SetPoints(crest_arrows_points)
        crest_arrows_polydata.SetLines(crest_arrows_lines)

        # show crest arrows
        crestSpoke_model = slicer.vtkMRMLModelNode()
        crestSpoke_model.SetScene(scene)
        crestSpoke_model.SetName("Crest Spoke")
        crestSpoke_model.SetAndObservePolyData(crest_arrows_polydata)
        # model display node
        crestSpoke_model_display = slicer.vtkMRMLModelDisplayNode()
        crestSpoke_model_display.SetColor(1, 1, 0)
        crestSpoke_model_display.SetScene(scene)
        crestSpoke_model_display.SetLineWidth(3.0)
        crestSpoke_model_display.SetBackfaceCulling(0)
        scene.AddNode(crestSpoke_model_display)
        crestSpoke_model.SetAndObserveDisplayNodeID(
            crestSpoke_model_display.GetID())
        scene.AddNode(crestSpoke_model)

        # show fold curve
        foldCurve_model = slicer.vtkMRMLModelNode()
        foldCurve_model.SetScene(scene)
        foldCurve_model.SetName("Fold Curve")
        foldCurve_model.SetAndObservePolyData(foldCurve_polyData)
        # model display node
        foldCurve_model_display = slicer.vtkMRMLModelDisplayNode()
        foldCurve_model_display.SetColor(1, 1, 0)
        foldCurve_model_display.SetScene(scene)
        foldCurve_model_display.SetLineWidth(3.0)
        foldCurve_model_display.SetBackfaceCulling(0)
        scene.AddNode(foldCurve_model_display)
        foldCurve_model.SetAndObserveDisplayNodeID(
            foldCurve_model_display.GetID())
        scene.AddNode(foldCurve_model)

        # show connections to fold curve point from nearby interior points
        # compute the nearest interior point
        connection_polydata = vtk.vtkPolyData()
        connection_points = vtk.vtkPoints()
        connection_lines = vtk.vtkCellArray()
        for i in range(foldCurve_polyData.GetNumberOfPoints()):
            min_dist = 100000.0
            nearest_index = 0
            pt_fold = [0] * 3
            foldCurve_polyData.GetPoint(i, pt_fold)
            id0 = connection_points.InsertNextPoint(pt_fold)

            for j in range(upSpokes.GetNumberOfPoints()):
                pt_interior = [0] * 3
                upSpokes.GetPoint(j, pt_interior)
                dist = math.sqrt((pt_fold[0] - pt_interior[0])**2 +
                                 (pt_fold[1] - pt_interior[1])**2 +
                                 (pt_fold[2] - pt_interior[2])**2)
                if dist < min_dist:
                    min_dist = dist
                    nearest_index = j

            pt_nearest_interior = upSpokes.GetPoint(nearest_index)
            id1 = connection_points.InsertNextPoint(pt_nearest_interior)
            line = vtk.vtkLine()

            line.GetPointIds().SetId(0, id0)
            line.GetPointIds().SetId(1, id1)

            connection_lines.InsertNextCell(line)

        connection_polydata.SetPoints(connection_points)
        connection_polydata.SetLines(connection_lines)
        connection_model = slicer.vtkMRMLModelNode()
        connection_model.SetScene(scene)
        connection_model.SetName("Connection to Fold Curve")
        connection_model.SetAndObservePolyData(connection_polydata)
        # model display node
        connection_model_display = slicer.vtkMRMLModelDisplayNode()
        connection_model_display.SetColor(0, 0, 0)
        connection_model_display.SetScene(scene)
        connection_model_display.SetLineWidth(3.0)
        connection_model_display.SetBackfaceCulling(0)
        scene.AddNode(connection_model_display)
        connection_model.SetAndObserveDisplayNodeID(
            connection_model_display.GetID())
        scene.AddNode(connection_model)
示例#41
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)

        import vtk.util.numpy_support as VN
        pointsArray = VN.vtk_to_numpy(points.GetData())
        self.planePosition, self.planeNormal = self.planeFit(pointsArray.T)

        # 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
        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.SetPolyDataConnection(sphere.GetOutputPort())

        # 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
        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
示例#42
0
    def visualizeNewSrep(self, filename):
        """ Parse header.xml file, create models from the data, and visualize it. """
        # 1. parse header file
        tree = ET.parse(filename)
        upFileName = ''
        crestFileName = ''
        downFileName = ''
        nCols = 0
        nRows = 0
        headerFolder = os.path.dirname(filename)
        for child in tree.getroot():
            if child.tag == 'upSpoke':
                if os.path.isabs(child.text):
                    upFileName = os.path.join(headerFolder, child.text)
                upFileName = os.path.join(headerFolder, child.text)
            elif child.tag == 'downSpoke':
                downFileName = os.path.join(headerFolder, child.text)
            elif child.tag == 'crestSpoke':
                crestFileName = os.path.join(headerFolder, child.text)
            elif child.tag == 'nRows':
                nRows = (int)(child.text)
            elif child.tag == 'nCols':
                nCols = (int)(child.text)

        logging.info("upSpoke file: " + upFileName)
        logging.info("downSpoke file: " + downFileName)
        logging.info("crestSpoke file: " + crestFileName)

        reader = vtk.vtkXMLPolyDataReader()
        reader.SetFileName(upFileName)
        reader.Update()

        upSpokes = reader.GetOutput()

        upPointData = upSpokes.GetPointData()
        numberOfArrays = upPointData.GetNumberOfArrays()
        if numberOfArrays is 0:
            logging.warning("File: " + upFileName + " does not contain data")

        # medial_polyData = upSpokes #  this is poly data for skeleton

        scene = slicer.mrmlScene

        # base line of medial sheet
        fidDisplayNode = slicer.vtkMRMLMarkupsDisplayNode()
        scene.AddNode(fidDisplayNode)
        fidNode = slicer.vtkMRMLMarkupsFiducialNode()
        # If we would have more than 100 fiducial points (meant for editing points) better to use a regular MRMLModelNode
        # In the future, we would like the user to be able to move the nodes, and the connected structures to update accordingly.
        # Meanwhile, we lock the moving.
        fidNode.SetLocked(True)
        fidDisplayNode.SetGlyphScale(0.01)
        fidDisplayNode.SetSelectedColor(1.0, 1.0, 0.0)
        fidDisplayNode.SetTextScale(0.0)
        scene.AddNode(fidNode)
        fidNode.SetAndObserveDisplayNodeID(fidDisplayNode.GetID())
        # \TODO come up with better name later

        # prepare for arrows for upspokes
        upSpoke_points = vtk.vtkPoints()
        upSpoke_lines = vtk.vtkCellArray()

        arr_length = upPointData.GetArray('spokeLength')
        arr_dirs = upPointData.GetArray('spokeDirection')
        for i in range(upSpokes.GetNumberOfPoints()):
            pt = [0] * 3
            upSpokes.GetPoint(i, pt)
            # base point of up arrows
            id0 = upSpoke_points.InsertNextPoint(pt)

            # head of up arrows
            spoke_length = arr_length.GetValue(i)
            baseIdx = i * 3
            dirX = arr_dirs.GetValue(baseIdx)
            dirY = arr_dirs.GetValue(baseIdx + 1)
            dirZ = arr_dirs.GetValue(baseIdx + 2)
            pt1 = [0] * 3
            pt1[0] = pt[0] + spoke_length * dirX
            pt1[1] = pt[1] + spoke_length * dirY
            pt1[2] = pt[2] + spoke_length * dirZ
            id1 = upSpoke_points.InsertNextPoint(pt1)

            up_arrow = vtk.vtkLine()
            up_arrow.GetPointIds().SetId(0, id0)
            up_arrow.GetPointIds().SetId(1, id1)
            upSpoke_lines.InsertNextCell(up_arrow)

            fidNode.AddFiducial(pt[0], pt[1], pt[2])

        # boundary_point_ids = []

        # model node for medial mesh
        medial_model = slicer.vtkMRMLModelNode()
        medial_model.SetScene(scene)
        medial_model.SetName("Medial Mesh")
        medial_model.SetAndObservePolyData(reader.GetOutput())
        # model display node for the medial mesh
        medial_model_display = slicer.vtkMRMLModelDisplayNode()
        medial_model_display.SetColor(0, 0.5, 0)
        medial_model_display.SetScene(scene)
        medial_model_display.SetLineWidth(3.0)
        medial_model_display.SetRepresentation(1)
        medial_model_display.SetBackfaceCulling(0)
        scene.AddNode(medial_model_display)
        medial_model.SetAndObserveDisplayNodeID(medial_model_display.GetID())
        scene.AddNode(medial_model)

        # model node for up spoke (poly data for arrows)
        upSpoke_polyData = vtk.vtkPolyData()
        upSpoke_polyData.SetPoints(upSpoke_points)
        upSpoke_polyData.SetLines(upSpoke_lines)

        upSpoke_model = slicer.vtkMRMLModelNode()
        upSpoke_model.SetScene(scene)
        upSpoke_model.SetName("Top Spoke")
        upSpoke_model.SetAndObservePolyData(upSpoke_polyData)
        # model display node for the top spoke
        # cyan for the top spoke
        upSpoke_model_display = slicer.vtkMRMLModelDisplayNode()
        upSpoke_model_display.SetColor(0, 1, 1)
        upSpoke_model_display.SetScene(scene)
        upSpoke_model_display.SetLineWidth(3.0)
        upSpoke_model_display.SetBackfaceCulling(0)
        scene.AddNode(upSpoke_model_display)
        upSpoke_model.SetAndObserveDisplayNodeID(upSpoke_model_display.GetID())
        scene.AddNode(upSpoke_model)

        # prepare for down spokes
        reader.SetFileName(downFileName)
        reader.Update()
        downSpokes = reader.GetOutput()

        downSpoke_polyData = vtk.vtkPolyData()
        downSpoke_lines = vtk.vtkCellArray()
        downSpoke_points = vtk.vtkPoints()

        downPointData = downSpokes.GetPointData()
        arr_length = downPointData.GetArray('spokeLength')
        arr_dirs = downPointData.GetArray('spokeDirection')
        for i in range(downSpokes.GetNumberOfPoints()):
            # tail of arrows
            pt_tail = [0] * 3
            downSpokes.GetPoint(i, pt_tail)
            id0 = downSpoke_points.InsertNextPoint(pt_tail)

            # head of arrows
            pt_head = [0] * 3
            spoke_length = arr_length.GetValue(i)
            baseIdx = i * 3
            dirX = arr_dirs.GetValue(baseIdx)
            dirY = arr_dirs.GetValue(baseIdx + 1)
            dirZ = arr_dirs.GetValue(baseIdx + 2)
            pt_head[0] = pt_tail[0] + spoke_length * dirX
            pt_head[1] = pt_tail[1] + spoke_length * dirY
            pt_head[2] = pt_tail[2] + spoke_length * dirZ
            id1 = downSpoke_points.InsertNextPoint(pt_head)

            # connection between head and tail
            con = vtk.vtkLine()
            con.GetPointIds().SetId(0, id0)
            con.GetPointIds().SetId(1, id1)
            downSpoke_lines.InsertNextCell(con)

        downSpoke_polyData.SetPoints(downSpoke_points)
        downSpoke_polyData.SetLines(downSpoke_lines)

        downSpoke_model = slicer.vtkMRMLModelNode()
        downSpoke_model.SetScene(scene)
        downSpoke_model.SetName("Bottom Spoke")
        downSpoke_model.SetAndObservePolyData(downSpoke_polyData)
        # model display node for the down spoke
        downSpoke_model_display = slicer.vtkMRMLModelDisplayNode()
        downSpoke_model_display.SetColor(1, 0, 1)
        downSpoke_model_display.SetScene(scene)
        downSpoke_model_display.SetLineWidth(3.0)
        downSpoke_model_display.SetBackfaceCulling(0)
        scene.AddNode(downSpoke_model_display)
        downSpoke_model.SetAndObserveDisplayNodeID(
            downSpoke_model_display.GetID())
        scene.AddNode(downSpoke_model)

        # crest spoke
        new_reader = vtk.vtkXMLPolyDataReader()
        new_reader.SetFileName(crestFileName)
        new_reader.Update()
        foldCurve_polyData = new_reader.GetOutput()
        foldPointData = foldCurve_polyData.GetPointData()
        arr_length = foldPointData.GetArray('spokeLength')
        arr_dirs = foldPointData.GetArray('spokeDirection')
        crest_arrows_polydata = vtk.vtkPolyData()
        crest_arrows_points = vtk.vtkPoints()
        crest_arrows_lines = vtk.vtkCellArray()
        for i in range(foldCurve_polyData.GetNumberOfPoints()):
            # tail of crest arrows
            pt_tail = [0] * 3
            foldCurve_polyData.GetPoint(i, pt_tail)
            id0 = crest_arrows_points.InsertNextPoint(pt_tail)

            # head of crest arrows
            pt_head = [0] * 3
            spoke_length = arr_length.GetValue(i)
            baseIdx = i * 3
            dirX = arr_dirs.GetValue(baseIdx)
            dirY = arr_dirs.GetValue(baseIdx + 1)
            dirZ = arr_dirs.GetValue(baseIdx + 2)
            pt_head[0] = pt_tail[0] + spoke_length * dirX
            pt_head[1] = pt_tail[1] + spoke_length * dirY
            pt_head[2] = pt_tail[2] + spoke_length * dirZ
            id1 = crest_arrows_points.InsertNextPoint(pt_head)

            crest_line = vtk.vtkLine()
            crest_line.GetPointIds().SetId(0, id0)
            crest_line.GetPointIds().SetId(1, id1)
            crest_arrows_lines.InsertNextCell(crest_line)

        crest_arrows_polydata.SetPoints(crest_arrows_points)
        crest_arrows_polydata.SetLines(crest_arrows_lines)

        # show crest arrows
        crestSpoke_model = slicer.vtkMRMLModelNode()
        crestSpoke_model.SetScene(scene)
        crestSpoke_model.SetName("Crest Spoke")
        crestSpoke_model.SetAndObservePolyData(crest_arrows_polydata)
        # model display node
        crestSpoke_model_display = slicer.vtkMRMLModelDisplayNode()
        crestSpoke_model_display.SetColor(1, 1, 0)
        crestSpoke_model_display.SetScene(scene)
        crestSpoke_model_display.SetLineWidth(3.0)
        crestSpoke_model_display.SetBackfaceCulling(0)
        scene.AddNode(crestSpoke_model_display)
        crestSpoke_model.SetAndObserveDisplayNodeID(
            crestSpoke_model_display.GetID())
        scene.AddNode(crestSpoke_model)

        # show fold curve
        foldCurve_model = slicer.vtkMRMLModelNode()
        foldCurve_model.SetScene(scene)
        foldCurve_model.SetName("Fold Curve")
        foldCurve_model.SetAndObservePolyData(foldCurve_polyData)
        # model display node
        foldCurve_model_display = slicer.vtkMRMLModelDisplayNode()
        foldCurve_model_display.SetColor(1, 1, 0)
        foldCurve_model_display.SetScene(scene)
        foldCurve_model_display.SetLineWidth(3.0)
        foldCurve_model_display.SetBackfaceCulling(0)
        scene.AddNode(foldCurve_model_display)
        foldCurve_model.SetAndObserveDisplayNodeID(
            foldCurve_model_display.GetID())
        scene.AddNode(foldCurve_model)

        # show connections to fold curve point from nearby interior points
        # compute the nearest interior point
        connection_polydata = vtk.vtkPolyData()
        connection_points = vtk.vtkPoints()
        connection_lines = vtk.vtkCellArray()
        for i in range(foldCurve_polyData.GetNumberOfPoints()):
            min_dist = 100000.0
            nearest_index = 0
            pt_fold = [0] * 3
            foldCurve_polyData.GetPoint(i, pt_fold)
            id0 = connection_points.InsertNextPoint(pt_fold)

            for j in range(upSpokes.GetNumberOfPoints()):
                pt_interior = [0] * 3
                upSpokes.GetPoint(j, pt_interior)
                dist = self.distance(pt_fold, pt_interior)
                if dist < min_dist:
                    min_dist = dist
                    nearest_index = j

            pt_nearest_interior = upSpokes.GetPoint(nearest_index)
            id1 = connection_points.InsertNextPoint(pt_nearest_interior)
            line = vtk.vtkLine()

            line.GetPointIds().SetId(0, id0)
            line.GetPointIds().SetId(1, id1)

            connection_lines.InsertNextCell(line)

        connection_polydata.SetPoints(connection_points)
        connection_polydata.SetLines(connection_lines)
        connection_model = slicer.vtkMRMLModelNode()
        connection_model.SetScene(scene)
        connection_model.SetName("Connection to Fold Curve")
        connection_model.SetAndObservePolyData(connection_polydata)
        # model display node
        connection_model_display = slicer.vtkMRMLModelDisplayNode()
        connection_model_display.SetColor(0, 0, 0)
        connection_model_display.SetScene(scene)
        connection_model_display.SetLineWidth(3.0)
        connection_model_display.SetBackfaceCulling(0)
        scene.AddNode(connection_model_display)
        connection_model.SetAndObserveDisplayNodeID(
            connection_model_display.GetID())
        scene.AddNode(connection_model)
  def createCone(self):
    #f = slicer.util.getNode('Target')
    self.pos = [0,0,0]
    self.pos1 = [0,0,0]
    self.targetFiducial.GetNthFiducialPosition(0,self.pos)
    self.targetFiducial.GetNthFiducialPosition(1,self.pos1)

    # Create a vtkPoints object and store the points in it
    points = vtk.vtkPoints()
    points.InsertNextPoint(self.pos)

    points.InsertNextPoint(self.pos1)

    # Create line
    line = vtk.vtkLine()
    line.GetPointIds().SetId(0,0)
    line.GetPointIds().SetId(1,1)
    lineCellArray = vtk.vtkCellArray()
    lineCellArray.InsertNextCell(line)

    self.lineNode = slicer.vtkMRMLModelNode()
    self.lineNode.SetName('Line')
    linePolyData = vtk.vtkPolyData()
    self.lineNode.SetAndObservePolyData(linePolyData)
    modelDisplay = slicer.vtkMRMLModelDisplayNode()
    modelDisplay.SetSliceIntersectionVisibility(True)
    modelDisplay.SetColor(0,0,1)
    slicer.mrmlScene.AddNode(modelDisplay)

    self.lineNode.SetAndObserveDisplayNodeID(modelDisplay.GetID())
    slicer.mrmlScene.AddNode(self.lineNode)

    self.lineNode.GetPolyData().SetPoints(points)
    self.lineNode.GetPolyData().SetLines(lineCellArray)
    self.cone = vtk.vtkConeSource()
    self.cone = vtk.vtkConeSource()
    self.cone.SetResolution(50)

    self.cone.SetRadius(20)

    vector = np.subtract(self.pos,self.pos1)
    self.cone.SetDirection([vector[0],vector[1],vector[2]])
    dist = np.linalg.norm(vector)
    self.cone.SetHeight(dist)

    self.coneModel = slicer.vtkMRMLModelNode()
    self.coneModel.SetName('Cone')

    self.coneModel.SetPolyDataConnection(self.cone.GetOutputPort())
    slicer.mrmlScene.AddNode(self.coneModel)

    modelDisplay1 = slicer.vtkMRMLModelDisplayNode()
    modelDisplay1.SetSliceIntersectionVisibility(True)
    modelDisplay1.SetColor(0,1,1)
    modelDisplay1.SetOpacity(0.30)
    slicer.mrmlScene.AddNode(modelDisplay1)

    self.coneModel.SetAndObserveDisplayNodeID(modelDisplay1.GetID())
    slicer.mrmlScene.AddNode(self.coneModel)

    x3 = [(self.pos1[0]-self.pos[0])/2 + self.pos[0], (self.pos1[1]-self.pos[1])/2 +self.pos[1], (self.pos1[2]-self.pos[2])/2 +self.pos[2]]
    self.cone.SetCenter(x3)
示例#44
0
 def setAndObserveDisplayNode(node):
   displayNode = slicer.vtkMRMLModelDisplayNode()
   slicer.mrmlScene.AddNode(displayNode)
   node.SetAndObserveDisplayNodeID(displayNode.GetID())
   return displayNode
示例#45
0
    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)
        print(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")