Exemplo n.º 1
0
    def createNewModelNode(self, polyData, nodeName):
        modelNode = slicer.mrmlScene.AddNode(slicer.vtkMRMLModelNode())
        modelNode.SetName(nodeName)
        modelNode.CreateDefaultDisplayNodes()
        modelNode.SetAndObservePolyData(polyData)

        return modelNode
Exemplo n.º 2
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
    def onApply(self):
        # Allow users revert to this state by clicking Undo
        self.scriptedEffect.saveStateForUndo()

        inputVolume = self.scriptedEffect.parameterSetNode(
        ).GetMasterVolumeNode()
        outputVolume = self.outputVolumeSelector.currentNode()
        maskOutsideSurface = self.maskOutsideSurfaceCheckBox.checked
        fillValue = self.fillValueEdit.value

        segmentID = self.scriptedEffect.parameterSetNode(
        ).GetSelectedSegmentID()
        segmentationNode = self.scriptedEffect.parameterSetNode(
        ).GetSegmentationNode()
        maskingModel = slicer.vtkMRMLModelNode()
        outputPolyData = vtk.vtkPolyData()
        slicer.vtkSlicerSegmentationsModuleLogic.GetSegmentClosedSurfaceRepresentation(
            segmentationNode, segmentID, outputPolyData)
        maskingModel.SetAndObservePolyData(outputPolyData)

        self.maskVolumeWithSegment(inputVolume, maskingModel,
                                   maskOutsideSurface, fillValue, outputVolume)
        qt.QApplication.restoreOverrideCursor()

        #De-select effect
        self.scriptedEffect.selectEffect("")
Exemplo n.º 4
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
Exemplo n.º 5
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
  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
Exemplo n.º 7
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
Exemplo n.º 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)
Exemplo n.º 9
0
    def createNeedleModel(self, toolname):

        modelNode = slicer.vtkMRMLModelNode()
        # create needle model module logic
        createModelLogic = slicer.modules.createmodels.logic()
        #modelDisplayNode = slicer.vtkMRMLModelDisplayNode()
        #modelDisplayNode.SetName(modelNode.GetName())

        # create a RFA probe needle
        if 'RFAProbe' in toolname:
            modelNode = createModelLogic.CreateNeedle(150, True, 0, 1)
            modelNode.SetName(toolname)
            modelDisplayNode = modelNode.GetDisplayNode()
            modelDisplayNode.SetColor([0, 0, 1])  # Blue
        # slicer.mrmlScene.AddNode(modelDisplayNode)
        # modelNode.SetAndObserveDisplayNodeID(modelDisplayNode.GetID())

        elif 'Introducer' in toolname:
            modelNode = createModelLogic.CreateNeedle(100, True, 0, 1)
            modelNode.SetName(toolname)
            modelDisplayNode = modelNode.GetDisplayNode()
            modelDisplayNode.SetColor([1, 0, 0])  # Red
        # slicer.mrmlScene.AddNode(modelDisplayNode)
        # modelNode.SetAndObserveDisplayNodeID(modelDisplayNode.GetID())

        else:
            modelNode = createModelLogic.CreateNeedle(100, True, 1, 1)
            modelNode.SetName(toolname)
            modelDisplayNode = modelNode.GetDisplayNode()
            modelDisplayNode.SetColor([0, 1, 0])

        return modelNode
Exemplo n.º 10
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
Exemplo n.º 11
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)
Exemplo n.º 12
0
    def onEdit(self):
        # Create empty model node
        if self.segmentModel is None:
            self.segmentModel = slicer.vtkMRMLModelNode()
            slicer.mrmlScene.AddNode(self.segmentModel)

        segmentID = self.scriptedEffect.parameterSetNode(
        ).GetSelectedSegmentID()
        segmentationNode = self.scriptedEffect.parameterSetNode(
        ).GetSegmentationNode()
        segment = segmentationNode.GetSegmentation().GetSegment(segmentID)

        fPosStr = vtk.mutable("")
        segment.GetTag("DrawTubeEffectMarkupPositions", fPosStr)
        # convert from space-separated list o fnumbers to 1D array
        import numpy
        fPos = numpy.fromstring(str(fPosStr), sep=' ')
        # convert from 1D array (N*3) to 2D array (N,3)
        fPosNum = int(len(fPos) / 3)
        fPos = fPos.reshape((fPosNum, 3))
        for i in xrange(fPosNum):
            self.segmentMarkupNode.AddFiducialFromArray(fPos[i])

        self.editButton.setEnabled(False)
        self.updateModelFromSegmentMarkupNode()
 def tree2Model(self, tree, model=None):
     # convert the tree structure a vtkMRMLModelNode
     if model is None:
         model = slicer.vtkMRMLModelNode()
         model.SetName('Tree')
     mesh = self.tree2Mesh(tree)
     model.SetAndObserveMesh(mesh)
     return model
Exemplo n.º 14
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
Exemplo n.º 15
0
 def placeFiducials(self):
   self.clippingModelNode = slicer.vtkMRMLModelNode()
   self.clippingModelNode.SetName('clipModelNode')
   slicer.mrmlScene.AddNode(self.clippingModelNode)
   self.createAndConfigureClippingModelDisplayNode()
   self.createMarkupsFiducialNode()
   self.inputMarkupNode.AddObserver(vtk.vtkCommand.ModifiedEvent, self.updateModel)
   volumeClipPointsDisplayNode = self.setupDisplayNode()
   self.inputMarkupNode.SetAndObserveDisplayNodeID(volumeClipPointsDisplayNode.GetID())
Exemplo n.º 16
0
    def test_Segmentation(self):
        """ Test the GetRASBounds & GetBounds method on a segmentation.
    """
        #self.delayDisplay("Starting test_Segmentation")
        cubeSource = vtk.vtkCubeSource()
        cubeSource.SetXLength(500)
        cubeSource.SetYLength(200)
        cubeSource.SetZLength(300)
        cubeSource.SetCenter(10, -85, 0.7)

        rotation = vtk.vtkTransform()
        rotation.RotateX(15.0)
        rotation.RotateZ(78)

        applyTransform = vtk.vtkTransformPolyDataFilter()
        applyTransform.SetTransform(rotation)
        applyTransform.SetInputConnection(cubeSource.GetOutputPort())
        applyTransform.Update()

        modelNode = slicer.mrmlScene.AddNode(slicer.vtkMRMLModelNode())
        modelNode.SetPolyDataConnection(applyTransform.GetOutputPort())

        segmentationNode = slicer.mrmlScene.AddNewNodeByClass(
            "vtkMRMLSegmentationNode")
        segmentationLogic = slicer.modules.segmentations.logic()
        segmentationLogic.ImportModelToSegmentationNode(
            modelNode, segmentationNode)

        # Testing
        bounds = list(range(6))
        segmentationNode.GetRASBounds(bounds)
        untransformedBounds = [
            -65.41641522206768, 237.23434621664228, -303.75878430165756,
            289.7072339384945, -217.463212035832, 213.6873140360733
        ]
        self.assertListAlmostEquals(bounds, untransformedBounds)

        segmentationNode.GetBounds(bounds)
        self.assertListAlmostEquals(bounds, untransformedBounds)

        transform = vtk.vtkTransform()
        transform.Translate([-5.0, +42.0, -0.1])
        transform.RotateWXYZ(41, 0.7, 0.6, 75)
        transform.Scale(2, 3, 10)
        transformNode = slicer.mrmlScene.AddNode(slicer.vtkMRMLTransformNode())
        transformNode.ApplyTransform(transform)

        segmentationNode.SetAndObserveTransformNodeID(transformNode.GetID())
        transformedBounds = [
            -690.2701685073093, 966.991271911892, -740.4842166018336,
            1018.2608117218165, -2183.4229718546612, 2144.1077463008546
        ]
        segmentationNode.GetRASBounds(bounds)
        self.assertListAlmostEquals(bounds, transformedBounds)

        segmentationNode.GetBounds(bounds)
        self.assertListAlmostEquals(bounds, untransformedBounds)
Exemplo n.º 17
0
    def test_Segmentation(self):
        """ Test the GetRASBounds & GetBounds method on a segmentation.
    """
        #self.delayDisplay("Starting test_Segmentation")
        cubeSource = vtk.vtkCubeSource()
        cubeSource.SetXLength(500)
        cubeSource.SetYLength(200)
        cubeSource.SetZLength(300)
        cubeSource.SetCenter(10, -85, 0.7)

        rotation = vtk.vtkTransform()
        rotation.RotateX(15.0)
        rotation.RotateZ(78)

        applyTransform = vtk.vtkTransformPolyDataFilter()
        applyTransform.SetTransform(rotation)
        applyTransform.SetInputConnection(cubeSource.GetOutputPort())
        applyTransform.Update()

        modelNode = slicer.mrmlScene.AddNode(slicer.vtkMRMLModelNode())
        modelNode.SetPolyDataConnection(applyTransform.GetOutputPort())

        segmentationNode = slicer.mrmlScene.AddNewNodeByClass(
            "vtkMRMLSegmentationNode")
        segmentationLogic = slicer.modules.segmentations.logic()
        segmentationLogic.ImportModelToSegmentationNode(
            modelNode, segmentationNode)

        # Testing
        bounds = range(6)
        segmentationNode.GetRASBounds(bounds)
        untransformedBounds = [
            -65.4164152220677, 237.23434621664234, -305.4495706784099,
            289.7072339384947, -217.46321203583187, 213.68731403607347
        ]
        self.assertListAlmostEquals(bounds, untransformedBounds)

        segmentationNode.GetBounds(bounds)
        self.assertListAlmostEquals(bounds, untransformedBounds)

        transform = vtk.vtkTransform()
        transform.Translate([-5.0, +42.0, -0.1])
        transform.RotateWXYZ(41, 0.7, 0.6, 75)
        transform.Scale(2, 3, 10)
        transformNode = slicer.mrmlScene.AddNode(slicer.vtkMRMLTransformNode())
        transformNode.ApplyTransform(transform)

        segmentationNode.SetAndObserveTransformNodeID(transformNode.GetID())
        transformedBounds = [
            -690.2701685073098, 970.3186946284741, -744.3124542486084,
            1018.260811721817, -2183.4639807718822, 2144.107746300856
        ]
        segmentationNode.GetRASBounds(bounds)
        self.assertListAlmostEquals(bounds, transformedBounds)

        segmentationNode.GetBounds(bounds)
        self.assertListAlmostEquals(bounds, untransformedBounds)
Exemplo n.º 18
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)
Exemplo n.º 19
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)
Exemplo n.º 20
0
 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
 def tube2Model(self, tube, model=None):
     # convert a single tubular structure to a vtkMRMLModelNode
     if model is None:
         model = slicer.vtkMRMLModelNode()
         name = 'Segment ' + str(
             tube['ID']) + (' - ' + tube['Name'] if 'Name' in tube else '')
         model.SetName(name)
     mesh = self.tube2CylinderMesh(tube)
     model.SetAndObserveMesh(mesh)
     return model
Exemplo n.º 22
0
 def createTrajectoryModel(self):
     createModelLogic = slicer.modules.createmodels.logic()
     trajectoryModelNode = slicer.vtkMRMLModelNode()
     trajectoryModelNode = createModelLogic.CreateCylinder(100, 0.05)
     probeModelDisplayNode = trajectoryModelNode.GetDisplayNode()
     probeModelDisplayNode.SetColor([1, 0, 0])
     probeModelDisplayNode.SetOpacity(0.5)
     probeModelDisplayNode.SetSliceIntersectionVisibility(1)
     slicer.mrmlScene.AddNode(trajectoryModelNode)
     self.trajectoryModelNode = trajectoryModelNode
     return trajectoryModelNode
Exemplo n.º 23
0
    def onFiducialPlacementToggleChanged(self):
        if self.fiducialPlacementToggle.placeButton().isChecked():
            # Create empty model node
            if self.segmentModel is None:
                self.segmentModel = slicer.vtkMRMLModelNode()
                slicer.mrmlScene.AddNode(self.segmentModel)

            # Create empty markup fiducial node
            if self.segmentMarkupNode is None:
                self.createNewMarkupNode()
                self.fiducialPlacementToggle.setCurrentNode(
                    self.segmentMarkupNode)
Exemplo n.º 24
0
    def getSourceTargetFromDrawing(self):
        # get smplae distance
        sampleDistance = float(
            self.parameterNode.GetParameter("DrawSampleDistance"))

        # create curve from drawing and resample
        sourceCurve = slicer.mrmlScene.AddNewNodeByClass(
            'vtkMRMLMarkupsCurveNode')
        sourceCurve.GetDisplayNode().SetSelectedColor(1, 1, 0)
        sourceCurve.SetControlPointPositionsWorld(self.rasPoints)
        sourceCurve.ResampleCurveWorld(sampleDistance)
        self.auxNodes.append(sourceCurve)

        # get resampled points
        resampledPoints = vtk.vtkPoints()
        sourceCurve.GetControlPointPositionsWorld(resampledPoints)
        if resampledPoints.GetNumberOfPoints() <= 1:
            return (None, ) * 3

        # get closest model sliced
        slicedModel, originalModel = self.sliceClosestModel(
            resampledPoints.GetPoint(0))

        if not slicedModel:
            return (None, ) * 3

        self.auxNodes.append(slicedModel)

        # resample sourceCurve in sliced model with same amount of points
        targetCurve = slicer.mrmlScene.AddNewNodeByClass(
            'vtkMRMLMarkupsCurveNode')
        targetCurve.GetDisplayNode().SetVisibility(0)
        targetCurve.SetControlPointPositionsWorld(resampledPoints)
        targetCurve.SetCurveTypeToShortestDistanceOnSurface(slicedModel)
        targetCurve.ResampleCurveSurface(
            sampleDistance,
            slicer.vtkMRMLModelNode().SafeDownCast(slicedModel), 0.0025)
        targetCurve.ResampleCurveWorld(targetCurve.GetCurveLengthWorld() / max(
            (sourceCurve.GetNumberOfControlPoints() - 1), 1))
        self.auxNodes.append(targetCurve)

        # curve to fiducial
        sourceFiducial = self.curveToFiducial(sourceCurve)
        targetFiducial = self.curveToFiducial(targetCurve)

        # set name
        shNode = slicer.mrmlScene.GetSubjectHierarchyNode()
        modelParentName = shNode.GetItemName(
            shNode.GetItemParent(shNode.GetItemByDataNode(originalModel)))
        targetFiducial.SetName(modelParentName + '_' + originalModel.GetName())

        return sourceFiducial, targetFiducial, sourceCurve
Exemplo n.º 25
0
    def test_Model(self):
        """ Test the GetRASBounds & GetBounds method on a model.
    """
        #self.delayDisplay("Starting test_Model")
        # Setup
        cubeSource = vtk.vtkCubeSource()
        cubeSource.SetXLength(500)
        cubeSource.SetYLength(200)
        cubeSource.SetZLength(300)
        cubeSource.SetCenter(10, -85, 0.7)

        rotation = vtk.vtkTransform()
        rotation.RotateX(15.0)
        rotation.RotateZ(78)

        applyTransform = vtk.vtkTransformPolyDataFilter()
        applyTransform.SetTransform(rotation)
        applyTransform.SetInputConnection(cubeSource.GetOutputPort())
        applyTransform.Update()

        modelNode = slicer.mrmlScene.AddNode(slicer.vtkMRMLModelNode())
        modelNode.SetPolyDataConnection(applyTransform.GetOutputPort())

        # Testing
        bounds = range(6)
        modelNode.GetRASBounds(bounds)
        untransformedBounds = [
            -64.5710220336914, 235.01434326171875, -302.91339111328125,
            287.3067932128906, -214.92703247070312, 212.1946258544922
        ]
        self.assertListAlmostEquals(bounds, untransformedBounds)

        modelNode.GetBounds(bounds)
        self.assertListAlmostEquals(bounds, untransformedBounds)

        transform = vtk.vtkTransform()
        transform.Translate([-5.0, +42.0, -0.1])
        transform.RotateWXYZ(41, 0.7, 0.6, 75)
        transform.Scale(2, 3, 10)
        transformNode = slicer.mrmlScene.AddNode(slicer.vtkMRMLTransformNode())
        transformNode.ApplyTransform(transform)

        modelNode.SetAndObserveTransformNodeID(transformNode.GetID())
        transformedBounds = [
            -684.0789214975257, 961.8640451930095, -737.3987882515103,
            1009.8075011032414, -2158.028473491281, 2129.118193451847
        ]
        modelNode.GetRASBounds(bounds)
        self.assertListAlmostEquals(bounds, transformedBounds)

        modelNode.GetBounds(bounds)
        self.assertListAlmostEquals(bounds, untransformedBounds)
 def measurementsTable2Model(self, tableNode, model=None):
     # convert a measurements table to a mesh a vtkMRMLModelNode
     if model is None:
         model = slicer.vtkMRMLModelNode()
         model.SetName('Measurements')
     if self.getType(tableNode) == 'tree':
         mesh = self.treeTable2Mesh(tableNode)
     elif self.getType(tableNode) == 'areaMeasurements':
         mesh = self.areaMeasurementsTable2Mesh(tableNode)
     else:
         mesh = self.volumeMeasurementsTable2Mesh(tableNode)
     model.SetAndObserveMesh(mesh)
     return model
    def OnSmoothLabelMapButtonClicked(self):
        # Get working polydata
        WorkingNodeName = self.WorkingLabelMapStorage.currentNode().GetName()
        if self.SegmentationNode.GetClosedSurfaceRepresentation(
                WorkingNodeName) == None:
            self.SegmentationNode.CreateClosedSurfaceRepresentation()

        WorkingPolyData = self.SegmentationNode.GetClosedSurfaceRepresentation(
            WorkingNodeName)

        # Smooth working polydata
        logic = UsSurfaceToLandmarksLogic()
        SmoothedPolyData = logic.SmoothPolyData(
            WorkingPolyData, self.SmoothingConvergenceSlider.value,
            self.SmoothingIterationsSlider.value)

        # Convert polydata to labelmap via segmentation and vtkmodel
        SmoothedModelNode = slicer.vtkMRMLModelNode()
        SmoothedModelNode.SetName(WorkingNodeName)
        SmoothedModelNode.SetAndObservePolyData(SmoothedPolyData)
        #SmoothedModelNode

        ConvSeg = slicer.vtkMRMLSegmentationNode()
        ConvSeg.SetScene(slicer.mrmlScene)
        SegLogic = slicer.modules.segmentations.logic()
        SegLogic.ImportModelToSegmentationNode(SmoothedModelNode, ConvSeg)
        ConvSeg.CreateBinaryLabelmapRepresentation()
        ConvSeg.SetMasterRepresentationToBinaryLabelmap()

        # Clear mrmlScene of old labelmap node before exporting the new one
        #OldLabelMapNode = self.WorkingLabelMapStorage.currentNode()
        #OldLabelMapNode = slicer.util.getNode(WorkingNodeName)
        #if OldLabelMapNode != None:
        #  slicer.mrmlScene.RemoveNode(OldLabelMapNode)

        # Export segmentation label map representation to mrml node for storage in interface
        SmoothedLabelMapNode = slicer.vtkMRMLLabelMapVolumeNode()
        SmoothedLabelMapNode.SetName(WorkingNodeName + self.SmoothTag)

        LabelMapName = vtk.vtkStringArray()
        LabelMapName.InsertNextValue(WorkingNodeName)
        slicer.mrmlScene.AddNode(SmoothedLabelMapNode)
        SegLogic.ExportSegmentsToLabelmapNode(ConvSeg, LabelMapName,
                                              SmoothedLabelMapNode)
        #SmoothedLabelMapNode.SetOrigin(self.InputVolumeSelector.currentNode().GetOrigin())
        # Update working polydata in UI
        # Add new smoothed label map node to mrmlScene
        self.WorkingLabelMapStorage.setCurrentNode(SmoothedLabelMapNode)
        self.UpdateSegmentationNode()

        return True
Exemplo n.º 28
0
  def test_Segmentation(self):
    """ Test the GetRASBounds & GetBounds method on a segmentation.
    """
    #self.delayDisplay("Starting test_Segmentation")
    cubeSource = vtk.vtkCubeSource()
    cubeSource.SetXLength(500)
    cubeSource.SetYLength(200)
    cubeSource.SetZLength(300)
    cubeSource.SetCenter(10, -85, 0.7)

    rotation = vtk.vtkTransform()
    rotation.RotateX(15.0)
    rotation.RotateZ(78)

    applyTransform = vtk.vtkTransformPolyDataFilter()
    applyTransform.SetTransform(rotation)
    applyTransform.SetInputConnection(cubeSource.GetOutputPort())
    applyTransform.Update()

    modelNode = slicer.mrmlScene.AddNode(slicer.vtkMRMLModelNode())
    modelNode.SetPolyDataConnection(applyTransform.GetOutputPort())

    segmentationNode = slicer.mrmlScene.AddNode(slicer.vtkMRMLSegmentationNode())
    segmentationLogic = slicer.modules.segmentations.logic()
    segmentationLogic.ImportModelToSegmentationNode(modelNode, segmentationNode)

    # Testing
    bounds = range(6)
    segmentationNode.GetRASBounds(bounds)
    untransformedBounds = [-65.4164152220677, 237.23434621664234, -305.4495706784099, 289.7072339384947, -217.46321203583187, 213.68731403607347]
    self.assertListAlmostEquals(bounds, untransformedBounds)

    segmentationNode.GetBounds(bounds)
    self.assertListAlmostEquals(bounds, untransformedBounds)

    transform = vtk.vtkTransform()
    transform.Translate([-5.0, +42.0, -0.1])
    transform.RotateWXYZ(41, 0.7, 0.6, 75)
    transform.Scale(2, 3, 10)
    transformNode = slicer.mrmlScene.AddNode(slicer.vtkMRMLTransformNode())
    transformNode.ApplyTransform(transform)

    segmentationNode.SetAndObserveTransformNodeID(transformNode.GetID())
    transformedBounds = [-690.2701685073098, 970.3186946284741, -744.3124542486084, 1018.260811721817, -2183.4639807718822, 2144.107746300856]
    segmentationNode.GetRASBounds(bounds)
    self.assertListAlmostEquals(bounds, transformedBounds)

    segmentationNode.GetBounds(bounds)
    self.assertListAlmostEquals(bounds, untransformedBounds)
Exemplo n.º 29
0
  def test_Segmentation(self):
    """ Test the GetRASBounds & GetBounds method on a segmentation.
    """
    #self.delayDisplay("Starting test_Segmentation")
    cubeSource = vtk.vtkCubeSource()
    cubeSource.SetXLength(500)
    cubeSource.SetYLength(200)
    cubeSource.SetZLength(300)
    cubeSource.SetCenter(10, -85, 0.7)

    rotation = vtk.vtkTransform()
    rotation.RotateX(15.0)
    rotation.RotateZ(78)

    applyTransform = vtk.vtkTransformPolyDataFilter()
    applyTransform.SetTransform(rotation)
    applyTransform.SetInputConnection(cubeSource.GetOutputPort())
    applyTransform.Update()

    modelNode = slicer.mrmlScene.AddNode(slicer.vtkMRMLModelNode())
    modelNode.SetPolyDataConnection(applyTransform.GetOutputPort())

    segmentationNode = slicer.mrmlScene.AddNode(slicer.vtkMRMLSegmentationNode())
    segmentationLogic = slicer.modules.segmentations.logic()
    segmentationLogic.ImportModelToSegmentationNode(modelNode, segmentationNode)

    # Testing
    bounds = range(6)
    segmentationNode.GetRASBounds(bounds)
    untransformedBounds = [-65.0710220336914, 235.9289779663086, -304.413391113281, 288.586608886719, -216.427032470703, 213.572967529297]
    self.assertListAlmostEquals(bounds, untransformedBounds)

    segmentationNode.GetBounds(bounds)
    self.assertListAlmostEquals(bounds, untransformedBounds)

    transform = vtk.vtkTransform()
    transform.Translate([-5.0, +42.0, -0.1])
    transform.RotateWXYZ(41, 0.7, 0.6, 75)
    transform.Scale(2, 3, 10)
    transformNode = slicer.mrmlScene.AddNode(slicer.vtkMRMLTransformNode())
    transformNode.ApplyTransform(transform)

    segmentationNode.SetAndObserveTransformNodeID(transformNode.GetID())
    transformedBounds = [-687.4653523284665, 966.3004987004498, -741.50842882335, 1013.9676912857693, -2173.06971199151, 2142.935099515583]
    segmentationNode.GetRASBounds(bounds)
    self.assertListAlmostEquals(bounds, transformedBounds)

    segmentationNode.GetBounds(bounds)
    self.assertListAlmostEquals(bounds, untransformedBounds)
Exemplo n.º 30
0
  def test_Segmentation(self):
    """ Test the GetRASBounds & GetBounds method on a segmentation.
    """
    #self.delayDisplay("Starting test_Segmentation")
    cubeSource = vtk.vtkCubeSource()
    cubeSource.SetXLength(500)
    cubeSource.SetYLength(200)
    cubeSource.SetZLength(300)
    cubeSource.SetCenter(10, -85, 0.7)

    rotation = vtk.vtkTransform()
    rotation.RotateX(15.0)
    rotation.RotateZ(78)

    applyTransform = vtk.vtkTransformPolyDataFilter()
    applyTransform.SetTransform(rotation)
    applyTransform.SetInputConnection(cubeSource.GetOutputPort())
    applyTransform.Update()

    modelNode = slicer.mrmlScene.AddNode(slicer.vtkMRMLModelNode())
    modelNode.SetPolyDataConnection(applyTransform.GetOutputPort())

    segmentationNode = slicer.mrmlScene.AddNode(slicer.vtkMRMLSegmentationNode())
    segmentationLogic = slicer.modules.segmentations.logic()
    segmentationLogic.ImportModelToSegmentationNode(modelNode, segmentationNode)

    # Testing
    bounds = range(6)
    segmentationNode.GetRASBounds(bounds)
    untransformedBounds = [-65.0710220336914, 235.9289779663086, -304.413391113281, 288.586608886719, -216.427032470703, 213.572967529297]
    self.assertListAlmostEquals(bounds, untransformedBounds)

    segmentationNode.GetBounds(bounds)
    self.assertListAlmostEquals(bounds, untransformedBounds)

    transform = vtk.vtkTransform()
    transform.Translate([-5.0, +42.0, -0.1])
    transform.RotateWXYZ(41, 0.7, 0.6, 75)
    transform.Scale(2, 3, 10)
    transformNode = slicer.mrmlScene.AddNode(slicer.vtkMRMLTransformNode())
    transformNode.ApplyTransform(transform)

    segmentationNode.SetAndObserveTransformNodeID(transformNode.GetID())
    transformedBounds = [-200.70776329131795, 479.54290966330126, -723.6172978253361, 996.0765602877555, -2171.2883672792996, 2141.1537548033725]
    segmentationNode.GetRASBounds(bounds)
    self.assertListAlmostEquals(bounds, transformedBounds)

    segmentationNode.GetBounds(bounds)
    self.assertListAlmostEquals(bounds, untransformedBounds)
Exemplo n.º 31
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
Exemplo n.º 32
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)
Exemplo n.º 33
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())
Exemplo n.º 34
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()
Exemplo n.º 35
0
  def test_Model(self):
    """ Test the GetRASBounds & GetBounds method on a model.
    """
    #self.delayDisplay("Starting test_Model")
    # Setup
    cubeSource = vtk.vtkCubeSource()
    cubeSource.SetXLength(500)
    cubeSource.SetYLength(200)
    cubeSource.SetZLength(300)
    cubeSource.SetCenter(10, -85, 0.7)

    rotation = vtk.vtkTransform()
    rotation.RotateX(15.0)
    rotation.RotateZ(78)

    applyTransform = vtk.vtkTransformPolyDataFilter()
    applyTransform.SetTransform(rotation)
    applyTransform.SetInputConnection(cubeSource.GetOutputPort())
    applyTransform.Update()

    modelNode = slicer.mrmlScene.AddNode(slicer.vtkMRMLModelNode())
    modelNode.SetPolyDataConnection(applyTransform.GetOutputPort())

    # Testing
    bounds = range(6)
    modelNode.GetRASBounds(bounds)
    untransformedBounds = [-64.5710220336914, 235.01434326171875, -302.91339111328125, 287.3067932128906, -214.92703247070312, 212.1946258544922]
    self.assertListAlmostEquals(bounds, untransformedBounds)

    modelNode.GetBounds(bounds)
    self.assertListAlmostEquals(bounds, untransformedBounds)

    transform = vtk.vtkTransform()
    transform.Translate([-5.0, +42.0, -0.1])
    transform.RotateWXYZ(41, 0.7, 0.6, 75)
    transform.Scale(2, 3, 10)
    transformNode = slicer.mrmlScene.AddNode(slicer.vtkMRMLTransformNode())
    transformNode.ApplyTransform(transform)

    modelNode.SetAndObserveTransformNodeID(transformNode.GetID())
    transformedBounds = [-684.0789214975257, 961.8640451930095, -737.3987882515103, 1009.8075011032414, -2158.028473491281, 2129.118193451847]
    modelNode.GetRASBounds(bounds)
    self.assertListAlmostEquals(bounds, transformedBounds)

    modelNode.GetBounds(bounds)
    self.assertListAlmostEquals(bounds, untransformedBounds)
 def createIntermediateHardenModel(self, model):
     hardenModel = slicer.mrmlScene.GetNodesByName("SurfaceRegistration_" + model.GetName() + "_hardenCopy_" + str(
         slicer.app.applicationPid())).GetItemAsObject(0)
     if hardenModel is None:
         hardenModel = slicer.vtkMRMLModelNode()
     hardenPolyData = vtk.vtkPolyData()
     hardenPolyData.DeepCopy(model.GetPolyData())
     hardenModel.SetAndObservePolyData(hardenPolyData)
     hardenModel.SetName(
         "SurfaceRegistration_" + model.GetName() + "_hardenCopy_" + str(slicer.app.applicationPid()))
     if model.GetParentTransformNode():
         hardenModel.SetAndObserveTransformNodeID(model.GetParentTransformNode().GetID())
     hardenModel.HideFromEditorsOn()
     slicer.mrmlScene.AddNode(hardenModel)
     logic = slicer.vtkSlicerTransformLogic()
     logic.hardenTransform(hardenModel)
     return hardenModel
Exemplo n.º 37
0
    def drawSphere(self, centerOfSphere, radiusOfSphere):

        s = vtk.vtkSphereSource()
        s.SetRadius(radiusOfSphere)
        s.SetCenter(centerOfSphere[0], centerOfSphere[1], centerOfSphere[2])
        s.SetPhiResolution(36)
        s.SetThetaResolution(36)

        s.Update()

        m = slicer.vtkMRMLModelNode()
        slicer.mrmlScene.AddNode(m)
        m.CreateDefaultDisplayNodes()
        #m = self.setup.outputSelector
        m.GetDisplayNode().SetSliceIntersectionVisibility(True)
        m.GetDisplayNode().SetColor(1, 0, 0)

        m.SetAndObservePolyData(s.GetOutput())
Exemplo n.º 38
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
 def createIntermediateHardenModel(self, model):
     hardenModel = slicer.mrmlScene.GetNodesByName(
         "SurfaceRegistration_" + model.GetName() + "_hardenCopy_" +
         str(slicer.app.applicationPid())).GetItemAsObject(0)
     if hardenModel is None:
         hardenModel = slicer.vtkMRMLModelNode()
     hardenPolyData = vtk.vtkPolyData()
     hardenPolyData.DeepCopy(model.GetPolyData())
     hardenModel.SetAndObservePolyData(hardenPolyData)
     hardenModel.SetName("SurfaceRegistration_" + model.GetName() +
                         "_hardenCopy_" + str(slicer.app.applicationPid()))
     if model.GetParentTransformNode():
         hardenModel.SetAndObserveTransformNodeID(
             model.GetParentTransformNode().GetID())
     hardenModel.HideFromEditorsOn()
     slicer.mrmlScene.AddNode(hardenModel)
     logic = slicer.vtkSlicerTransformLogic()
     logic.hardenTransform(hardenModel)
     return hardenModel
Exemplo n.º 40
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)
    def OnDecimateLabelMapButtonClicked(self):
        # Get working polydata
        WorkingNodeName = self.WorkingLabelMapStorage.currentNode().GetName()
        if self.SegmentationNode.GetClosedSurfaceRepresentation(
                WorkingNodeName) == None:
            self.SegmentationNode.CreateClosedSurfaceRepresentation()
        WorkingPolyData = self.SegmentationNode.GetClosedSurfaceRepresentation(
            WorkingNodeName)

        # Decimate working polydata
        logic = UsSurfaceToLandmarksLogic()
        DecimatedPolyData = logic.DecimatePolyData(WorkingPolyData)

        # Convert polydata to labelmap via segmentation and vtkmodel
        DecimatedModelNode = slicer.vtkMRMLModelNode()
        DecimatedModelNode.SetName(WorkingNodeName)
        DecimatedModelNode.SetAndObservePolyData(DecimatedPolyData)

        ConvSeg = slicer.vtkMRMLSegmentationNode()
        ConvSeg.SetScene(slicer.mrmlScene)
        SegLogic = slicer.modules.segmentations.logic()
        SegLogic.ImportModelToSegmentationNode(DecimatedModelNode, ConvSeg)
        ConvSeg.CreateBinaryLabelmapRepresentation()
        ConvSeg.SetMasterRepresentationToBinaryLabelmap()

        LabelMapName = vtk.vtkStringArray()
        LabelMapName.InsertNextValue(WorkingNodeName)

        DecimatedLabelMapNode = slicer.vtkMRMLLabelMapVolumeNode()
        DecimatedLabelMapNode.SetName(WorkingNodeName)
        slicer.mrmlScene.AddNode(DecimatedLabelMapNode)

        SegLogic.ExportSegmentsToLabelmapNode(ConvSeg, LabelMapName,
                                              DecimatedLabelMapNode)
        #SmoothedOrientedImageData = ConvSeg.GetBinaryLabelmapRepresentation(WorkingNodeName)
        #DecimatedLabelMapNode.SetAndObserveImageData(SmoothedOrientedImageData)
        # Update working polydata in UI
        self.WorkingLabelMapStorage.setCurrentNode(DecimatedLabelMapNode)
        self.UpdateSegmentationNode()

        return True
Exemplo n.º 42
0
    def onShowPathButton(self):
        print 'Reconstructing retractor trajectory ...'
        fidNode = slicer.util.getNode('MarkupsFiducial_*')
        if fidNode == None:
            slicer.util.CreateNodeByClass('vtkMRMLMarkupsFiducialNode')
            fidNode = slicer.util.getNode('MarkupsFiducial_*')
        outputModel = slicer.mrmlScene.AddNode(slicer.vtkMRMLModelNode())
        outputModel.SetName('Path Trajectory')
        outputModel.CreateDefaultDisplayNodes()
        outputModel.GetDisplayNode().SetSliceIntersectionVisibility(True)
        outputModel.GetDisplayNode().SetColor(1, 1, 0)

        markupsToModel = slicer.mrmlScene.AddNode(
            slicer.vtkMRMLMarkupsToModelNode())
        markupsToModel.SetAutoUpdateOutput(True)
        markupsToModel.SetAndObserveModelNodeID(outputModel.GetID())
        markupsToModel.SetAndObserveMarkupsNodeID(fidNode.GetID())
        markupsToModel.SetModelType(slicer.vtkMRMLMarkupsToModelNode.Curve)
        markupsToModel.SetCurveType(
            slicer.vtkMRMLMarkupsToModelNode.CardinalSpline)
        print 'Reconstruction complete'
Exemplo n.º 43
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())
    def test_LabelMapToModel1(self):
        """ Ideally you should have several levels of tests.  At the lowest level
        tests should exercise the functionality of the logic with different inputs
        (both valid and invalid).  At higher levels your tests should emulate the
        way the user would interact with your code and confirm that it still works
        the way you intended.
        One of the most important features of the tests is that it should alert other
        developers when their changes will have an impact on the behavior of your
        module.  For example, if a developer removes a feature that you depend on,
        your test should break so they know that the feature is needed.
        """

        self.delayDisplay("Starting the test")
        #
        # first, get some data
        #
        import urllib
        downloads = (
            ('http://slicer.kitware.com/midas3/download?items=153172',
             'BrainTumor_GBM_HG0003.mrb', slicer.util.loadScene),
        )

        for url, name, loader in downloads:
            filePath = slicer.app.temporaryPath + '/' + name
            if not os.path.exists(filePath) or os.stat(filePath).st_size == 0:
                logging.info(
                    'Requesting download %s from %s...\n' % (name, url))
                urllib.urlretrieve(url, filePath)
            if loader:
                logging.info('Loading %s...' % (name,))
                loader(filePath)
        self.delayDisplay('Finished with download and loading')

        labelMapNode = slicer.util.getNode(pattern="Tissue Segmentation Volume")
        logic = LabelMapToModelLogic()
        self.assertTrue(logic.hasImageData(labelMapNode))
        modelNode = slicer.vtkMRMLModelNode()
        logic.run(labelMapNode, modelNode)
        self.delayDisplay('Test passed!')
Exemplo n.º 45
0
  def fiberToModel(self,fiber):
    """Convert a vtkMRMLFiberBundleNode into a dummy vtkMRMLModelNode
    so it can use the same converter.
    Note: need to use attributes to send color since we cannot
    add a display node to the dummy node since it is not in a scene.
    If fiberMode is tube, create tubes from fiber tracts, else use lines from tracts
    """
    if self.targetFiberCount and int(self.targetFiberCount) < fiber.GetPolyData().GetNumberOfCells():
      fiberPolyData = self.copyFirstNLines(fiber.GetPolyData(), int(self.targetFiberCount))
    else:
      fiberPolyData = fiber.GetPolyData()

    model = slicer.vtkMRMLModelNode()
    model.SetName("ModelFrom_"+fiber.GetID())
    displayNode = None
    if self.fiberMode == "tubes":
      tuber = vtk.vtkTubeFilter()
      tuber.SetInputDataObject(fiberPolyData)
      tuber.Update()
      polyData = tuber.GetOutput()
      model.SetAndObservePolyData(polyData)
      normalsArray = polyData.GetPointData().GetArray('TubeNormals')
      if not normalsArray:
        return None
      normalsArray.SetName('Normals')
      displayNode = fiber.GetTubeDisplayNode()
    elif self.fiberMode == "lines":
      model.SetAndObservePolyData(fiberPolyData)
      displayNode = fiber.GetLineDisplayNode()
    if displayNode:
      color = json.dumps(list(displayNode.GetColor()))
      model.SetAttribute("color", color)
      model.SetAttribute("visibility", str(displayNode.GetVisibility()))
    return(model)

    notes = """
  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)
  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)
  def test_3D_interaction2Models(self):
    """ Test that the interaction widget works with multiple models.
    """
    #self.delayDisplay("Starting test_3D_interaction2Models")
    #
    # Setup:
    #  1. Create 2 cubes:
    #     - 1 centered
    #     - Another moved.
    #  2. Get the widget
    #

    # Centered cube
    centeredCubeSource = vtk.vtkCubeSource()
    centeredCubeSize = [500, 200, 300]
    centeredCubeSource.SetXLength(centeredCubeSize[0])
    centeredCubeSource.SetYLength(centeredCubeSize[1])
    centeredCubeSource.SetZLength(centeredCubeSize[2])
    centeredCubeSource.SetCenter(0.0, 0.0, 0.0)
    centeredCubeSource.Update()

    centeredCubeNode = slicer.mrmlScene.AddNode(slicer.vtkMRMLModelNode())
    centeredCubeNode.SetPolyDataConnection(centeredCubeSource.GetOutputPort())

    # Moved cube
    movedCubeSource = vtk.vtkCubeSource()
    movedCubeSource.SetXLength(800)
    movedCubeSource.SetYLength(233)
    movedCubeSource.SetZLength(761)
    movedCubeSource.SetCenter(100.0, -80.0, -700.023)

    rotation = vtk.vtkTransform()
    rotation.RotateY(45.0)

    applyTransform = vtk.vtkTransformPolyDataFilter()
    applyTransform.SetTransform(rotation)
    applyTransform.SetInputConnection(movedCubeSource.GetOutputPort())
    applyTransform.Update()

    movedCubeNode = slicer.mrmlScene.AddNode(slicer.vtkMRMLModelNode())
    movedCubeNode.SetPolyDataConnection(applyTransform.GetOutputPort())

    # Get the widget
    logic = SlicerTransformInteractionTest1Logic()
    tNode, tdNode = logic.addTransform()
    slicer.app.layoutManager().layout = slicer.vtkMRMLLayoutNode.SlicerLayoutOneUp3DView
    manager = logic.getModel3DDisplayableManager()
    self.assertIsNotNone(manager)

    widget = manager.GetWidget(tdNode)
    tdNode.SetEditorVisibility(True)
    self.assertTrue(widget.GetEnabled())

    representation = widget.GetRepresentation()
    transform = vtk.vtkTransform()

    #
    # No transform, make sure the widget is correctly placed around:
    #  1. No cubes
    #  2. The centered cube
    #  3. The centered cube AND the other cube
    #  4. The other cube only
    #  5. No cubes
    #

    # Check default widget tranform values
    expectedDefaultTransform = [
      [100.0,   0.0,    0.0,    0.0],
      [0.0,   100.0,    0.0,    0.0],
      [0.0,     0.0,  100.0,    0.0],
      [0.0,     0.0,    0.0,    1.0],
      ]
    representation.GetTransform(transform)
    self.assertTransform(transform, expectedDefaultTransform)

    # Transform the centered cube
    centeredCubeNode.SetAndObserveTransformNodeID(tNode.GetID())
    tdNode.UpdateEditorBounds()
    centeredCubeTransform = copy.deepcopy(expectedDefaultTransform)
    for i in range(3):
      centeredCubeTransform[i][i] = 2*centeredCubeSize[i]

    representation.GetTransform(transform)
    self.assertTransform(transform, centeredCubeTransform)

    # Transform both cubes
    movedCubeNode.SetAndObserveTransformNodeID(tNode.GetID())
    tdNode.UpdateEditorBounds()
    bothCubeTransform = [
      [2452.35424805,     0.0,      0.0,         -363.088562012],
      [0.0,             593.0,      0.0,          -48.25],
      [0.0,               0.0,   2535.19702148,  -483.799255371],
      [0.0,               0.0,      0.0,            1.0],
    ]

    representation.GetTransform(transform)
    self.assertTransform(transform, bothCubeTransform)

    # Transform only moved cube
    centeredCubeNode.SetAndObserveTransformNodeID(None)
    tdNode.UpdateEditorBounds()
    movedCubeTransform = [
      [2207.58724976,   0.0,     0.0,          -424.280311584],
      [0.0,           466.0,     0.0,           -80.0],
      [0.0,             0.0,   2207.58731651,  -565.701681614],
      [0.0,             0.0,      0.0,            1.0],
    ]

    representation.GetTransform(transform)
    self.assertTransform(transform, movedCubeTransform)

    # Default again
    movedCubeNode.SetAndObserveTransformNodeID(None)
    tdNode.UpdateEditorBounds()

    representation.GetTransform(transform)
    self.assertTransform(transform, expectedDefaultTransform)
  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)
Exemplo n.º 50
0
  def TestSection_3_ImportExportSegment(self):
    # Import/export, both one label and all labels
    logging.info('Test section 3: Import/export segment')
    
    # Export single segment to model node
    bodyModelNode = slicer.vtkMRMLModelNode()
    bodyModelNode.SetName('BodyModel')
    slicer.mrmlScene.AddNode(bodyModelNode)
    
    bodySegment = self.inputSegmentationNode.GetSegmentation().GetSegment('Body_Contour')
    result = vtkSlicerSegmentationsModuleLogic.ExportSegmentToRepresentationNode(bodySegment, bodyModelNode)
    self.assertTrue(result)
    self.assertIsNotNone(bodyModelNode.GetPolyData())
    self.assertEqual(bodyModelNode.GetPolyData().GetNumberOfPoints(), 302)
    #TODO: On Linux and Windows it is 588, on Mac it is 580. Need to investigate
    # self.assertEqual(bodyModelNode.GetPolyData().GetNumberOfCells(), 588)
    self.assertTrue(bodyModelNode.GetPolyData().GetNumberOfCells() == 588 or bodyModelNode.GetPolyData().GetNumberOfCells() == 580)

    # Export single segment to volume node
    bodyLabelmapNode = slicer.vtkMRMLLabelMapVolumeNode()
    bodyLabelmapNode.SetName('BodyLabelmap')
    slicer.mrmlScene.AddNode(bodyLabelmapNode)
    result = vtkSlicerSegmentationsModuleLogic.ExportSegmentToRepresentationNode(bodySegment, bodyLabelmapNode)
    self.assertTrue(result)
    bodyImageData = bodyLabelmapNode.GetImageData()
    self.assertIsNotNone(bodyImageData)
    imageStat = vtk.vtkImageAccumulate()
    imageStat.SetInputData(bodyImageData)
    imageStat.Update()
    self.assertEqual(imageStat.GetVoxelCount(), 648)
    self.assertEqual(imageStat.GetMin()[0], 0)
    self.assertEqual(imageStat.GetMax()[0], 1)

    # Export multiple segments to volume node
    allSegmentsLabelmapNode = slicer.vtkMRMLLabelMapVolumeNode()
    allSegmentsLabelmapNode.SetName('AllSegmentsLabelmap')
    slicer.mrmlScene.AddNode(allSegmentsLabelmapNode)
    result = vtkSlicerSegmentationsModuleLogic.ExportAllSegmentsToLabelmapNode(self.inputSegmentationNode, allSegmentsLabelmapNode)
    self.assertTrue(result)
    allSegmentsImageData = allSegmentsLabelmapNode.GetImageData()
    self.assertIsNotNone(allSegmentsImageData)
    imageStat = vtk.vtkImageAccumulate()
    imageStat.SetInputData(allSegmentsImageData)
    imageStat.SetComponentExtent(0,5,0,0,0,0)
    imageStat.SetComponentOrigin(0,0,0)
    imageStat.SetComponentSpacing(1,1,1)
    imageStat.Update()
    self.assertEqual(imageStat.GetVoxelCount(), 54872000)
    imageStatResult = imageStat.GetOutput()
    self.assertEqual(imageStatResult.GetScalarComponentAsDouble(0,0,0,0), 46678738)
    self.assertEqual(imageStatResult.GetScalarComponentAsDouble(1,0,0,0), 0)
    self.assertEqual(imageStatResult.GetScalarComponentAsDouble(2,0,0,0), 7618805)
    self.assertEqual(imageStatResult.GetScalarComponentAsDouble(3,0,0,0), 128968)
    self.assertEqual(imageStatResult.GetScalarComponentAsDouble(4,0,0,0), 0) # Built from color table and color four is removed in previous test section
    self.assertEqual(imageStatResult.GetScalarComponentAsDouble(5,0,0,0), 445489)

    # Import model to segment
    modelImportSegmentationNode = vtkMRMLSegmentationNode()
    modelImportSegmentationNode.SetName('ModelImport')
    modelImportSegmentationNode.GetSegmentation().SetMasterRepresentationName(self.closedSurfaceReprName)
    slicer.mrmlScene.AddNode(modelImportSegmentationNode)
    modelSegment = vtkSlicerSegmentationsModuleLogic.CreateSegmentFromModelNode(bodyModelNode)
    modelSegment.UnRegister(None) # Need to release ownership
    self.assertIsNotNone(modelSegment)
    self.assertIsNotNone(modelSegment.GetRepresentation(self.closedSurfaceReprName))

    # Import multi-label labelmap to segmentation
    multiLabelImportSegmentationNode = vtkMRMLSegmentationNode()
    multiLabelImportSegmentationNode.SetName('MultiLabelImport')
    multiLabelImportSegmentationNode.GetSegmentation().SetMasterRepresentationName(self.binaryLabelmapReprName)
    slicer.mrmlScene.AddNode(multiLabelImportSegmentationNode)
    result = vtkSlicerSegmentationsModuleLogic.ImportLabelmapToSegmentationNode(allSegmentsLabelmapNode, multiLabelImportSegmentationNode)
    self.assertTrue(result)
    self.assertEqual(multiLabelImportSegmentationNode.GetSegmentation().GetNumberOfSegments(), 3)

    # Import labelmap into single segment
    singleLabelImportSegmentationNode = vtkMRMLSegmentationNode()
    singleLabelImportSegmentationNode.SetName('SingleLabelImport')
    singleLabelImportSegmentationNode.GetSegmentation().SetMasterRepresentationName(self.binaryLabelmapReprName)
    slicer.mrmlScene.AddNode(singleLabelImportSegmentationNode)
    # Should not import multi-label labelmap to segment
    nullSegment = vtkSlicerSegmentationsModuleLogic.CreateSegmentFromLabelmapVolumeNode(allSegmentsLabelmapNode)
    self.assertIsNone(nullSegment)
    logging.info('(This error message tests an impossible scenario, it is supposed to appear)')
    # Make labelmap single-label and import again
    threshold = vtk.vtkImageThreshold()
    threshold.ThresholdByUpper(0.5)
    threshold.SetInValue(1)
    threshold.SetOutValue(0)
    threshold.SetOutputScalarType(vtk.VTK_UNSIGNED_CHAR)
    if vtk.VTK_MAJOR_VERSION <= 5:
      threshold.SetInput(allSegmentsLabelmapNode.GetImageData())
    else:
      threshold.SetInputData(allSegmentsLabelmapNode.GetImageData())
    threshold.SetOutput(allSegmentsLabelmapNode.GetImageData())
    threshold.Update()
    labelSegment = vtkSlicerSegmentationsModuleLogic.CreateSegmentFromLabelmapVolumeNode(allSegmentsLabelmapNode)
    labelSegment.UnRegister(None) # Need to release ownership
    self.assertIsNotNone(labelSegment)
    self.assertIsNotNone(labelSegment.GetRepresentation(self.binaryLabelmapReprName))

    # Import/export with transforms
    logging.info('Test section 4/2: Import/export with transforms')

    # Create transform node that will be used to transform the tested nodes
    bodyModelTransformNode = slicer.vtkMRMLLinearTransformNode()
    slicer.mrmlScene.AddNode(bodyModelTransformNode)
    bodyModelTransform = vtk.vtkTransform()
    bodyModelTransform.Translate(1000.0, 0.0, 0.0)
    bodyModelTransformNode.ApplyTransformMatrix(bodyModelTransform.GetMatrix())
    
    # Set transform as parent to input segmentation node
    self.inputSegmentationNode.SetAndObserveTransformNodeID(bodyModelTransformNode.GetID())

    # Export single segment to model node from transformed segmentation
    bodyModelNodeTransformed = slicer.vtkMRMLModelNode()
    bodyModelNodeTransformed.SetName('BodyModelTransformed')
    slicer.mrmlScene.AddNode(bodyModelNodeTransformed)
    bodySegment = self.inputSegmentationNode.GetSegmentation().GetSegment('Body_Contour')
    result = vtkSlicerSegmentationsModuleLogic.ExportSegmentToRepresentationNode(bodySegment, bodyModelNodeTransformed)
    self.assertTrue(result)
    self.assertIsNotNone(bodyModelNodeTransformed.GetParentTransformNode())

    # Export single segment to volume node from transformed segmentation
    bodyLabelmapNodeTransformed = slicer.vtkMRMLLabelMapVolumeNode()
    bodyLabelmapNodeTransformed.SetName('BodyLabelmapTransformed')
    slicer.mrmlScene.AddNode(bodyLabelmapNodeTransformed)
    result = vtkSlicerSegmentationsModuleLogic.ExportSegmentToRepresentationNode(bodySegment, bodyLabelmapNodeTransformed)
    self.assertTrue(result)
    self.assertIsNotNone(bodyLabelmapNodeTransformed.GetParentTransformNode())

    # Create transform node that will be used to transform the tested nodes
    modelTransformedImportSegmentationTransformNode = slicer.vtkMRMLLinearTransformNode()
    slicer.mrmlScene.AddNode(modelTransformedImportSegmentationTransformNode)
    modelTransformedImportSegmentationTransform = vtk.vtkTransform()
    modelTransformedImportSegmentationTransform.Translate(-500.0, 0.0, 0.0)
    modelTransformedImportSegmentationTransformNode.ApplyTransformMatrix(modelTransformedImportSegmentationTransform.GetMatrix())

    # Import transformed model to segment in transformed segmentation
    modelTransformedImportSegmentationNode = vtkMRMLSegmentationNode()
    modelTransformedImportSegmentationNode.SetName('ModelImportTransformed')
    modelTransformedImportSegmentationNode.GetSegmentation().SetMasterRepresentationName(self.closedSurfaceReprName)
    slicer.mrmlScene.AddNode(modelTransformedImportSegmentationNode)
    modelTransformedImportSegmentationNode.SetAndObserveTransformNodeID(modelTransformedImportSegmentationTransformNode.GetID())
    modelSegmentTranformed = vtkSlicerSegmentationsModuleLogic.CreateSegmentFromModelNode(bodyModelNodeTransformed, modelTransformedImportSegmentationNode)
    modelSegmentTranformed.UnRegister(None) # Need to release ownership
    self.assertIsNotNone(modelSegmentTranformed)
    modelSegmentTransformedPolyData = modelSegmentTranformed.GetRepresentation(self.closedSurfaceReprName)
    self.assertIsNotNone(modelSegmentTransformedPolyData)
    self.assertEqual(int(modelSegmentTransformedPolyData.GetBounds()[0]), 1332)
    self.assertEqual(int(modelSegmentTransformedPolyData.GetBounds()[1]), 1675)

    # Clean up temporary nodes
    slicer.mrmlScene.RemoveNode(bodyModelNode)
    slicer.mrmlScene.RemoveNode(bodyLabelmapNode)
    slicer.mrmlScene.RemoveNode(allSegmentsLabelmapNode)
    slicer.mrmlScene.RemoveNode(modelImportSegmentationNode)
    slicer.mrmlScene.RemoveNode(multiLabelImportSegmentationNode)
    slicer.mrmlScene.RemoveNode(singleLabelImportSegmentationNode)
    slicer.mrmlScene.RemoveNode(bodyModelTransformNode)
    slicer.mrmlScene.RemoveNode(bodyModelNodeTransformed)
    slicer.mrmlScene.RemoveNode(bodyLabelmapNodeTransformed)
    slicer.mrmlScene.RemoveNode(modelTransformedImportSegmentationNode)
Exemplo n.º 51
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
Exemplo n.º 52
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" )
Exemplo n.º 53
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
Exemplo n.º 54
0
  def TestSection_ImportExportSegment(self):
    # Import/export, both one label and all labels
    logging.info('Test section: Import/export segment')

    # Export single segment to model node
    bodyModelNode = slicer.vtkMRMLModelNode()
    bodyModelNode.SetName('BodyModel')
    slicer.mrmlScene.AddNode(bodyModelNode)

    bodySegment = self.inputSegmentationNode.GetSegmentation().GetSegment(self.bodySegmentName)
    result = slicer.vtkSlicerSegmentationsModuleLogic.ExportSegmentToRepresentationNode(bodySegment, bodyModelNode)
    self.assertTrue(result)
    self.assertIsNotNone(bodyModelNode.GetPolyData())
    #TODO: Number of points increased to 1677 due to end-capping, need to investigate!
    #self.assertEqual(bodyModelNode.GetPolyData().GetNumberOfPoints(), 302)
    #TODO: On Linux and Windows it is 588, on Mac it is 580. Need to investigate
    # self.assertEqual(bodyModelNode.GetPolyData().GetNumberOfCells(), 588)
    #self.assertTrue(bodyModelNode.GetPolyData().GetNumberOfCells() == 588 or bodyModelNode.GetPolyData().GetNumberOfCells() == 580)

    # Export single segment to volume node
    bodyLabelmapNode = slicer.vtkMRMLLabelMapVolumeNode()
    bodyLabelmapNode.SetName('BodyLabelmap')
    slicer.mrmlScene.AddNode(bodyLabelmapNode)
    result = slicer.vtkSlicerSegmentationsModuleLogic.ExportSegmentToRepresentationNode(bodySegment, bodyLabelmapNode)
    self.assertTrue(result)
    bodyImageData = bodyLabelmapNode.GetImageData()
    self.assertIsNotNone(bodyImageData)
    imageStat = vtk.vtkImageAccumulate()
    imageStat.SetInputData(bodyImageData)
    imageStat.Update()
    self.assertEqual(imageStat.GetVoxelCount(), 792)
    self.assertEqual(imageStat.GetMin()[0], 0)
    self.assertEqual(imageStat.GetMax()[0], 1)

    # Export multiple segments to volume node
    allSegmentsLabelmapNode = slicer.vtkMRMLLabelMapVolumeNode()
    allSegmentsLabelmapNode.SetName('AllSegmentsLabelmap')
    slicer.mrmlScene.AddNode(allSegmentsLabelmapNode)
    result = slicer.vtkSlicerSegmentationsModuleLogic.ExportAllSegmentsToLabelmapNode(self.inputSegmentationNode, allSegmentsLabelmapNode)
    self.assertTrue(result)
    allSegmentsImageData = allSegmentsLabelmapNode.GetImageData()
    self.assertIsNotNone(allSegmentsImageData)
    imageStat = vtk.vtkImageAccumulate()
    imageStat.SetInputData(allSegmentsImageData)
    imageStat.SetComponentExtent(0,5,0,0,0,0)
    imageStat.SetComponentOrigin(0,0,0)
    imageStat.SetComponentSpacing(1,1,1)
    imageStat.Update()
    imageStatResult = imageStat.GetOutput()
    for i in range(4):
      logging.info("Volume {0}: {1}".format(i, imageStatResult.GetScalarComponentAsDouble(i,0,0,0)))
    self.assertEqual(imageStat.GetVoxelCount(), 127109360)
    self.assertEqual(imageStatResult.GetScalarComponentAsDouble(0,0,0,0), 78967249)
    self.assertEqual(imageStatResult.GetScalarComponentAsDouble(1,0,0,0), 39705288)
    self.assertEqual(imageStatResult.GetScalarComponentAsDouble(2,0,0,0), 890883)
    self.assertEqual(imageStatResult.GetScalarComponentAsDouble(3,0,0,0), 7545940)
    # Import model to segment
    modelImportSegmentationNode = slicer.mrmlScene.AddNewNodeByClass('vtkMRMLSegmentationNode', 'ModelImport')
    modelImportSegmentationNode.GetSegmentation().SetMasterRepresentationName(self.closedSurfaceReprName)
    modelSegment = slicer.vtkSlicerSegmentationsModuleLogic.CreateSegmentFromModelNode(bodyModelNode)
    modelSegment.UnRegister(None) # Need to release ownership
    self.assertIsNotNone(modelSegment)
    self.assertIsNotNone(modelSegment.GetRepresentation(self.closedSurfaceReprName))

    # Import multi-label labelmap to segmentation
    multiLabelImportSegmentationNode = slicer.mrmlScene.AddNewNodeByClass('vtkMRMLSegmentationNode', 'MultiLabelImport')
    multiLabelImportSegmentationNode.GetSegmentation().SetMasterRepresentationName(self.binaryLabelmapReprName)
    result = slicer.vtkSlicerSegmentationsModuleLogic.ImportLabelmapToSegmentationNode(allSegmentsLabelmapNode, multiLabelImportSegmentationNode)
    self.assertTrue(result)
    self.assertEqual(multiLabelImportSegmentationNode.GetSegmentation().GetNumberOfSegments(), 3)

    # Import labelmap into single segment
    singleLabelImportSegmentationNode = slicer.mrmlScene.AddNewNodeByClass('vtkMRMLSegmentationNode', 'SingleLabelImport')
    singleLabelImportSegmentationNode.GetSegmentation().SetMasterRepresentationName(self.binaryLabelmapReprName)
    # Should not import multi-label labelmap to segment
    nullSegment = slicer.vtkSlicerSegmentationsModuleLogic.CreateSegmentFromLabelmapVolumeNode(allSegmentsLabelmapNode)
    self.assertIsNone(nullSegment)
    logging.info('(This error message is a result of testing an impossible scenario, it is supposed to appear)')
    # Make labelmap single-label and import again
    threshold = vtk.vtkImageThreshold()
    threshold.SetInValue(0)
    threshold.SetOutValue(1)
    threshold.ReplaceInOn()
    threshold.ThresholdByLower(0)
    threshold.SetOutputScalarType(vtk.VTK_UNSIGNED_CHAR)
    if vtk.VTK_MAJOR_VERSION <= 5:
      threshold.SetInput(allSegmentsLabelmapNode.GetImageData())
    else:
      threshold.SetInputData(allSegmentsLabelmapNode.GetImageData())
    threshold.Update()
    allSegmentsLabelmapNode.GetImageData().ShallowCopy(threshold.GetOutput())
    labelSegment = slicer.vtkSlicerSegmentationsModuleLogic.CreateSegmentFromLabelmapVolumeNode(allSegmentsLabelmapNode)
    labelSegment.UnRegister(None) # Need to release ownership
    self.assertIsNotNone(labelSegment)
    self.assertIsNotNone(labelSegment.GetRepresentation(self.binaryLabelmapReprName))

    # Import/export with transforms
    logging.info('Test subsection: Import/export with transforms')

    # Create transform node that will be used to transform the tested nodes
    bodyModelTransformNode = slicer.vtkMRMLLinearTransformNode()
    slicer.mrmlScene.AddNode(bodyModelTransformNode)
    bodyModelTransform = vtk.vtkTransform()
    bodyModelTransform.Translate(1000.0, 0.0, 0.0)
    bodyModelTransformNode.ApplyTransformMatrix(bodyModelTransform.GetMatrix())

    # Set transform as parent to input segmentation node
    self.inputSegmentationNode.SetAndObserveTransformNodeID(bodyModelTransformNode.GetID())

    # Export single segment to model node from transformed segmentation
    bodyModelNodeTransformed = slicer.vtkMRMLModelNode()
    bodyModelNodeTransformed.SetName('BodyModelTransformed')
    slicer.mrmlScene.AddNode(bodyModelNodeTransformed)
    bodySegment = self.inputSegmentationNode.GetSegmentation().GetSegment(self.bodySegmentName)
    result = slicer.vtkSlicerSegmentationsModuleLogic.ExportSegmentToRepresentationNode(bodySegment, bodyModelNodeTransformed)
    self.assertTrue(result)
    self.assertIsNotNone(bodyModelNodeTransformed.GetParentTransformNode())

    # Export single segment to volume node from transformed segmentation
    bodyLabelmapNodeTransformed = slicer.vtkMRMLLabelMapVolumeNode()
    bodyLabelmapNodeTransformed.SetName('BodyLabelmapTransformed')
    slicer.mrmlScene.AddNode(bodyLabelmapNodeTransformed)
    result = slicer.vtkSlicerSegmentationsModuleLogic.ExportSegmentToRepresentationNode(bodySegment, bodyLabelmapNodeTransformed)
    self.assertTrue(result)
    self.assertIsNotNone(bodyLabelmapNodeTransformed.GetParentTransformNode())

    # Create transform node that will be used to transform the tested nodes
    modelTransformedImportSegmentationTransformNode = slicer.vtkMRMLLinearTransformNode()
    slicer.mrmlScene.AddNode(modelTransformedImportSegmentationTransformNode)
    modelTransformedImportSegmentationTransform = vtk.vtkTransform()
    modelTransformedImportSegmentationTransform.Translate(-500.0, 0.0, 0.0)
    modelTransformedImportSegmentationTransformNode.ApplyTransformMatrix(modelTransformedImportSegmentationTransform.GetMatrix())

    # Import transformed model to segment in transformed segmentation
    modelTransformedImportSegmentationNode = slicer.mrmlScene.AddNewNodeByClass('vtkMRMLSegmentationNode', 'ModelImportTransformed')
    modelTransformedImportSegmentationNode.GetSegmentation().SetMasterRepresentationName(self.closedSurfaceReprName)
    modelTransformedImportSegmentationNode.SetAndObserveTransformNodeID(modelTransformedImportSegmentationTransformNode.GetID())
    modelSegmentTranformed = slicer.vtkSlicerSegmentationsModuleLogic.CreateSegmentFromModelNode(bodyModelNodeTransformed, modelTransformedImportSegmentationNode)
    modelSegmentTranformed.UnRegister(None) # Need to release ownership
    self.assertIsNotNone(modelSegmentTranformed)
    modelSegmentTransformedPolyData = modelSegmentTranformed.GetRepresentation(self.closedSurfaceReprName)
    self.assertIsNotNone(modelSegmentTransformedPolyData)
    self.assertEqual(int(modelSegmentTransformedPolyData.GetBounds()[0]), 1332)
    self.assertEqual(int(modelSegmentTransformedPolyData.GetBounds()[1]), 1675)

    # Clean up temporary nodes
    slicer.mrmlScene.RemoveNode(bodyModelNode)
    slicer.mrmlScene.RemoveNode(bodyLabelmapNode)
    slicer.mrmlScene.RemoveNode(allSegmentsLabelmapNode)
    slicer.mrmlScene.RemoveNode(modelImportSegmentationNode)
    slicer.mrmlScene.RemoveNode(multiLabelImportSegmentationNode)
    slicer.mrmlScene.RemoveNode(singleLabelImportSegmentationNode)
    slicer.mrmlScene.RemoveNode(bodyModelTransformNode)
    slicer.mrmlScene.RemoveNode(bodyModelNodeTransformed)
    slicer.mrmlScene.RemoveNode(bodyLabelmapNodeTransformed)
    slicer.mrmlScene.RemoveNode(modelTransformedImportSegmentationNode)