コード例 #1
0
ファイル: Q3DC.py プロジェクト: luciemac/Q3DCExtension
 def test_CalculateDisplacement2(self):
     logic = Q3DCLogic()
     markupsNode1 = slicer.vtkMRMLMarkupsFiducialNode()
     slicer.mrmlScene.RemoveAllObservers()
     
     markupsNode1.AddFiducial(63.90,-46.98, 6.98)
     markupsNode1.AddFiducial(43.79,-60.16,12.16)
     markupsNode1.AddFiducial(62.21,-45.31,7.41)
     markupsNode1.AddFiducial(41.97,-61.24,11.30)
     
     yaw = logic.computeYaw(markupsNode1, 0, markupsNode1, 1, markupsNode1, 2, markupsNode1, 3)
     roll = logic.computeRoll(markupsNode1, 0, markupsNode1, 1, markupsNode1, 2, markupsNode1, 3)
     print "roll, pitch", yaw, roll
     if yaw != 4.964 or roll != 3.565:
         return False
     
     markupsNode1.AddFiducial(53.80,-53.57,9.47)
     markupsNode1.AddFiducial(53.98,-52.13,9.13)
     markupsNode1.AddFiducial(52.09,-53.27,9.36)
     markupsNode1.AddFiducial(51.77,-50.10,9.80)
     pitch = logic.computePitch(markupsNode1, 4, markupsNode1, 5, markupsNode1, 6, markupsNode1, 7)
     if pitch != 21.187:
         return False
     
     return True
コード例 #2
0
  def section_MarkupRole(self):
    self.delayDisplay("Markup role",self.delayMs)

    shNode = slicer.vtkMRMLSubjectHierarchyNode.GetSubjectHierarchyNode(slicer.mrmlScene)
    self.assertIsNotNone( shNode )

    # Create sample markups node
    markupsNode = slicer.vtkMRMLMarkupsFiducialNode()
    slicer.mrmlScene.AddNode(markupsNode)
    markupsNode.SetName(self.sampleMarkupName)
    fiducialPosition = [100.0, 0.0, 0.0]
    markupsNode.AddFiducialFromArray(fiducialPosition)
    markupsShItemID = shNode.GetItemByDataNode(markupsNode)
    self.assertIsNotNone( markupsShItemID )
    self.assertEqual( shNode.GetItemOwnerPluginName(markupsShItemID), 'Markups' )

    # Create patient and study
    patientItemID = shNode.CreateSubjectItem(shNode.GetSceneItemID(), 'Patient')
    self.studyItemID = shNode.CreateStudyItem(patientItemID, 'Study')

    # Add markups under study
    markupsShItemID2 = shNode.CreateItem(self.studyItemID, markupsNode)
    self.assertEqual( markupsShItemID, markupsShItemID2 )
    self.assertEqual( shNode.GetItemParent(markupsShItemID), self.studyItemID )
    self.assertEqual( shNode.GetItemOwnerPluginName(markupsShItemID), 'Markups' )
コード例 #3
0
ファイル: SlicerBoundsTest.py プロジェクト: SlicerRt/Slicer
  def test_Markup(self):
    """ Test the GetRASBounds & GetBounds method on a markup.
    """
    #self.delayDisplay("Starting test_Markup")
    markupNode = slicer.mrmlScene.AddNode(slicer.vtkMRMLMarkupsFiducialNode())

    markupNode.AddFiducial(1.0, 0.0, 0.0)
    markupNode.AddFiducial(-45.0, -90.0, -180.0)
    markupNode.AddFiducial(-200.0, 500.0, -0.23)
    markupNode.AddFiducial(1.0, 1003.01, 0.0)

    bounds = range(6)
    markupNode.GetRASBounds(bounds)
    untransformedBounds = [-200, 1.0, -90, 1003.01, -180.0, 0.0]
    self.assertListAlmostEquals(bounds, untransformedBounds)

    markupNode.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)

    markupNode.SetAndObserveTransformNodeID(transformNode.GetID())
    transformedBounds = [-1977.3875985837567, 90.6250336838986, -213.3290140037272, 2314.3030541154367, -1801.9498682023534, 24.221433153858232]
    markupNode.GetRASBounds(bounds)
    self.assertListAlmostEquals(bounds, transformedBounds)

    markupNode.GetBounds(bounds)
    self.assertListAlmostEquals(bounds, untransformedBounds)
コード例 #4
0
    def onCurrentNodeChanged(self):
        if self.inputModelSelector.currentNode():
            activeInputID = self.inputModelSelector.currentNode().GetID()
            if activeInputID:
                if not self.dictionaryInput.has_key(activeInputID):
                    # Add the new input on the dictionary
                    self.dictionaryInput[activeInputID] = self.inputState()
                    fidNode  = slicer.vtkMRMLMarkupsFiducialNode()
                    slicer.mrmlScene.AddNode(fidNode)
                    self.dictionaryInput[activeInputID].fidNodeID = fidNode.GetID()

                    # Observers Fiducials Node:
                    self.dictionaryInput[activeInputID].MarkupAddedEventTag = fidNode.AddObserver(fidNode.MarkupAddedEvent, self.onMarkupAddedEvent)
                    self.dictionaryInput[activeInputID].PointModifiedEventTag = fidNode.AddObserver(fidNode.PointModifiedEvent, self.onPointModifiedEvent)
                else:
                    # Key already exists -> Set the markupsList associated to that model active!
                    slicer.modules.markups.logic().SetActiveListID(slicer.mrmlScene.GetNodeByID(self.dictionaryInput[activeInputID].fidNodeID))
                
                # Update landmark ComboBox by adding the labels of landmarks associated to that model
                fidNode = slicer.app.mrmlScene().GetNodeByID(self.dictionaryInput[activeInputID].fidNodeID)
                if fidNode:
                    if self.landmarkComboBoxROI.count != 0:
                        self.landmarkComboBoxROI.clear()
                    numOfFid = fidNode.GetNumberOfMarkups()
                    if numOfFid > 0:
                        for i in range(0, numOfFid):
                            landmarkLabel = fidNode.GetNthMarkupLabel(i)
                            self.landmarkComboBoxROI.addItem(landmarkLabel)

                self.logic.UpdateThreeDView(self.inputModelSelector.currentNode(),
                                            self.dictionaryInput,
                                            self.landmarkComboBoxROI.currentText,
                                            'onCurrentNodeChanged')
            else:
                print ' Input chosen: None! '
コード例 #5
0
    def section_MarkupRole(self):
        self.delayDisplay("Markup role", self.delayMs)

        # Create sample markups node
        markupsNode = slicer.vtkMRMLMarkupsFiducialNode()
        slicer.mrmlScene.AddNode(markupsNode)
        markupsNode.SetName(self.sampleMarkupName)
        fiducialPosition = [100.0, 0.0, 0.0]
        markupsNode.AddFiducialFromArray(fiducialPosition)

        # Add markups to subject hierarchy
        from vtkSlicerSubjectHierarchyModuleMRML import vtkMRMLSubjectHierarchyNode

        patientNode = vtkMRMLSubjectHierarchyNode.CreateSubjectHierarchyNode(
            slicer.mrmlScene, None, slicer.vtkMRMLSubjectHierarchyConstants.GetDICOMLevelPatient(), "Patient"
        )
        studyNode = vtkMRMLSubjectHierarchyNode.CreateSubjectHierarchyNode(
            slicer.mrmlScene, patientNode, self.studyName, slicer.vtkMRMLSubjectHierarchyConstants.GetDICOMLevelStudy()
        )
        markupsShNode = vtkMRMLSubjectHierarchyNode.CreateSubjectHierarchyNode(
            slicer.mrmlScene,
            studyNode,
            slicer.vtkMRMLSubjectHierarchyConstants.GetDICOMLevelSeries(),
            self.sampleMarkupName,
            markupsNode,
        )

        self.assertTrue(markupsShNode != None)
        self.assertTrue(markupsShNode.GetParentNode() == studyNode)
        self.assertTrue(markupsShNode.GetOwnerPluginName() == "Markups")
コード例 #6
0
  def test_GraphCutSegmentSelfTest1(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.
    """

    
    #
    # first, get some data
    #
    # import urllib
	# downloads = (('http://www.slicer.org/slicerWiki/images/5/59/RegLib_C01_1.nrrd', 'Tumor.nrrd', slicer.util.loadVolume),)
	#export http_proxy=http://proxyhost:proxyport

    # 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')
	
    self.delayDisplay("Starting the test")
    mainWindow = slicer.util.mainWindow()
    mainWindow.moduleSelector().selectModule('GraphCutInteravtiveSegmenter')
	
    volumeNode = self.downloadMRHead()
#    slicer.util.loadVolume(slicer.app.slicerHome+"/RegLib_C01_1.nrrd")
#   volumeNode = slicer.util.getNode('RegLib_C01_1')
	
    cropVolumeNode = slicer.vtkMRMLCropVolumeParametersNode()
    cropVolumeNode.SetScene(slicer.mrmlScene)
    slicer.mrmlScene.AddNode(cropVolumeNode)
	
    fiducial = slicer.vtkMRMLMarkupsFiducialNode()
    fiducial.SetScene(slicer.mrmlScene)
    fiducial.AddFiducial(-1.8,31.6,11.9)
    fiducial.AddFiducial(15.7,45.0,30.1)
    fiducial.AddFiducial(-18.5,12.0,30.1)
    fiducial.AddFiducial(-2.6,28.7,45.5)
    slicer.mrmlScene.AddNode(fiducial)
	 
    graphCutLogic = slicer.modules.graphcutinteractivesegmenter.logic()
    graphCutLogic.checkMarkups(volumeNode,fiducial)
    graphCutLogic.crop(volumeNode,cropVolumeNode)
		
    graphCutLogic.apply(slicer.mrmlScene.GetNodeByID(cropVolumeNode.GetOutputVolumeNodeID()),True,True)
    self.delayDisplay('Test passed!')
コード例 #7
0
ファイル: mixins.py プロジェクト: fedorov/SlicerProstate
 def cloneFiducials(original, cloneName, keepDisplayNode=False):
   clone = slicer.vtkMRMLMarkupsFiducialNode()
   clone.Copy(original)
   clone.SetName(cloneName)
   slicer.mrmlScene.AddNode(clone)
   if not keepDisplayNode:
     displayNode = slicer.vtkMRMLMarkupsDisplayNode()
     slicer.mrmlScene.AddNode(displayNode)
     clone.SetAndObserveDisplayNodeID(displayNode.GetID())
   return clone
コード例 #8
0
    def onCapture(self):
        if self.isManualCapturing:
            # Cancel button hit
            self.endManualCapturing()
            slicer.modules.annotations.logic().StopPlaceMode()
            return ()

        # Record tracker data at time of freeze and store
        videoCameraToReferenceVtk = vtk.vtkMatrix4x4()
        self.videoCameraTransformSelector.currentNode(
        ).GetMatrixTransformToParent(videoCameraToReferenceVtk)
        self.videoCameraToReference = PinholeCameraRayIntersectionWidget.vtk4x4ToNumpy(
            videoCameraToReferenceVtk)

        if PinholeCameraRayIntersectionWidget.areSameVTK4x4(
                videoCameraToReferenceVtk, self.identity4x4):
            self.resultsLabel.text = "Invalid transform. Please try again with sensor in view."
            return ()

        # Reset view so that capture button always works
        if self.imageSelector.currentNode() is not None:
            slicer.app.layoutManager().sliceWidget('Red').sliceLogic(
            ).GetSliceCompositeNode().SetBackgroundVolumeID(
                self.imageSelector.currentNode().GetID())
            slicer.app.layoutManager().sliceWidget(
                'Red').sliceLogic().FitSliceToAll()
        self.onSelect()

        # Make a copy of the volume node (aka freeze cv capture) to allow user to play with detection parameters or click on center
        self.centerFiducialSelectionNode = slicer.mrmlScene.GetNodeByID(
            slicer.app.layoutManager().sliceWidget('Red').sliceLogic(
            ).GetSliceCompositeNode().GetBackgroundVolumeID())
        self.copyNode = slicer.mrmlScene.CopyNode(
            self.centerFiducialSelectionNode)
        imData = vtk.vtkImageData()
        imData.DeepCopy(self.centerFiducialSelectionNode.GetImageData())
        self.copyNode.SetAndObserveImageData(imData)
        self.copyNode.SetName('FrozenImage')
        slicer.app.layoutManager().sliceWidget(
            'Red').sliceLogic().GetSliceCompositeNode().SetBackgroundVolumeID(
                self.copyNode.GetID())

        # Initiate fiducial selection
        self.markupsNode = slicer.vtkMRMLMarkupsFiducialNode()
        slicer.mrmlScene.AddNode(self.markupsNode)
        self.markupsNode.SetName('SphereCenter')
        self.markupsLogic.SetActiveListId(self.markupsNode)
        self.markupsLogic.StartPlaceMode(False)
        self.pointModifiedObserverTag = self.markupsNode.AddObserver(
            slicer.vtkMRMLMarkupsNode.PointModifiedEvent, self.onPointModified)

        # Disable resetting while capture is active
        self.resetButton.setEnabled(False)
        self.isManualCapturing = True
        self.captureButton.setText('Cancel')
コード例 #9
0
ファイル: Q3DC.py プロジェクト: luciemac/Q3DCExtension
 def test_CalculateDisplacement1(self):
     logic = Q3DCLogic()
     slicer.mrmlScene.RemoveAllObservers()
     markupsNode1 = slicer.vtkMRMLMarkupsFiducialNode()
     markupsNode1.AddFiducial(-5.331, 51.955, 4.831)
     markupsNode1.AddFiducial(-8.018, 41.429, -52.621)
     diffXAxis, diffYAxis, diffZAxis, threeDDistance = logic.defineDistances(markupsNode1, 0, markupsNode1, 1)
     print diffXAxis, diffYAxis, diffZAxis, threeDDistance
     if diffXAxis != -2.687 or diffYAxis != -10.526 or diffZAxis != -57.452 or threeDDistance != 58.47:
         return False
     return True
コード例 #10
0
ファイル: PathPlanner.py プロジェクト: GSaj2020/PathPlanning
  def test_TestInsidePoints(self):
      """ Testing points I know are inside of the mask (first point is outside of the region entirely, second is the origin.
      """
      self.delayDisplay("Starting test points inside mask.")
      mask = slicer.util.getNode('r_hippo')

      # I am going to hard code one point I know is within my mask
      insidePoints = slicer.vtkMRMLMarkupsFiducialNode()
      insidePoints.AddFiducial(152.3, 124.6, 108.0)
      insidePoints.AddFiducial(145, 129, 108.0)

      # run our class
      returnedPoints = slicer.vtkMRMLMarkupsFiducialNode()
      PickPointsMatrix().run(mask, insidePoints, returnedPoints)
      # check if we have any returned fiducials -- this should be 1
      if (returnedPoints.GetNumberOfFiducials() != 2):
        self.delayDisplay('Test failed. There are ' + str(returnedPoints.GetNumberOfFiducials()) + ' return points.')
        return

      self.delayDisplay('Test passed!' + str(returnedPoints.GetNumberOfFiducials()) + ' points were returned.')
コード例 #11
0
    def run(self, numToAdd=100, rOffset=0, usefewerModifyCalls=0):
        """
    Run the actual algorithm
    """
        print('Running test to add %s fidicuals' % (numToAdd, ))
        print('Index\tTime to add fid\tDelta between adds')
        print("%(index)04s\t" % {'index': "i"}, "t\tdt'")
        r = rOffset
        a = 0
        s = 0
        t1 = 0
        t2 = 0
        t3 = 0
        t4 = 0
        timeToAddThisFid = 0
        timeToAddLastFid = 0

        testStartTime = time.clock()
        displayNode = slicer.vtkMRMLMarkupsDisplayNode()
        slicer.mrmlScene.AddNode(displayNode)
        fidNode = slicer.vtkMRMLMarkupsFiducialNode()
        slicer.mrmlScene.AddNode(fidNode)
        fidNode.SetAndObserveDisplayNodeID(displayNode.GetID())

        if usefewerModifyCalls == 1:
            print("Start modify")
            mod = fidNode.StartModify()

        import random

        # iterate over the number of fiducials to add
        for i in range(numToAdd):
            #    print "i = ", i, "/", numToAdd, ", r = ", r, ", a = ", a, ", s = ", s
            t1 = time.clock()
            fidNode.AddFiducial(r, a, s)
            t2 = time.clock()
            timeToAddThisFid = t2 - t1
            dt = timeToAddThisFid - timeToAddLastFid
            #print '%(index)04d\t' % {'index': i}, timeToAddThisFid, "\t", dt
            r = float(i) / numToAdd * 100.0 - 50.0 + random.uniform(
                -20.0, 20.0)
            a = float(i) / numToAdd * 100.0 - 50.0 + random.uniform(
                -20.0, 20.0)
            s = random.uniform(-20.0, 20.0)
            timeToAddLastFid = timeToAddThisFid

        if usefewerModifyCalls == 1:
            fidNode.EndModify(mod)

        testEndTime = time.clock()
        testTime = testEndTime - testStartTime
        print("Total time to add ", numToAdd, " = ", testTime)

        return True
コード例 #12
0
 def markupsNodes(self):
   return {
     slicer.vtkMRMLMarkupsAngleNode(): slicer.vtkSlicerAngleWidget(),
     slicer.vtkMRMLMarkupsClosedCurveNode(): slicer.vtkSlicerCurveWidget(),
     slicer.vtkMRMLMarkupsCurveNode(): slicer.vtkSlicerCurveWidget(),
     slicer.vtkMRMLMarkupsFiducialNode(): slicer.vtkSlicerPointsWidget(),
     slicer.vtkMRMLMarkupsLineNode(): slicer.vtkSlicerLineWidget(),
     slicer.vtkMRMLMarkupsPlaneNode(): slicer.vtkSlicerPlaneWidget(),
     slicer.vtkMRMLMarkupsROINode(): slicer.vtkSlicerROIWidget(),
     slicer.vtkMRMLMarkupsTestLineNode(): slicer.vtkSlicerTestLineWidget()
   }
コード例 #13
0
ファイル: Q3DC.py プロジェクト: luciemac/Q3DCExtension
 def onDefineMidPointClicked(self):
     newMarkupsNode = slicer.vtkMRMLMarkupsFiducialNode()
     slicer.mrmlScene.AddNode(newMarkupsNode)
     
     self.logic.calculateMidPoint(newMarkupsNode,
                                  self.markupsDictionary,
                                  self.correspondenceLandmarkDict[self.landmarkComboBox1.currentText],
                                  self.correspondenceLandmarkDict[self.landmarkComboBox2.currentText])
                                  
     newMarkupsNode.SetNthMarkupLocked(0, True)
     if self.midPointOnSurfaceCheckBox.isChecked():
         self.logic.projectLandmarkOnSurface(self.markupsDictionary[newMarkupsNode.GetID()].landmarkDictionary.values()[0], newMarkupsNode.GetID()) 
コード例 #14
0
  def test_PathPlanning_TestEmptyMask(self):
    """Test the case for the empty mask where there is no target mask"""
    self.delayDisplay('Starting test points for empty mask')
    emptymask = slicer.vtkMRMLLabelMapVolumeNode()
    emptymask.SetAndObserveImageData(vtk.vtkImageData())

    targets = slicer.util.getNode('targets')

    #run the class PickPathsmat()
    Output = slicer.vtkMRMLMarkupsFiducialNode()
    PickPathsmat().run(emptymask, targets, Output)
    self.delayDisplay("Test passed! Empty mask doesn't break the class PickPathsmat()")
コード例 #15
0
  def run(self,numToAdd=100,rOffset=0,usefewerModifyCalls=0):
    """
    Run the actual algorithm
    """
    print('Running test to add %s fidicuals' % (numToAdd,))
    print('Index\tTime to add fid\tDelta between adds')
    print("%(index)04s\t" % {'index': "i"}, "t\tdt'")
    r = rOffset
    a = 0
    s = 0
    t1 = 0
    t2 = 0
    t3 = 0
    t4 = 0
    timeToAddThisFid = 0
    timeToAddLastFid = 0

    testStartTime = time.clock()
    displayNode = slicer.vtkMRMLMarkupsDisplayNode()
    slicer.mrmlScene.AddNode(displayNode)
    fidNode = slicer.vtkMRMLMarkupsFiducialNode()
    slicer.mrmlScene.AddNode(fidNode)
    fidNode.SetAndObserveDisplayNodeID(displayNode.GetID())

    if usefewerModifyCalls == 1:
      print("Start modify")
      mod = fidNode.StartModify()

    import random

    # iterate over the number of fiducials to add
    for i in range(numToAdd):
      #    print "i = ", i, "/", numToAdd, ", r = ", r, ", a = ", a, ", s = ", s
      t1 = time.clock()
      fidNode.AddFiducial(r,a,s)
      t2 = time.clock()
      timeToAddThisFid = t2 - t1
      dt = timeToAddThisFid - timeToAddLastFid
      #print '%(index)04d\t' % {'index': i}, timeToAddThisFid, "\t", dt
      r = float(i)/numToAdd * 100.0 - 50.0 + random.uniform(-20.0, 20.0)
      a = float(i)/numToAdd * 100.0 - 50.0 + random.uniform(-20.0, 20.0)
      s = random.uniform(-20.0, 20.0)
      timeToAddLastFid = timeToAddThisFid

    if usefewerModifyCalls == 1:
      fidNode.EndModify(mod)

    testEndTime = time.clock()
    testTime = testEndTime - testStartTime
    print("Total time to add ",numToAdd," = ", testTime)

    return True
コード例 #16
0
  def test_PathPlanning_InFiducial(self):
    #Check that the algorithm doesn't save a fiducial that's out of the target
    self.delayDisplay('Starting test point is inside target.')

    #get image node
    hippo = slicer.util.getNode('r_hippo')

    #Code two points that is inside the target structure
    PointIn = slicer.vtkMRMLMarkupsFiducialNode()
    PointIn.AddFiducial(156, 122, 110) #This point was obtained by inspection
    PointIn.AddFiducial(153.6, 126.1, 103) #This point was obtained by inspection

    #run the class PickPathsmat
    Output = slicer.vtkMRMLMarkupsFiducialNode()
    PickPathsmat().run(hippo, PointIn, Output)

    #check if it has returned any fiducial -- it has to be empty
    if Output.GetNumberOfFiducials() != 2:
      self.delayDisplay('Test failed. There are ' + str(Output.GetNumberOfFiducials()))
      return

    self.delayDisplay('Test passed! ' + str(Output.GetNumberOfFiducials()) + ' points were returned')
コード例 #17
0
 def createNewMarkupNode(self):
     # Create empty markup fiducial node
     if self.segmentMarkupNode is None:
         displayNode = slicer.vtkMRMLMarkupsDisplayNode()
         displayNode.SetTextScale(0)
         slicer.mrmlScene.AddNode(displayNode)
         self.segmentMarkupNode = slicer.vtkMRMLMarkupsFiducialNode()
         self.segmentMarkupNode.SetName('C')
         slicer.mrmlScene.AddNode(self.segmentMarkupNode)
         self.segmentMarkupNode.SetAndObserveDisplayNodeID(
             displayNode.GetID())
         self.setAndObserveSegmentMarkupNode(self.segmentMarkupNode)
         self.updateGUIFromMRML()
コード例 #18
0
ファイル: Q3DC.py プロジェクト: luciemac/Q3DCExtension
 def onAddLandmarkButtonClicked(self):
     newFidNode = slicer.vtkMRMLMarkupsFiducialNode()
     slicer.mrmlScene.AddNode(newFidNode)
     print newFidNode.GetID()
     slicer.modules.markups.logic().SetActiveListID(newFidNode)
     selectionNode = slicer.mrmlScene.GetNodeByID("vtkMRMLSelectionNodeSingleton")
     selectionNode.SetReferenceActivePlaceNodeClassName("vtkMRMLMarkupsFiducialNode")
     interactionNode = slicer.mrmlScene.GetNodeByID("vtkMRMLInteractionNodeSingleton")
     if self.modelComboBox.currentNode():
         interactionNode.SetCurrentInteractionMode(1)
     else:
         # Add a MessageBox!
         print "Select a model of reference"
コード例 #19
0
    def SetupCalibrationNode(self, usCalibrationNode):
        if (usCalibrationNode is None):
            return

        # Reference to marked points lists
        if (usCalibrationNode.GetNodeReference(
                ImagelessUSCalibrationWidget.MARKED_POINTS_ROLE) is None):
            markedPoints = slicer.vtkMRMLMarkupsFiducialNode()
            markedPoints.SetName("Marked_Points")
            markedPoints.SetScene(slicer.mrmlScene)
            slicer.mrmlScene.AddNode(markedPoints)
            usCalibrationNode.SetAndObserveNodeReferenceID(
                ImagelessUSCalibrationWidget.MARKED_POINTS_ROLE,
                markedPoints.GetID())

        # Reference to unmarked points lists
        if (usCalibrationNode.GetNodeReference(
                ImagelessUSCalibrationWidget.UNMARKED_POINTS_ROLE) is None):
            unmarkedPoints = slicer.vtkMRMLMarkupsFiducialNode()
            unmarkedPoints.SetName("Unmarked_Points")
            unmarkedPoints.SetScene(slicer.mrmlScene)
            slicer.mrmlScene.AddNode(unmarkedPoints)
            usCalibrationNode.SetAndObserveNodeReferenceID(
                ImagelessUSCalibrationWidget.UNMARKED_POINTS_ROLE,
                unmarkedPoints.GetID())

        # Observe Markups node for knowing when to add corresponding point
        usCalibrationNode.GetNodeReference(
            ImagelessUSCalibrationWidget.UNMARKED_POINTS_ROLE).AddObserver(
                vtk.vtkCommand.ModifiedEvent,
                partial(self.ComputeCalibration, usCalibrationNode))
        usCalibrationNode.GetNodeReference(
            ImagelessUSCalibrationWidget.MARKED_POINTS_ROLE).AddObserver(
                vtk.vtkCommand.ModifiedEvent,
                partial(self.ComputeCalibration, usCalibrationNode))
        usCalibrationNode.AddObserver(
            vtk.vtkCommand.ModifiedEvent,
            partial(self.ComputeCalibration, usCalibrationNode))
コード例 #20
0
    def test_PathPlanning2_TestNoPoints(self):
        """Test the case for the null space where there is no entry fiducials"""
        self.delayDisplay('Starting test no points for the ventricles mask')
        ventricles = slicer.util.getNode('ventricles')

        # Empty markup fiducials set
        emptypoints = slicer.vtkMRMLMarkupsFiducialNode()

        # run the class PickPathsmat()
        targets = slicer.util.getNode('targets')
        IntersectWith().run(ventricles, emptypoints, targets)
        self.delayDisplay(
            "Test passed! Empty markup fiducials don't break the class IntersectWith()"
        )
コード例 #21
0
ファイル: HannahG.py プロジェクト: HLGreer/HannahG-CISC472
  def createTransformPoints(randErr, N):
    Scale = 30.0
    Sigma = randErr  # radius of random error

    fromNormCoordinates = numpy.random.rand(N, 3)  # An array of random numbers
    noise = numpy.random.normal(0.0, Sigma, N * 3)

    # Homework for Jan 24:
    referenceToRas = slicer.vtkMRMLLinearTransformNode()
    slicer.mrmlScene.AddNode(referenceToRas)
    referenceToRas.SetName('ReferenceToRas')

    referenceFids = slicer.vtkMRMLMarkupsFiducialNode()
    referenceFids.SetName('ReferenceFiducials')
    slicer.mrmlScene.AddNode(referenceFids)
    referenceFids.GetDisplayNode().SetSelectedColor(0, 0, 1)
    RASFids = slicer.vtkMRMLMarkupsFiducialNode()
    RASFids.SetName('RASFiducials')
    slicer.mrmlScene.AddNode(RASFids)
    RASFids.GetDisplayNode().SetSelectedColor(1, 1, 0)

    alphaPoints = vtk.vtkPoints()
    betaPoints = vtk.vtkPoints()
    for i in range(N):
      x = (fromNormCoordinates[i, 0] - 0.5) * Scale
      y = (fromNormCoordinates[i, 1] - 0.5) * Scale
      z = (fromNormCoordinates[i, 2] - 0.5) * Scale
      numFids = referenceFids.AddFiducial(x, y, z)
      numPoints = alphaPoints.InsertNextPoint(x, y, z)
      xx = x + noise[i * 3]
      yy = y + noise[i * 3 + 1]
      zz = z + noise[i * 3 + 2]
      numFids = RASFids.AddFiducial(xx, yy, zz)
      numPoints = betaPoints.InsertNextPoint(xx, yy, zz)

    return [alphaPoints, betaPoints, referenceToRas]
コード例 #22
0
    def onAddLesion(self):
        # add a fiducial to the current lesions list
        self.lesionList = self.targetListSelector.currentNode()
        if self.lesionList is None:
            # creating a lesion list
            self.lesionList = slicer.vtkMRMLMarkupsFiducialNode()
            self.lesionList.SetName("Lesions")
            slicer.mrmlScene.AddNode(self.lesionList)
            self.targetListSelector.setCurrentNode(self.lesionList)
            self.addObservers()

        interactionNode = slicer.util.getNode(
            "vtkMRMLInteractionNodeSingleton")
        interactionNode.SwitchToSinglePlaceMode()
        slicer.modules.markups.logic().SetActiveListID(self.lesionList)
コード例 #23
0
 def SetupCalibrationNode( self, frwNode ):
   if ( frwNode is None ):
     return
     
   # Add a new fiducial node for "Image_Points" (from points)
   if ( frwNode.GetFromFiducialListNode() is None ):
     imagePoints = slicer.vtkMRMLMarkupsFiducialNode()
     imagePoints.SetName( "Image_Points" )
     imagePoints.SetScene( slicer.mrmlScene )
     slicer.mrmlScene.AddNode( imagePoints )
     frwNode.SetAndObserveFromFiducialListNodeId( imagePoints.GetID() )
     
   # Add a new fiducial node for "Probe_Points" (to points)
   if ( frwNode.GetToFiducialListNode() is None ):
     probePoints = slicer.vtkMRMLMarkupsFiducialNode()
     probePoints.SetName( "Probe_Points" )
     probePoints.SetScene( slicer.mrmlScene )
     slicer.mrmlScene.AddNode( probePoints )
     frwNode.SetAndObserveToFiducialListNodeId( probePoints.GetID() )
     
   frwNode.SetRegistrationModeToSimilarity()
   
   # Observe Markups node for knowing when to add corresponding point
   frwNode.GetFromFiducialListNode().AddObserver( slicer.vtkMRMLMarkupsFiducialNode.MarkupAddedEvent, partial( self.AddPointToCalibration, frwNode ) )
コード例 #24
0
  def run(self):
    """
    Run the actual algorithm
    """
    #Obtengo puntos de referencia
    f = slicer.util.getNode('reference_sacro_points')
    sacroToReference = slicer.util.getNode('sacroToReference')

    p1 = [0.0,0.0,0.0]
    p2 = [0.0,0.0,0.0]
    p3 = [0.0,0.0,0.0]

    f.GetNthFiducialPosition(0,p1)
    f.GetNthFiducialPosition(1,p2)
    f.GetNthFiducialPosition(2,p3)

    p1 = p1 + [1.0]
    p2 = p2 + [1.0]
    p3 = p3 + [1.0]

    # transformamos los puntos a sus coordenadas transformadas

    tr= vtk.vtkMatrix4x4()
    sacroToReference.GetMatrixTransformToWorld(tr) 

    p1Transformed = [0.0,0.0,0.0,1.0]
    p2Transformed = [0.0,0.0,0.0,1.0]
    p3Transformed = [0.0,0.0,0.0,1.0]

    tr.MultiplyPoint(p1, p1Transformed)
    tr.MultiplyPoint(p2, p2Transformed)
    tr.MultiplyPoint(p3, p3Transformed)

    p1Transformed =  [p1Transformed[i] for i in (0,1,2)]
    p2Transformed =  [p2Transformed[i] for i in (0,1,2)]
    p3Transformed =  [p3Transformed[i] for i in (0,1,2)]

    m = [np.divide((p1Transformed[0]+p2Transformed[0]+p3Transformed[0]),3),np.divide((p1Transformed[1]+p2Transformed[1]+p3Transformed[1]),3),np.divide((p1Transformed[2]+p2Transformed[2]+p3Transformed[2]),3)]
    #normal
    normal = np.cross(np.subtract(p1Transformed,p2Transformed),np.subtract(p1Transformed,p3Transformed))

    fids_original = slicer.vtkMRMLMarkupsFiducialNode()
    fids_original.SetName('Mean Point')
    fids_original.AddFiducialFromArray(m)
    slicer.mrmlScene.AddNode(fids_original)
    fids_original.GetDisplayNode().SetSelectedColor(0,0,1)
    
    plano = self.drawPlane(m, normal)
コード例 #25
0
    def test_DefinitionOfROI(self, Model, FinalModel, FidNodeName, PointsCoords):

        self.delayDisplay("Definition of a FOI on " + Model.GetName())

        widget = slicer.modules.PickAndPaintWidget
        widget.inputModelSelector.setCurrentNode(Model)
        self.inputMarkupsFiducial = slicer.vtkMRMLMarkupsFiducialNode()
        self.inputMarkupsFiducial.SetName(FidNodeName)
        slicer.mrmlScene.AddNode(self.inputMarkupsFiducial)
        widget.inputLandmarksSelector.setCurrentNode(self.inputMarkupsFiducial)
        for point in PointsCoords:
            self.inputMarkupsFiducial.AddFiducial(point[0], point[1], point[2])
            widget.ShapeQuantifierCore.onPointModifiedEvent(self.inputMarkupsFiducial,None)
            widget.radiusDefinitionWidget.value = 3.0

        return self.compare_ROIS(self.inputMarkupsFiducial, Model, FinalModel)
コード例 #26
0
    def run(self, landmarkFilePath, outputDirectory, headerSize,
            loadFileOption):
        """
    Run the actual algorithm
    """
        # set landmark filename and length of header
        headerSize = 2  #number of lines in the header
        landmarkFileName = os.path.basename(landmarkFilePath)
        (landmarkFileBase, ext) = os.path.splitext(landmarkFileName)

        # Create a markups node for imported points
        fiducialNode = slicer.vtkMRMLMarkupsFiducialNode()
        slicer.mrmlScene.AddNode(fiducialNode)
        fiducialNode.CreateDefaultDisplayNodes()
        fiducialNode.SetName(landmarkFileBase)

        # read landmarks
        landmarkFile = open(landmarkFilePath)
        lines = landmarkFile.readlines()
        landmarkFile.close()

        #iterate through list of and place in markups node
        for i in range(headerSize, len(lines) - 1):
            # in this file format, lines contain [name, x-coordinate, y-coordinate, z-coordinate]
            # by default, split command splits by whitespace
            lineData = lines[i].split()
            if len(lineData) == 4:
                coordinates = [
                    float(lineData[1]),
                    float(lineData[2]),
                    float(lineData[3])
                ]
                name = lineData[0]
                fiducialNode.AddFiducialFromArray(coordinates, name)
            else:
                logging.debug("Error: not a supported landmark file format")

        outputPath = os.path.join(outputDirectory, landmarkFileBase + '.fcsv')
        slicer.util.saveNode(fiducialNode, outputPath)
        if not loadFileOption:
            slicer.mrmlScene.RemoveNode(fiducialNode)  #remove node from scene

        logging.info('Processing completed')

        return True
コード例 #27
0
  def createTarget(self):

    #First we create the list to add the fiducials
    if self.firstFiducial:
      self.targetFiducial = slicer.vtkMRMLMarkupsFiducialNode()  
      self.targetFiducial.SetName('Target')
      slicer.mrmlScene.AddNode(self.targetFiducial)
      self.firstFiducial  = False


    self.targetFiducial.AddObserver(self.targetFiducial.MarkupAddedEvent, self.onMRMLSceneModified)


    placeModePersistence = 1
    slicer.modules.markups.logic().StartPlaceMode(placeModePersistence)
    

    self.targetFiducial.SetDisplayVisibility(True)
コード例 #28
0
    def test_DefinitionOfROI(self, Model, FinalModel, FidNodeName,
                             PointsCoords):

        self.delayDisplay("Definition of a FOI on " + Model.GetName())

        widget = slicer.modules.PickAndPaintWidget
        widget.inputModelSelector.setCurrentNode(Model)
        self.inputMarkupsFiducial = slicer.vtkMRMLMarkupsFiducialNode()
        self.inputMarkupsFiducial.SetName(FidNodeName)
        slicer.mrmlScene.AddNode(self.inputMarkupsFiducial)
        widget.inputLandmarksSelector.setCurrentNode(self.inputMarkupsFiducial)
        for point in PointsCoords:
            self.inputMarkupsFiducial.AddFiducial(point[0], point[1], point[2])
            widget.ShapeQuantifierCore.onPointModifiedEvent(
                self.inputMarkupsFiducial, None)
            widget.radiusDefinitionWidget.value = 3.0

        return self.compare_ROIS(self.inputMarkupsFiducial, Model, FinalModel)
コード例 #29
0
  def section_MarkupRole(self):
    self.delayDisplay("Markup role",self.delayMs)

    # Create sample markups node
    markupsNode = slicer.vtkMRMLMarkupsFiducialNode()
    slicer.mrmlScene.AddNode(markupsNode)
    markupsNode.SetName(self.sampleMarkupName)
    fiducialPosition = [100.0, 0.0, 0.0]
    markupsNode.AddFiducialFromArray(fiducialPosition)

    # Add markups to subject hierarchy
    patientNode = slicer.vtkMRMLSubjectHierarchyNode.CreateSubjectHierarchyNode(slicer.mrmlScene, None, slicer.vtkMRMLSubjectHierarchyConstants.GetDICOMLevelPatient(), 'Patient')
    studyNode = slicer.vtkMRMLSubjectHierarchyNode.CreateSubjectHierarchyNode(slicer.mrmlScene, patientNode, self.studyName, slicer.vtkMRMLSubjectHierarchyConstants.GetDICOMLevelStudy())
    markupsShNode = slicer.vtkMRMLSubjectHierarchyNode.CreateSubjectHierarchyNode(slicer.mrmlScene, studyNode, slicer.vtkMRMLSubjectHierarchyConstants.GetDICOMLevelSeries(), self.sampleMarkupName, markupsNode)

    self.assertIsNotNone( markupsShNode )
    self.assertEqual( markupsShNode.GetParentNode(), studyNode )
    self.assertEqual( markupsShNode.GetOwnerPluginName(), 'Markups' )
コード例 #30
0
ファイル: TreeView.py プロジェクト: jAchtzehn/leaddbs
 def addFunction(self):
     # interaction node
     interactionNode = slicer.app.applicationLogic().GetInteractionNode()
     selectionNode = slicer.app.applicationLogic().GetSelectionNode()
     selectionNode.SetReferenceActivePlaceNodeClassName(
         "vtkMRMLMarkupsFiducialNode")
     # create aux marpus node
     fiducialNode = slicer.vtkMRMLMarkupsFiducialNode()
     slicer.mrmlScene.AddNode(fiducialNode)
     fiducialNode.CreateDefaultDisplayNodes()
     fiducialNode.GetDisplayNode().SetGlyphScale(1)
     fiducialNode.SetLocked(1)
     fiducialNode.SetName(
         slicer.mrmlScene.GenerateUniqueName('Fixed Point'))
     # add to subject hierarchy
     WarpDriveUtil.addFixedPoint(fiducialNode)
     # activate placement
     selectionNode.SetActivePlaceNodeID(fiducialNode.GetID())
     interactionNode.SetCurrentInteractionMode(interactionNode.Place)
コード例 #31
0
 def saveLandmarks(m, filename):
     fiducialNode = slicer.vtkMRMLMarkupsFiducialNode(
     )  # Create a markups node for imported points
     l = np.shape(m)[0]
     for landmark in range(l):
         coordinates = [
             float(-1 * m[landmark, 0]),
             float(-1 * m[landmark, 1]),
             float(m[landmark, 2])
         ]
         fiducialNode.AddFiducialFromArray(
             coordinates,
             str(landmark))  #insert fiducial named by landmark number
     slicer.mrmlScene.AddNode(fiducialNode)
     fiducialNode.SetName(
         'LM')  # set name to subject name, removing new line char
     path = filename + '.fcsv'
     slicer.util.saveNode(fiducialNode, path)
     slicer.mrmlScene.RemoveNode(fiducialNode)  #remove node from scene
     #fiducialNode.RemoveAllControlPoints() # remove all landmarks from node (new markups version)
     fiducialNode.RemoveAllMarkups()  # remove all landmarks from node
コード例 #32
0
 def convertDepthToPoints(self):
     try:
         self.fiducialNode = slicer.util.getNode("depthFiducials")
         numFiducials = self.fiducialNode.GetNumberOfFiducials()
         for i in range(numFiducials, 0, -1):
             self.fiducialNode.RemoveAllMarkups()
     except slicer.util.MRMLNodeNotFoundException:
         self.fiducialNode = slicer.vtkMRMLMarkupsFiducialNode()
         self.fiducialNode.SetName("depthFiducials")
         slicer.mrmlScene.AddNode(self.fiducialNode)
     max_depth = self.depthImage.max()
     imageShape = self.depthImage.shape
     fidAddedCount = 0
     for x in range(0, imageShape[0], 10):
         for y in range(0, imageShape[1], 10):
             depthValue = self.depthImage[x][y]
             if depthValue >= max_depth * (self.threshold / 100.0):
                 self.fiducialNode.AddFiducialFromArray(
                     numpy.array([x, y, depthValue]))
                 fidAddedCount += 1
     slicer.mrmlScene.Modified()
コード例 #33
0
ファイル: ReadLandmarkFile.py プロジェクト: jcfr/SlicerMorph
  def run(self, landmarkFilePath, headerSize, enableScreenshots=0):
    """
    Run the actual algorithm
    """
    # set landmark filename and length of header
    headerSize = 2  #number of lines in the header
    landmarkFileName = os.path.basename(landmarkFilePath)
    (landmarkFileBase, ext) = os.path.splitext(landmarkFileName)


    # Create a markups node for imported points
    fiducialNode = slicer.vtkMRMLMarkupsFiducialNode()
    slicer.mrmlScene.AddNode(fiducialNode)
    fiducialNode.CreateDefaultDisplayNodes()
    fiducialNode.SetName(landmarkFileBase)

    # read landmarks
    landmarkFile = open(landmarkFilePath, "r")
    lines = landmarkFile.readlines()
    landmarkFile.close()

    #iterate through list of and place in markups node
    for i in range(headerSize,len(lines)-1):
      # in this file format, lines contain [name, x-coordinate, y-coordinate, z-coordinate]
      # by default, split command splits by whitespace
      lineData = lines[i].split()
      if len(lineData) == 4:
        coordinates = [float(lineData[1]), float(lineData[2]), float(lineData[3])]
        name = lineData[0]
        fiducialNode.AddFiducialFromArray(coordinates, name)
      else: 
        logging.debug("Error: not a supported landmark file format")

    # Capture screenshot
    if enableScreenshots:
      self.takeScreenshot('ReadLandmarkFileTest-Start','MyScreenshot',-1)

    logging.info('Processing completed')

    return True
コード例 #34
0
	def onOWButton(self):
		#Setup Fiduical placement
		self.placedLandmarkNode = slicer.vtkMRMLMarkupsFiducialNode()
		slicer.mrmlScene.AddNode(self.placedLandmarkNode)
		#Fiduical Placement Widget
		self.fiducialWidget = slicer.qSlicerMarkupsPlaceWidget()
		self.fiducialWidget.buttonsVisible = False
		self.fiducialWidget.placeButton().show()
		self.fiducialWidget.setMRMLScene(slicer.mrmlScene)
		self.fiducialWidget.setCurrentNode(self.placedLandmarkNode)
		self.fiducialWidget.placeMultipleMarkups = slicer.qSlicerMarkupsPlaceWidget.ForcePlaceSingleMarkup

		#Delay to ensure Widget Appears & provide user with info
		slicer.util.infoDisplay("Place the following fiducial:\n\n" +
			 					"Oval Window\n\n" +
								"Press okay when ready to begin" )

		#Enable fiducial placement
		self.fiducialWidget.setPlaceModeEnabled(True)
		#Enable Cochlear Nerve button
		self.OWButton.enabled = False
		self.CNButton.enabled = True
コード例 #35
0
ファイル: SlicerBoundsTest.py プロジェクト: qtigercom/Slicer
    def test_Markup(self):
        """ Test the GetRASBounds & GetBounds method on a markup.
    """
        #self.delayDisplay("Starting test_Markup")
        markupNode = slicer.mrmlScene.AddNode(
            slicer.vtkMRMLMarkupsFiducialNode())

        markupNode.AddFiducial(1.0, 0.0, 0.0)
        markupNode.AddFiducial(-45.0, -90.0, -180.0)
        markupNode.AddFiducial(-200.0, 500.0, -0.23)
        markupNode.AddFiducial(1.0, 1003.01, 0.0)

        bounds = range(6)
        markupNode.GetRASBounds(bounds)
        untransformedBounds = [-200, 1.0, -90, 1003.01, -180.0, 0.0]
        self.assertListAlmostEquals(bounds, untransformedBounds)

        markupNode.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)

        markupNode.SetAndObserveTransformNodeID(transformNode.GetID())
        transformedBounds = [
            -1977.3875985837567, 90.6250336838986, -213.3290140037272,
            2314.3030541154367, -1801.9498682023534, 24.221433153858232
        ]
        markupNode.GetRASBounds(bounds)
        self.assertListAlmostEquals(bounds, transformedBounds)

        markupNode.GetBounds(bounds)
        self.assertListAlmostEquals(bounds, untransformedBounds)
コード例 #36
0
 def createMarkupsFiducialNode(self):
   self.inputMarkupNode = slicer.vtkMRMLMarkupsFiducialNode()
   self.inputMarkupNode.SetName('inputMarkupNode')
   slicer.mrmlScene.AddNode(self.inputMarkupNode)
コード例 #37
0
ファイル: ShaderProperties.py プロジェクト: neslimsah/Slicer
  def testSphereCut(self):

    self.delayDisplay("Starting...")
    self.setUp()

    import SampleData
    mrHead = SampleData.downloadSample('MRHead')

    self.delayDisplay("Head downloaded...")

    slicer.util.mainWindow().moduleSelector().selectModule('VolumeRendering')
    volumeRenderingWidgetRep = slicer.modules.volumerendering.widgetRepresentation()
    volumeRenderingWidgetRep.setMRMLVolumeNode(mrHead)

    volumeRenderingNode = slicer.mrmlScene.GetFirstNodeByName('VolumeRendering')
    volumeRenderingNode.SetVisibility(1)

    self.delayDisplay('Volume rendering on')

    methodComboBox = slicer.util.findChildren(name='RenderingMethodComboBox')[0]
    methodComboBox.currentIndex = methodComboBox.findText('VTK GPU Ray Casting')

    self.delayDisplay('GPU Ray Casting on')

    markupNode = slicer.mrmlScene.AddNode(slicer.vtkMRMLMarkupsFiducialNode())
    markupNode.AddFiducial(0.0, 100.0, 0.0)

    self.delayDisplay('Fiducial added')


    #------------------------------------------------------
    # Utility functions to get the position of the first
    # fiducial point in the scene and the shader property
    # node
    #------------------------------------------------------
    def GetFiducialPosition():
        fn = slicer.util.getNode('vtkMRMLMarkupsFiducialNode1')
        p=[0]*3
        fn.GetNthFiducialPosition(0,p)
        return p

    def GetShaderPropertyNode():
        return slicer.util.getNode('vtkMRMLShaderPropertyNode1')

    #------------------------------------------------------
    # Get the shader property node which contains every custom
    # shader modifications for every mapper associated with
    # the first volume rendering display node
    #------------------------------------------------------
    displayNode = slicer.util.getNodesByClass('vtkMRMLGPURayCastVolumeRenderingDisplayNode')[0]
    shaderPropNode = displayNode.GetOrCreateShaderPropertyNode(slicer.mrmlScene)
    shaderProp = shaderPropNode.GetShaderProperty()

    # turn off shading so carved region looks reasonable
    volumePropertyNode = displayNode.GetVolumePropertyNode()
    volumeProperty = volumePropertyNode.GetVolumeProperty()
    volumeProperty.ShadeOff()

    #------------------------------------------------------
    # Declare and initialize custom uniform variables
    # used in our shader replacement
    #------------------------------------------------------
    shaderUniforms = shaderPropNode.GetFragmentUniforms()
    shaderUniforms.RemoveAllUniforms()
    fiducialPos = GetFiducialPosition()
    shaderUniforms.SetUniform3f("center",fiducialPos)
    shaderUniforms.SetUniformf("radius",50.)

    #------------------------------------------------------
    # Replace the cropping implementation part of the
    # raycasting shader to skip everything in the sphere
    # defined by center and radius
    #------------------------------------------------------
    croppingImplShaderCode = """
        vec4 texCoordRAS = in_volumeMatrix[0] * in_textureDatasetMatrix[0]  * vec4(g_dataPos, 1.);
        g_skip = length(texCoordRAS.xyz - center) < radius;
    """
    shaderProp.ClearAllFragmentShaderReplacements()
    shaderProp.AddFragmentShaderReplacement("//VTK::Cropping::Impl", True, croppingImplShaderCode, False)

    #------------------------------------------------------
    # Add a callback when the fiducial moves to adjust
    # the center of the carving sphere accordingly
    #------------------------------------------------------
    def onFiducialMoved():
        p = GetFiducialPosition()
        propNode = GetShaderPropertyNode()
        propNode.GetFragmentUniforms().SetUniform3f("center",p)

    fn = slicer.util.getNode('vtkMRMLMarkupsFiducialNode1')
    fn.AddObserver(fn.PointModifiedEvent, lambda caller,event: onFiducialMoved())


    self.delayDisplay("Should be a carved out nose now")
コード例 #38
0
    def visualizeNewSrep(self, filename):
        # 1. parse header file
        tree = ET.parse(filename)
        upFileName = ''
        crestFileName = ''
        downFileName = ''
        nCols = 0
        nRows = 0
        for child in tree.getroot():
            if child.tag == 'upSpoke':
                upFileName = child.text
            elif child.tag == 'downSpoke':
                downFileName = child.text
            elif child.tag == 'crestSpoke':
                crestFileName = child.text
            elif child.tag == 'nRows':
                nRows = (int)(child.text)
            elif child.tag == 'nCols':
                nCols = (int)(child.text)

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

        upSpokes = reader.GetOutput()

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

        scene = slicer.mrmlScene

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

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

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

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

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

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

        boundary_point_ids = []

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            connection_lines.InsertNextCell(line)

        connection_polydata.SetPoints(connection_points)
        connection_polydata.SetLines(connection_lines)
        connection_model = slicer.vtkMRMLModelNode()
        connection_model.SetScene(scene)
        connection_model.SetName("Connection to Fold Curve")
        connection_model.SetAndObservePolyData(connection_polydata)
        # model display node
        connection_model_display = slicer.vtkMRMLModelDisplayNode()
        connection_model_display.SetColor(0, 0, 0)
        connection_model_display.SetScene(scene)
        connection_model_display.SetLineWidth(3.0)
        connection_model_display.SetBackfaceCulling(0)
        scene.AddNode(connection_model_display)
        connection_model.SetAndObserveDisplayNodeID(
            connection_model_display.GetID())
        scene.AddNode(connection_model)
コード例 #39
0
  def run(self):
    """
    Run the actual algorithm
    """
    print('Running test of the markups in compare viewers')

    #
    # first load the data
    #
    print("Getting MR Head Volume")
    import SampleData
    mrHeadVolume = SampleData.downloadSample("MRHead")

    #
    # link the viewers
    #
    sliceLogic = slicer.app.layoutManager().sliceWidget('Red').sliceLogic()
    compositeNode = sliceLogic.GetSliceCompositeNode()
    compositeNode.SetLinkedControl(1)

    #
    # MR Head in the background
    #
    sliceLogic.StartSliceCompositeNodeInteraction(1)
    compositeNode.SetBackgroundVolumeID(mrHeadVolume.GetID())
    sliceLogic.EndSliceCompositeNodeInteraction()

    #
    # switch to conventional layout
    #
    lm = slicer.app.layoutManager()
    lm.setLayout(2)

    # create a fiducial list
    displayNode = slicer.vtkMRMLMarkupsDisplayNode()
    slicer.mrmlScene.AddNode(displayNode)
    fidNode = slicer.vtkMRMLMarkupsFiducialNode()
    slicer.mrmlScene.AddNode(fidNode)
    fidNode.SetAndObserveDisplayNodeID(displayNode.GetID())

    # make it active
    selectionNode = slicer.mrmlScene.GetNodeByID("vtkMRMLSelectionNodeSingleton")
    if (selectionNode is not None):
      selectionNode.SetReferenceActivePlaceNodeID(fidNode.GetID())

    # add some known points to it
    eye1 = [33.4975, 79.4042, -10.2143]
    eye2 = [-31.283, 80.9652, -16.2143]
    nose = [4.61944, 114.526, -33.2143]
    index = fidNode.AddFiducialFromArray(eye1)
    fidNode.SetNthFiducialLabel(index, "eye-1")
    index = fidNode.AddFiducialFromArray(eye2)
    fidNode.SetNthFiducialLabel(index, "eye-2")
    index = fidNode.AddFiducialFromArray(nose)
    fidNode.SetNthFiducialLabel(index, "nose")

    self.delayDisplay("Placed 3 fiducials")

    #
    # switch to 2 viewers compare layout
    #
    lm.setLayout(12)
    self.delayDisplay("Switched to Compare 2 viewers")

    #
    # get compare slice composite node
    #
    compareLogic1 = slicer.app.layoutManager().sliceWidget('Compare1').sliceLogic()
    compareCompositeNode1 = compareLogic1.GetSliceCompositeNode()

    # set MRHead in the background
    compareLogic1.StartSliceCompositeNodeInteraction(1)
    compareCompositeNode1.SetBackgroundVolumeID(mrHeadVolume.GetID())
    compareLogic1.EndSliceCompositeNodeInteraction()
    compareLogic1.FitSliceToAll()
    # make it visible in 3D
    compareLogic1.GetSliceNode().SetSliceVisible(1)

    # scroll to a fiducial location
    compareLogic1.StartSliceOffsetInteraction()
    compareLogic1.SetSliceOffset(eye1[2])
    compareLogic1.EndSliceOffsetInteraction()
    self.delayDisplay("MH Head in background, scrolled to a fiducial")

    # scroll around through the range of points
    offset = nose[2]
    while offset < eye1[2]:
      compareLogic1.StartSliceOffsetInteraction()
      compareLogic1.SetSliceOffset(offset)
      compareLogic1.EndSliceOffsetInteraction()
      msg = "Scrolled to " + str(offset)
      self.delayDisplay(msg,250)
      offset += 1.0

    # switch back to conventional
    lm.setLayout(2)
    self.delayDisplay("Switched back to conventional layout")

    # switch to compare grid
    lm.setLayout(23)
    compareLogic1.FitSliceToAll()
    self.delayDisplay("Switched to Compare grid")

    # switch back to conventional
    lm.setLayout(2)
    self.delayDisplay("Switched back to conventional layout")

    return True
コード例 #40
0
    def run(self, enableScreenshots=0, screenshotScaleFactor=1):
        """
    Run the actual algorithm
    """
        self.delayDisplay("Running test of the Neurosurgical Planning tutorial")

        self.enableScreenshots = enableScreenshots
        self.screenshotScaleFactor = screenshotScaleFactor

        # conventional layout
        lm = slicer.app.layoutManager()
        lm.setLayout(2)

        moduleSelector = slicer.util.mainWindow().moduleSelector()
        #
        # first load the data
        #
        if self.enableScreenshots == 1:
            # for the tutorial, do it through the welcome module
            moduleSelector.selectModule("Welcome")
            self.delayDisplay("Screenshot")
            self.takeScreenshot("NeurosurgicalPlanning-Welcome", "Welcome module", -1)
        else:
            # otherwise show the sample data module
            moduleSelector.selectModule("SampleData")

        # use the sample data module logic to load data for the self test
        import SampleData

        sampleDataLogic = SampleData.SampleDataLogic()

        self.delayDisplay("Getting Baseline volume")
        baselineVolume = sampleDataLogic.downloadWhiteMatterExplorationBaselineVolume()

        self.delayDisplay("Getting DTI volume")
        dtiVolume = sampleDataLogic.downloadWhiteMatterExplorationDTIVolume()

        self.takeScreenshot("NeurosurgicalPlanning-Loaded", "Data loaded", -1)

        #
        # create a label map and set it for editing
        #
        volumesLogic = slicer.modules.volumes.logic()
        baselineVolumeLabel = volumesLogic.CreateAndAddLabelVolume(
            slicer.mrmlScene, baselineVolume, baselineVolume.GetName() + "-label"
        )
        baselineDisplayNode = baselineVolumeLabel.GetDisplayNode()
        baselineDisplayNode.SetAndObserveColorNodeID("vtkMRMLColorTableNodeFileGenericAnatomyColors.txt")
        selectionNode = slicer.app.applicationLogic().GetSelectionNode()
        selectionNode.SetReferenceActiveVolumeID(baselineVolume.GetID())
        selectionNode.SetReferenceActiveLabelVolumeID(baselineVolumeLabel.GetID())
        slicer.app.applicationLogic().PropagateVolumeSelection(0)

        data = slicer.util.array(baselineVolume.GetName() + "-label")
        data[6:15, 110:140, 130:160] = 293

        #
        # link the viewers
        #

        if self.enableScreenshots == 1:
            # for the tutorial, pop up the linking control
            sliceController = slicer.app.layoutManager().sliceWidget("Red").sliceController()
            popupWidget = sliceController.findChild("ctkPopupWidget")
            if popupWidget is not None:
                popupWidget.pinPopup(1)
                self.takeScreenshot("NeurosurgicalPlanning-Link", "Link slice viewers", -1)
                popupWidget.pinPopup(0)

        #
        # Tractography Label Map Seeding module
        #
        moduleSelector.selectModule("TractographyLabelMapSeeding")
        self.takeScreenshot(
            "NeurosurgicalPlanning-LabelMapSeedingModule", "Showing Tractography Label Seeding Module", -1
        )
        tractographyLabelSeeding = slicer.modules.tractographylabelmapseeding
        parameters = {}
        parameters["InputVolume"] = dtiVolume.GetID()
        baselinelabel293 = slicer.mrmlScene.GetFirstNodeByName("BaselineVolume-label")
        # VTK6 TODO - set 'InputROIPipelineInfo'
        parameters["InputROI"] = baselinelabel293.GetID()
        fibers = slicer.vtkMRMLFiberBundleNode()
        slicer.mrmlScene.AddNode(fibers)
        parameters["OutputFibers"] = fibers.GetID()
        parameters["UseIndexSpace"] = 1
        parameters["StoppingValue"] = 0.15
        parameters["ROIlabel"] = 293
        parameters["ThresholdMode"] = "FractionalAnisotropy"
        # defaults
        # parameters['ClTh'] = 0.3
        # parameters['MinimumLength'] = 20
        # parameters['MaximumLength'] = 800
        # parameters['StoppingCurvature'] = 0.7
        # parameters['IntegrationStepLength'] = 0.5
        # parameters['SeedSpacing'] = 2
        # and run it
        slicer.cli.run(tractographyLabelSeeding, None, parameters)
        self.takeScreenshot("NeurosurgicalPlanning-LabelMapSeeding", "Showing Tractography Label Seeding Results", -1)

        #
        # tractography fiducial seeding
        #
        moduleSelector.selectModule("TractographyInteractiveSeeding")
        self.takeScreenshot("NeurosurgicalPlanning-TIS", "Showing Tractography Interactive Seeding Module", -1)

        # DTI in background
        sliceLogic = slicer.app.layoutManager().sliceWidget("Red").sliceLogic()
        sliceLogic.StartSliceCompositeNodeInteraction(1)
        compositeNode = sliceLogic.GetSliceCompositeNode()
        compositeNode.SetBackgroundVolumeID(dtiVolume.GetID())
        sliceLogic.EndSliceCompositeNodeInteraction()

        # DTI visible in 3D
        sliceNode = sliceLogic.GetSliceNode()
        sliceLogic.StartSliceNodeInteraction(128)
        sliceNode.SetSliceVisible(1)
        sliceLogic.EndSliceNodeInteraction()

        self.takeScreenshot(
            "NeurosurgicalPlanning-TIS-DTI", "DTI volume with Tractography Interactive Seeding Module", -1
        )

        # place a fiducial
        displayNode = slicer.vtkMRMLMarkupsDisplayNode()
        slicer.mrmlScene.AddNode(displayNode)
        fidNode = slicer.vtkMRMLMarkupsFiducialNode()
        fidNode.SetName("F")
        slicer.mrmlScene.AddNode(fidNode)
        fidNode.SetAndObserveDisplayNodeID(displayNode.GetID())
        r = 28.338526
        a = 34.064367
        sliceOffset = 58.7
        s = sliceOffset
        fidNode.AddFiducial(r, a, s)

        # make it active
        selectionNode = slicer.mrmlScene.GetNodeByID("vtkMRMLSelectionNodeSingleton")
        if selectionNode is not None:
            selectionNode.SetReferenceActivePlaceNodeID(fidNode.GetID())

        self.takeScreenshot("NeurosurgicalPlanning-TIS-Fid1", "Fiducial in Tractography Interactive Seeding Module", -1)

        # set up the arguments
        wr = slicer.modules.tractographyinteractiveseeding.widgetRepresentation()
        wr.setDiffusionTensorVolumeNode(dtiVolume)
        # create a fiber bundle
        fiducialFibers = slicer.vtkMRMLFiberBundleNode()
        slicer.mrmlScene.AddNode(fiducialFibers)
        wr.setFiberBundleNode(fiducialFibers)
        wr.setSeedingNode(fidNode)
        wr.setMinimumPath(10)
        wr.setStoppingValue(0.15)

        self.takeScreenshot("NeurosurgicalPlanning-TIS-Args", "Tractography Interactive Seeding arguments", -1)

        self.delayDisplay("Moving the fiducial")
        for y in range(-20, 100, 5):
            msg = "Moving the fiducial to y = " + str(y)
            self.delayDisplay(msg, 250)
            fidNode.SetNthFiducialPosition(0, r, y, s)

        self.takeScreenshot(
            "NeurosurgicalPlanning-TIS-Moved", "Moved fiducial and did Tractography Interactive Seeding", -1
        )

        return True
コード例 #41
0
    def test_3D_parentTransform(self):
        """ Test that the interaction widget works with a parent transform.
    """
        #self.delayDisplay('Starting test_3D_parentTransform')
        #
        # Setup:
        #  - Use a markup fiducial node
        #  - Create a parent transform
        #  - Create another transform under the parent transform
        #

        markupNode = slicer.mrmlScene.AddNode(
            slicer.vtkMRMLMarkupsFiducialNode())
        markupNode.AddFiducial(500.0, -1000.0, 0.0)
        markupNode.AddFiducial(1000.0, 1000.0, 200.0)
        markupNode.AddFiducial(-1500.0, -200.0, -100.0)

        logic = SlicerTransformInteractionTest1Logic()
        parentNode, parendDisplayNode = logic.addTransform()

        leafNode, 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()

        #
        # Test the leaf transform (that has a parent) in a few situations
        #

        # Test the transform with just the parent (that is identity for now)
        leafNode.SetAndObserveTransformNodeID(parentNode.GetID())
        tdNode.UpdateEditorBounds()
        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)

        # Set an actual transform on the parent
        parentTransform = vtk.vtkTransform()
        move = [51.0, -27.0, 3.3]
        scale = [2.0, 7.0, 3.0]
        parentTransform.Translate(move)
        parentTransform.Scale(scale[0], scale[1], scale[2])
        parentTransform.RotateZ(90)
        parentTransform.RotateX(90)
        parentNode.ApplyTransformMatrix(parentTransform.GetMatrix())

        expectedTransformWithParent = [
            [0.0, 0.0, 200.0, 51.0],
            [700.0, 0.0, 0.0, -27.0],
            [0.0, 300.0, 0.0, 3.3],
            [0.0, 0.0, 0.0, 1.0],
        ]
        representation.GetTransform(transform)
        self.assertTransform(transform, expectedTransformWithParent)

        # Set the markup node under the leaf transform
        markupNode.SetAndObserveTransformNodeID(leafNode.GetID())
        tdNode.UpdateEditorBounds()
        expectedMarkupTransformWithParent = [
            [0.0, 0.0, 1200.0, 151.0],
            [35000.0, 0.0, 0.0, -1777.0],
            [0.0, 12000.0, 0.0, 3.3],
            [0.0, 0.0, 0.0, 1.0],
        ]
        representation.GetTransform(transform)
        self.assertTransform(transform, expectedMarkupTransformWithParent)

        # Set the parent transform to identity
        parentNode.ApplyTransformMatrix(
            parentTransform.GetLinearInverse().GetMatrix())
        expectedMarkupTransform = [
            [5000.0, 0.0, 0.0, -250.0],
            [0.0, 4000.0, 0.0, 0.0],
            [0.0, 0.0, 600.0, 50.0],
            [0.0, 0.0, 0.0, 1.0],
        ]
        representation.GetTransform(transform)
        self.assertTransform(transform, expectedMarkupTransform)
コード例 #42
0
  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)
コード例 #43
0
    def run(self, morphFileName, outputDirectory):
        """
    Run the actual conversion
    """
        f = open(morphFileName, 'r')
        data = f.readlines()
        f.close

        subjectNumber = 0
        landmarkNumber = 0
        dimensionNumber = 0
        nameIndex = 0
        rawIndex = 0

        #Scan file for data size
        for num, line in enumerate(data, 0):
            if 'individuals' in line.lower():
                subjectNumber = int(data[num + 1])
            elif 'landmarks' in line.lower():
                landmarkNumber = int(data[num + 1])
            elif 'dimensions' in line.lower():
                dimensionNumber = int(data[num + 1])
            elif 'names' in line.lower():
                nameIndex = num
            elif 'rawpoints' in line.lower():
                rawIndex = num

        #Check that size variables were found
        if subjectNumber == 0 or landmarkNumber == 0 or dimensionNumber == 0:
            print("Error reading file: can not read size")

        print("Individuals: ", subjectNumber)
        print("Landmarks: ", landmarkNumber)
        print("Dimensions: ", dimensionNumber)

        subjectList = data[nameIndex + 1:nameIndex + 1 + subjectNumber]
        rawData = data[rawIndex + 1:len(data)]  # get raw data portion of file
        rawData = [
            line for line in rawData if not ("\'" in line or "\n" == line)
        ]  # remove spaces and names

        if len(
                rawData
        ) != subjectNumber * landmarkNumber:  # check for error in landmark import
            print("Error reading file: incorrect landmark number")
        else:
            fiducialNode = slicer.vtkMRMLMarkupsFiducialNode(
            )  # Create a markups node for imported points
            for index, subject in enumerate(
                    subjectList):  # iterate through each subject

                for landmark in range(landmarkNumber):
                    lineData = rawData.pop(
                        0).split()  #get first line and split by whitespace
                    coordinates = [
                        float(lineData[0]),
                        float(lineData[1]),
                        float(lineData[2])
                    ]
                    fiducialNode.AddFiducialFromArray(coordinates, str(
                        landmark))  #insert fiducial named by landmark number

                slicer.mrmlScene.AddNode(fiducialNode)
                fiducialNode.SetName(
                    subject.split()
                    [0])  # set name to subject name, removing new line char
                path = os.path.join(outputDirectory,
                                    subject.split()[0] + '.fcsv')
                slicer.util.saveNode(fiducialNode, path)
                slicer.mrmlScene.RemoveNode(
                    fiducialNode)  #remove node from scene
                #fiducialNode.RemoveAllControlPoints() # remove all landmarks from node (new markups version)
                fiducialNode.RemoveAllMarkups(
                )  # remove all landmarks from node
        logging.info('Processing completed')

        return True
コード例 #44
0
  def test_3D_parentTransform(self):
    """ Test that the interaction widget works with a parent transform.
    """
    #self.delayDisplay('Starting test_3D_parentTransform')
    #
    # Setup:
    #  - Use a markup fiducial node
    #  - Create a parent transform
    #  - Create another transform under the parent transform
    #

    markupNode = slicer.mrmlScene.AddNode(slicer.vtkMRMLMarkupsFiducialNode())
    markupNode.AddFiducial(500.0, -1000.0, 0.0)
    markupNode.AddFiducial(1000.0, 1000.0, 200.0)
    markupNode.AddFiducial(-1500.0, -200.0, -100.0)

    logic = SlicerTransformInteractionTest1Logic()
    parentNode, parendDisplayNode = logic.addTransform()

    leafNode, 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()

    #
    # Test the leaf transform (that has a parent) in a few situations
    #

    # Test the transform with just the parent (that is identity for now)
    leafNode.SetAndObserveTransformNodeID(parentNode.GetID())
    tdNode.UpdateEditorBounds()
    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)

    # Set an actual transform on the parent
    parentTransform = vtk.vtkTransform()
    move = [51.0, -27.0, 3.3]
    scale = [2.0, 7.0, 3.0]
    parentTransform.Translate(move)
    parentTransform.Scale(scale[0], scale[1], scale[2])
    parentTransform.RotateZ(90)
    parentTransform.RotateX(90)
    parentNode.ApplyTransformMatrix(parentTransform.GetMatrix())

    expectedTransformWithParent = [
      [0.0,   0.0, 200.0,  51.0],
      [700.0, 0.0,   0.0, -27.0],
      [0.0, 300.0,   0.0,   3.3],
      [0.0,   0.0,   0.0,   1.0],
    ]
    representation.GetTransform(transform)
    self.assertTransform(transform, expectedTransformWithParent)

    # Set the markup node under the leaf transform
    markupNode.SetAndObserveTransformNodeID(leafNode.GetID())
    tdNode.UpdateEditorBounds()
    expectedMarkupTransformWithParent = [
      [0.0,     0.0, 1200.0,  151.0],
      [35000.0, 0.0,   0.0, -1777.0],
      [0.0, 12000.0,   0.0,   3.3],
      [0.0,     0.0,   0.0,   1.0],
    ]
    representation.GetTransform(transform)
    self.assertTransform(transform, expectedMarkupTransformWithParent)

    # Set the parent transform to identity
    parentNode.ApplyTransformMatrix(parentTransform.GetLinearInverse().GetMatrix())
    expectedMarkupTransform = [
      [5000.0,   0.0,   0.0, -250.0],
      [0.0,   4000.0,   0.0,    0.0],
      [0.0,      0.0, 600.0,   50.0],
      [0.0,     0.0,    0.0,   1.0],
    ]
    representation.GetTransform(transform)
    self.assertTransform(transform, expectedMarkupTransform)
コード例 #45
0
  def run(self):
    """
    Run the actual algorithm
    """
    print('Running test of the markups in different views')

    #
    # first load the data
    #
    import SampleData
    sampleDataLogic = SampleData.SampleDataLogic()
    print("Getting MR Head Volume")
    mrHeadVolume = sampleDataLogic.downloadMRHead()

    #
    # link the viewers
    #
    sliceLogic = slicer.app.layoutManager().sliceWidget('Red').sliceLogic()
    compositeNode = sliceLogic.GetSliceCompositeNode()
    compositeNode.SetLinkedControl(1)

    #
    # MR Head in the background
    #
    sliceLogic.StartSliceCompositeNodeInteraction(1)
    compositeNode.SetBackgroundVolumeID(mrHeadVolume.GetID())
    sliceLogic.EndSliceCompositeNodeInteraction()

    #
    # switch to conventional layout
    #
    lm = slicer.app.layoutManager()
    lm.setLayout(2)

    # create a fiducial list
    displayNode = slicer.vtkMRMLMarkupsDisplayNode()
    slicer.mrmlScene.AddNode(displayNode)
    fidNode = slicer.vtkMRMLMarkupsFiducialNode()
    slicer.mrmlScene.AddNode(fidNode)
    fidNode.SetAndObserveDisplayNodeID(displayNode.GetID())

    # make it active
    selectionNode = slicer.mrmlScene.GetNodeByID("vtkMRMLSelectionNodeSingleton")
    if (selectionNode is not None):
      selectionNode.SetReferenceActivePlaceNodeID(fidNode.GetID())

    # add some known points to it
    eye1 = [33.4975, 79.4042, -10.2143]
    eye2 = [-31.283, 80.9652, -16.2143]
    nose = [4.61944, 114.526, -33.2143]
    index = fidNode.AddFiducialFromArray(eye1)
    fidNode.SetNthFiducialLabel(index, "eye-1")
    index = fidNode.AddFiducialFromArray(eye2)
    fidNode.SetNthFiducialLabel(index, "eye-2")
    # hide the second eye as a test of visibility flags
    fidNode.SetNthFiducialVisibility(index, 0)
    index = fidNode.AddFiducialFromArray(nose)
    fidNode.SetNthFiducialLabel(index, "nose")

    self.logicDelayDisplay("Placed 3 fiducials")

    # self.printViewAndSliceNodes()

    if self.widgetVisible(fidNode, 'vtkMRMLViewNode1') == 0:
      self.logicDelayDisplay("Test failed: widget is not visible in view 1")
      # self.printViewNodeIDs(displayNode)
      return False

    #
    # switch to 2 3D views layout
    #
    lm.setLayout(15)
    self.logicDelayDisplay("Switched to 2 3D views")
    # self.printViewAndSliceNodes()

    if self.widgetVisible(fidNode, 'vtkMRMLViewNode1') == 0 or self.widgetVisible(fidNode, 'vtkMRMLViewNode2') == 0:
      self.logicDelayDisplay("Test failed: widget is not visible in view 1 and 2")
      # self.printViewNodeIDs(displayNode)
      return False

    #
    # show only in view 2
    #
    displayNode.AddViewNodeID("vtkMRMLViewNode2")
    self.logicDelayDisplay("Showing only in view 2")
    if self.widgetVisible(fidNode, 'vtkMRMLViewNode1') == 1:
      self.logicDelayDisplay("Test failed: widget is not supposed to be visible in view 1")
      # self.printViewNodeIDs(displayNode)
      return False
    if self.widgetVisible(fidNode, 'vtkMRMLViewNode2') == 0:
      self.logicDelayDisplay("Test failed: widget is not visible in view 2")
      # self.printViewNodeIDs(displayNode)
      return False

    #
    # remove it so show in all
    #
    displayNode.RemoveAllViewNodeIDs()
    self.logicDelayDisplay("Showing in both views")
    if self.widgetVisible(fidNode, 'vtkMRMLViewNode1') == 0 or self.widgetVisible(fidNode, 'vtkMRMLViewNode2') == 0:
      self.logicDelayDisplay("Test failed: widget is not visible in view 1 and 2")
      self.printViewNodeIDs(displayNode)
      return False

    #
    # show only in view 1
    #
    displayNode.AddViewNodeID("vtkMRMLViewNode1")
    self.logicDelayDisplay("Showing only in view 1")
    if self.widgetVisible(fidNode, 'vtkMRMLViewNode2') == 1:
      self.logicDelayDisplay("Test failed: widget is not supposed to be visible in view 2")
      # self.printViewNodeIDs(displayNode)
      return False
    if self.widgetVisible(fidNode, 'vtkMRMLViewNode1') == 0:
      self.logicDelayDisplay("Test failed: widget is not visible in view 1")
      # self.printViewNodeIDs(displayNode)
      return False

    # switch back to conventional
    lm.setLayout(2)
    self.logicDelayDisplay("Switched back to conventional layout")
    # self.printViewAndSliceNodes()

    # test of the visibility in slice views
    displayNode.RemoveAllViewNodeIDs()

    # jump to the last fiducial
    slicer.modules.markups.logic().JumpSlicesToNthPointInMarkup(fidNode.GetID(), index, 1)
    # refocus the 3D cameras as well
    slicer.modules.markups.logic().FocusCamerasOnNthPointInMarkup(fidNode.GetID(), index)

    # show only in red
    displayNode.AddViewNodeID('vtkMRMLSliceNodeRed')
    self.logicDelayDisplay("Show only in red slice")
    if self.widgetVisibleOnSlice(fidNode,'vtkMRMLSliceNodeRed') != 1:
      self.logicDelayDisplay("Test failed: widget not displayed on red slice")
      # self.printViewNodeIDs(displayNode)
      return False

    # remove all, add green
    # print 'before remove all, after added red'
    # self.printViewNodeIDs(displayNode)
    displayNode.RemoveAllViewNodeIDs()
    # print 'after removed all'
    # self.printViewNodeIDs(displayNode)
    displayNode.AddViewNodeID('vtkMRMLSliceNodeGreen')
    self.logicDelayDisplay('Show only in green slice')
    if self.widgetVisibleOnSlice(fidNode,'vtkMRMLSliceNodeRed') != 0 or self.widgetVisibleOnSlice(fidNode,'vtkMRMLSliceNodeGreen') != 1:
      self.logicDelayDisplay("Test failed: widget not displayed only on green slice")
      print '\tred = ',self.widgetVisibleOnSlice(fidNode,'vtkMRMLSliceNodeRed')
      print '\tgreen =',self.widgetVisibleOnSlice(fidNode,'vtkMRMLSliceNodeGreen')
      self.printViewNodeIDs(displayNode)
      return False

    return True
  def run(self,enableScreenshots=0,screenshotScaleFactor=1):
    """
    Run the actual algorithm
    """
    self.delayDisplay('Running test of the Neurosurgical Planning tutorial')

    self.enableScreenshots = enableScreenshots
    self.screenshotScaleFactor = screenshotScaleFactor

    # conventional layout
    lm = slicer.app.layoutManager()
    lm.setLayout(2)

    moduleSelector = slicer.util.mainWindow().moduleSelector()
    #
    # first load the data
    #
    if self.enableScreenshots == 1:
      # for the tutorial, do it through the welcome module
      moduleSelector.selectModule('Welcome')
      self.delayDisplay("Screenshot")
      self.takeScreenshot('NeurosurgicalPlanning-Welcome','Welcome module',-1)
    else:
      # otherwise show the sample data module
      moduleSelector.selectModule('SampleData')

    # use the sample data module logic to load data for the self test
    import SampleData
    sampleDataLogic = SampleData.SampleDataLogic()

    self.delayDisplay("Getting Baseline volume")
    baselineVolume = sampleDataLogic.downloadWhiteMatterExplorationBaselineVolume()

    self.delayDisplay("Getting DTI volume")
    dtiVolume = sampleDataLogic.downloadWhiteMatterExplorationDTIVolume()

    self.takeScreenshot('NeurosurgicalPlanning-Loaded','Data loaded',-1)

    #
    # link the viewers
    #

    if self.enableScreenshots == 1:
      # for the tutorial, pop up the linking control
      sliceController = slicer.app.layoutManager().sliceWidget("Red").sliceController()
      popupWidget = sliceController.findChild("ctkPopupWidget")
      if popupWidget != None:
        popupWidget.pinPopup(1)
        self.takeScreenshot('NeurosurgicalPlanning-Link','Link slice viewers',-1)
        popupWidget.pinPopup(0)

    sliceLogic = slicer.app.layoutManager().sliceWidget('Red').sliceLogic()
    compositeNode = sliceLogic.GetSliceCompositeNode()
    compositeNode.SetLinkedControl(1)

    #
    # baseline in the background
    #
    sliceLogic.StartSliceCompositeNodeInteraction(1)
    compositeNode.SetBackgroundVolumeID(baselineVolume.GetID())
    sliceLogic.EndSliceCompositeNodeInteraction()

    self.takeScreenshot('NeurosurgicalPlanning-Baseline','Baseline in background',-1)

    #
    # adjust window level on baseline
    #
    moduleSelector.selectModule('Volumes')
    baselineDisplay = baselineVolume.GetDisplayNode()
    baselineDisplay.SetAutoWindowLevel(0)
    baselineDisplay.SetWindow(2600)
    baselineDisplay.SetLevel(1206)
    self.takeScreenshot('NeurosurgicalPlanning-WindowLevel','Set W/L on baseline',-1)

    #
    # switch to red slice only
    #
    lm.setLayout(6)
    self.takeScreenshot('NeurosurgicalPlanning-RedSliceOnly','Set layout to Red Slice only',-1)

    #
    # segmentation of tumour
    #

    #
    # create a label map and set it for editing
    #
    volumesLogic = slicer.modules.volumes.logic()
    baselineVolumeLabel =  volumesLogic.CreateAndAddLabelVolume( slicer.mrmlScene, baselineVolume, baselineVolume.GetName() + '-label' )
    baselineDisplayNode = baselineVolumeLabel.GetDisplayNode()
    baselineDisplayNode.SetAndObserveColorNodeID('vtkMRMLColorTableNodeFileGenericAnatomyColors.txt')
    selectionNode = slicer.app.applicationLogic().GetSelectionNode()
    selectionNode.SetReferenceActiveVolumeID(baselineVolume.GetID())
    selectionNode.SetReferenceActiveLabelVolumeID(baselineVolumeLabel.GetID())
    slicer.app.applicationLogic().PropagateVolumeSelection(0)

    #
    # editor module
    #
    moduleSelector.selectModule('Editor')
    self.takeScreenshot('NeurosurgicalPlanning-Editor','Showing Editor Module',-1)

    # set the slice offset so drawing is right
    sliceNode = sliceLogic.GetSliceNode()
    sliceOffset = 58.7
    sliceNode.SetSliceOffset(sliceOffset)

    #
    # paint
    #
    parameterNode = EditUtil.getParameterNode()
    paintEffect = EditorLib.PaintEffectOptions()
    paintEffect.setMRMLDefaults()
    paintEffect.__del__()
    sliceWidget = lm.sliceWidget('Red')
    paintTool = EditorLib.PaintEffectTool(sliceWidget)
    self.takeScreenshot('NeurosurgicalPlanning-Paint','Paint tool in Editor Module',-1)

    #
    # paint in cystic part of tumor, using converstion from RAS coords to
    # avoid slice widget size differences
    #
    EditUtil.setLabel(293)
    displayCoords = self.rasToDisplay(-7.4, 71, sliceOffset)
    paintTool.paintAddPoint(displayCoords[0], displayCoords[1])
    displayCoords = self.rasToDisplay(-11, 73, sliceOffset)
    paintTool.paintAddPoint(displayCoords[0], displayCoords[1])
    displayCoords = self.rasToDisplay(-12, 85, sliceOffset)
    paintTool.paintAddPoint(displayCoords[0], displayCoords[1])
    displayCoords = self.rasToDisplay(-13, 91, sliceOffset)
    paintTool.paintAddPoint(displayCoords[0], displayCoords[1])
    displayCoords = self.rasToDisplay(-15, 78, sliceOffset)
    paintTool.paintAddPoint(displayCoords[0], displayCoords[1])
    paintTool.paintApply()
    self.takeScreenshot('NeurosurgicalPlanning-PaintCystic','Paint cystic part of tumor',-1)

    #
    # paint in solid part of tumor
    #
    EditUtil.setLabel(7)
    displayCoords = self.rasToDisplay(-0.5 , 118.5, sliceOffset)
    paintTool.paintAddPoint(displayCoords[0], displayCoords[1])
    displayCoords = self.rasToDisplay(-7.4 , 116, sliceOffset)
    paintTool.paintAddPoint(displayCoords[0], displayCoords[1])
    paintTool.paintApply()
    self.takeScreenshot('NeurosurgicalPlanning-PaintSolid','Paint solid part of tumor',-1)

    #
    # paint around the tumor
    #
    EditUtil.setLabel(295)
    rMax = 25
    rMin = -50
    aMax = 145
    aMin = 50
    rasStep = 5

    # draw the top and bottom
    for r in range(rMin, rMax, rasStep):
      displayCoords = self.rasToDisplay(r, aMin, sliceOffset)
      paintTool.paintAddPoint(displayCoords[0], displayCoords[1])
      displayCoords = self.rasToDisplay(r, aMax, sliceOffset)
      paintTool.paintAddPoint(displayCoords[0], displayCoords[1])
    # draw the left and right
    for a in range(aMin, aMax, rasStep):
      displayCoords = self.rasToDisplay(rMin, a, sliceOffset)
      paintTool.paintAddPoint(displayCoords[0], displayCoords[1])
      displayCoords = self.rasToDisplay(rMax, a, sliceOffset)
      paintTool.paintAddPoint(displayCoords[0], displayCoords[1])

    paintTool.paintApply()

    self.takeScreenshot('NeurosurgicalPlanning-PaintAround','Paint around tumor',-1)
    #
    # clean up after painting
    #
    paintTool.cleanup()
    paintTool = None

    #
    # Grow cut
    #
    growCutLogic = EditorLib.GrowCutEffectLogic(sliceWidget.sliceLogic())
    growCutLogic.growCut()
    self.takeScreenshot('NeurosurgicalPlanning-Growcut','Growcut',-1)

    #
    # Merge split volume
    #
    slicer.util.selectModule('Editor')
    slicer.util.findChildren(text='Split Merge Volume')[0].clicked()
    self.takeScreenshot('NeurosurgicalPlanning-SplitMerge','SplitMerge',-1)

    #
    # go to the data module
    #
    moduleSelector.selectModule('Data')
    self.takeScreenshot('NeurosurgicalPlanning-SplitMergeData','SplitMerge results in Data',-1)

    #
    # Ventricles Segmentation
    #

    moduleSelector.selectModule('Editor')
    #
    # select the label volume with the area around the tumor
    slicer.util.findChildren(name='PerStructureVolumesFrame')[0].collapsed = False
    treeView = slicer.util.findChildren(name='StructuresView')[0]
    selection = qt.QItemSelection()
    # selecting the last split volume in the third row
    row = 2
    rowStart = treeView.model().index(row,0)
    rowEnd = treeView.model().index(row,treeView.model().columnCount() - 1)
    # rowSel = qt.QItemSelection(rowStart, rowEnd)
    selection.select(rowStart, rowEnd)
    # backup: select the label map in the slice logic too
    baselinelabel295 = slicer.mrmlScene.GetFirstNodeByName("BaselineVolume-region 3-label")
    sliceLogic.StartSliceCompositeNodeInteraction(1)
    compositeNode.SetLabelVolumeID(baselinelabel295.GetID())
    sliceLogic.EndSliceCompositeNodeInteraction()
    self.takeScreenshot('NeurosurgicalPlanning-SelOutside','Select outside region',-1)

    #
    # Threshold tool
    #
    slicer.modules.EditorWidget.toolsBox.selectEffect('ThresholdEffect')
    parameterNode = EditUtil.getParameterNode()
    parameterNode.SetParameter('ThresholdEffect,min', str(1700))
    slicer.modules.EditorWidget.toolsBox.currentTools[0].apply()
    self.takeScreenshot('NeurosurgicalPlanning-Ventricles','Ventricles segmentation',-1)

    #
    # Save Islands
    #
    slicer.modules.EditorWidget.toolsBox.selectEffect('SaveIslandEffect')
    saveIslandLogic = EditorLib.SaveIslandEffectLogic(sliceWidget.sliceLogic())
    displayCoords = self.rasToDisplay(25.3, 5.8, sliceOffset)
    xy = (displayCoords[0], displayCoords[1])
    saveIslandLogic.saveIsland(xy)
    self.takeScreenshot('NeurosurgicalPlanning-SaveIsland','Ventricles save island',-1)

    #
    # Merge and build
    #
    slicer.util.findChildren(text='Merge And Build')[0].clicked()

    #
    # switch to conventional layout
    #
    lm.setLayout(2)
    self.takeScreenshot('NeurosurgicalPlanning-MergeAndBuild','Merged and built models',-1)

    #
    # Tractography label map seeding
    #

    #
    # select label volume with label 293, in the second row
    #
    row = 1
    rowStart = treeView.model().index(row,0)
    rowEnd = treeView.model().index(row,treeView.model().columnCount() - 1)
    # rowSel = qt.QItemSelection(rowStart, rowEnd)
    selection.select(rowStart, rowEnd)
    # backup: select the label map in the slice logic too
    baselinelabel293 = slicer.mrmlScene.GetFirstNodeByName("BaselineVolume-region 1-label")
    sliceLogic.StartSliceCompositeNodeInteraction(1)
    compositeNode.SetLabelVolumeID(baselinelabel293.GetID())
    sliceLogic.EndSliceCompositeNodeInteraction()
    self.takeScreenshot('NeurosurgicalPlanning-SelCystic','Select cystic region',-1)

    #
    # Dilate
    #
    slicer.modules.EditorWidget.toolsBox.selectEffect('DilateEffect')
    EditUtil.setLabel(293)
    self.takeScreenshot('NeurosurgicalPlanning-Dilate','Dilate tool',-1)
    # tutorial says to click apply three times
    for d in range (1,3):
      print d
      # slicer.util.findChildren(name='DilateEffectOptionsApply')[0].clicked()
      # slicer.modules.EditorWidget.toolsBox.currentTools[0].apply()
      slicer.modules.EditorWidget.toolsBox.currentOption.onApply()
    self.takeScreenshot('NeurosurgicalPlanning-Dilated','Dilated tumor',-1)

    #
    # Tractography Label Map Seeding module
    #
    moduleSelector.selectModule('TractographyLabelMapSeeding')
    self.takeScreenshot('NeurosurgicalPlanning-LabelMapSeedingModule','Showing Tractography Label Seeding Module',-1)
    tractographyLabelSeeding = slicer.modules.tractographylabelmapseeding
    parameters = {}
    parameters['InputVolume'] = dtiVolume.GetID()
    baselinelabel293 = slicer.mrmlScene.GetFirstNodeByName("BaselineVolume-region 1-label")
# VTK6 TODO - set 'InputROIPipelineInfo'
    parameters['InputROI'] = baselinelabel293.GetID()
    fibers = slicer.vtkMRMLFiberBundleNode()
    slicer.mrmlScene.AddNode(fibers)
    parameters['OutputFibers'] = fibers.GetID()
    parameters['UseIndexSpace'] = 1
    parameters['StoppingValue'] = 0.15
    parameters['ROIlabel'] = 293
    parameters['StoppingMode'] = 'FractionalAnisotropy'
    # defaults
    # parameters['ClTh'] = 0.3
    # parameters['MinimumLength'] = 20
    # parameters['MaximumLength'] = 800
    # parameters['StoppingCurvature'] = 0.7
    # parameters['IntegrationStepLength'] = 0.5
    # parameters['SeedSpacing'] = 2
    # and run it
    slicer.cli.run(tractographyLabelSeeding, None, parameters)
    self.takeScreenshot('NeurosurgicalPlanning-LabelMapSeeding','Showing Tractography Label Seeding Results',-1)

    #
    # tractography fiducial seeding
    #
    moduleSelector.selectModule('TractographyInteractiveSeeding')
    self.takeScreenshot('NeurosurgicalPlanning-TIS','Showing Tractography Interactive Seeding Module',-1)

    # DTI in background
    sliceLogic.StartSliceCompositeNodeInteraction(1)
    compositeNode.SetBackgroundVolumeID(dtiVolume.GetID())
    sliceLogic.EndSliceCompositeNodeInteraction()

    # DTI visible in 3D
    sliceNode = sliceLogic.GetSliceNode()
    sliceLogic.StartSliceNodeInteraction(128)
    sliceNode.SetSliceVisible(1)
    sliceLogic.EndSliceNodeInteraction()

    self.takeScreenshot('NeurosurgicalPlanning-TIS-DTI','DTI volume with Tractography Interactive Seeding Module',-1)

    # place a fiducial
    displayNode = slicer.vtkMRMLMarkupsDisplayNode()
    slicer.mrmlScene.AddNode(displayNode)
    fidNode = slicer.vtkMRMLMarkupsFiducialNode()
    fidNode.SetName('F')
    slicer.mrmlScene.AddNode(fidNode)
    fidNode.SetAndObserveDisplayNodeID(displayNode.GetID())
    r = 28.338526
    a = 34.064367
    s = sliceOffset
    fidNode.AddFiducial(r,a,s)

    # make it active
    selectionNode = slicer.mrmlScene.GetNodeByID("vtkMRMLSelectionNodeSingleton")
    if (selectionNode != None):
      selectionNode.SetReferenceActivePlaceNodeID(fidNode.GetID())

    self.takeScreenshot('NeurosurgicalPlanning-TIS-Fid1','Fiducial in Tractography Interactive Seeding Module',-1)


    # set up the arguments
    wr = slicer.modules.tractographyinteractiveseeding.widgetRepresentation()
    wr.setDiffusionTensorVolumeNode(dtiVolume)
    # create a fiber bundle
    fiducialFibers = slicer.vtkMRMLFiberBundleNode()
    slicer.mrmlScene.AddNode(fiducialFibers)
    wr.setFiberBundleNode(fiducialFibers)
    wr.setSeedingNode(fidNode)
    wr.setMinimumPath(10)
    wr.setStoppingValue(0.15)

    self.takeScreenshot('NeurosurgicalPlanning-TIS-Args','Tractography Interactive Seeding arguments',-1)

    self.delayDisplay("Moving the fiducial")
    for y in range(-20, 100, 5):
      msg = "Moving the fiducial to y = " + str(y)
      self.delayDisplay(msg,250)
      fidNode.SetNthFiducialPosition(0, r, y, s)

    self.takeScreenshot('NeurosurgicalPlanning-TIS-Moved','Moved fiducial and did Tractography Interactive Seeding',-1)

    return True
コード例 #47
0
    def run(self):
        """
    Run the actual algorithm
    """
        print('Running test of the markups in different views')

        #
        # first load the data
        #
        print("Getting MR Head Volume")
        import SampleData
        mrHeadVolume = SampleData.downloadSample("MRHead")

        #
        # link the viewers
        #
        sliceLogic = slicer.app.layoutManager().sliceWidget('Red').sliceLogic()
        compositeNode = sliceLogic.GetSliceCompositeNode()
        compositeNode.SetLinkedControl(1)

        #
        # MR Head in the background
        #
        sliceLogic.StartSliceCompositeNodeInteraction(1)
        compositeNode.SetBackgroundVolumeID(mrHeadVolume.GetID())
        sliceLogic.EndSliceCompositeNodeInteraction()

        #
        # switch to conventional layout
        #
        lm = slicer.app.layoutManager()
        lm.setLayout(2)

        # create a fiducial list
        displayNode = slicer.vtkMRMLMarkupsDisplayNode()
        slicer.mrmlScene.AddNode(displayNode)
        fidNode = slicer.vtkMRMLMarkupsFiducialNode()
        slicer.mrmlScene.AddNode(fidNode)
        fidNode.SetAndObserveDisplayNodeID(displayNode.GetID())

        # make it active
        selectionNode = slicer.mrmlScene.GetNodeByID(
            "vtkMRMLSelectionNodeSingleton")
        if (selectionNode is not None):
            selectionNode.SetReferenceActivePlaceNodeID(fidNode.GetID())

        # add some known points to it
        eye1 = [33.4975, 79.4042, -10.2143]
        eye2 = [-31.283, 80.9652, -16.2143]
        nose = [4.61944, 114.526, -33.2143]
        index = fidNode.AddFiducialFromArray(eye1)
        fidNode.SetNthFiducialLabel(index, "eye-1")
        index = fidNode.AddFiducialFromArray(eye2)
        fidNode.SetNthFiducialLabel(index, "eye-2")
        # hide the second eye as a test of visibility flags
        fidNode.SetNthFiducialVisibility(index, 0)
        index = fidNode.AddFiducialFromArray(nose)
        fidNode.SetNthFiducialLabel(index, "nose")

        self.delayDisplay("Placed 3 fiducials")

        # self.printViewAndSliceNodes()

        if self.widgetVisible(fidNode, 'vtkMRMLViewNode1') == 0:
            self.delayDisplay("Test failed: widget is not visible in view 1")
            # self.printViewNodeIDs(displayNode)
            return False

        #
        # switch to 2 3D views layout
        #
        lm.setLayout(15)
        self.delayDisplay("Switched to 2 3D views")
        # self.printViewAndSliceNodes()

        if self.widgetVisible(fidNode,
                              'vtkMRMLViewNode1') == 0 or self.widgetVisible(
                                  fidNode, 'vtkMRMLViewNode2') == 0:
            self.delayDisplay(
                "Test failed: widget is not visible in view 1 and 2")
            # self.printViewNodeIDs(displayNode)
            return False

        #
        # show only in view 2
        #
        displayNode.AddViewNodeID("vtkMRMLViewNode2")
        self.delayDisplay("Showing only in view 2")
        if self.widgetVisible(fidNode, 'vtkMRMLViewNode1') == 1:
            self.delayDisplay(
                "Test failed: widget is not supposed to be visible in view 1")
            # self.printViewNodeIDs(displayNode)
            return False
        if self.widgetVisible(fidNode, 'vtkMRMLViewNode2') == 0:
            self.delayDisplay("Test failed: widget is not visible in view 2")
            # self.printViewNodeIDs(displayNode)
            return False

        #
        # remove it so show in all
        #
        displayNode.RemoveAllViewNodeIDs()
        self.delayDisplay("Showing in both views")
        if self.widgetVisible(fidNode,
                              'vtkMRMLViewNode1') == 0 or self.widgetVisible(
                                  fidNode, 'vtkMRMLViewNode2') == 0:
            self.delayDisplay(
                "Test failed: widget is not visible in view 1 and 2")
            self.printViewNodeIDs(displayNode)
            return False

        #
        # show only in view 1
        #
        displayNode.AddViewNodeID("vtkMRMLViewNode1")
        self.delayDisplay("Showing only in view 1")
        if self.widgetVisible(fidNode, 'vtkMRMLViewNode2') == 1:
            self.delayDisplay(
                "Test failed: widget is not supposed to be visible in view 2")
            # self.printViewNodeIDs(displayNode)
            return False
        if self.widgetVisible(fidNode, 'vtkMRMLViewNode1') == 0:
            self.delayDisplay("Test failed: widget is not visible in view 1")
            # self.printViewNodeIDs(displayNode)
            return False

        # switch back to conventional
        lm.setLayout(2)
        self.delayDisplay("Switched back to conventional layout")
        # self.printViewAndSliceNodes()

        # test of the visibility in slice views
        displayNode.RemoveAllViewNodeIDs()

        # jump to the last fiducial
        slicer.modules.markups.logic().JumpSlicesToNthPointInMarkup(
            fidNode.GetID(), index, 1)
        # refocus the 3D cameras as well
        slicer.modules.markups.logic().FocusCamerasOnNthPointInMarkup(
            fidNode.GetID(), index)

        # show only in red
        displayNode.AddViewNodeID('vtkMRMLSliceNodeRed')
        self.delayDisplay("Show only in red slice")
        if self.widgetVisibleOnSlice(fidNode, 'vtkMRMLSliceNodeRed') != 1:
            self.delayDisplay("Test failed: widget not displayed on red slice")
            # self.printViewNodeIDs(displayNode)
            return False

        # remove all, add green
        # print 'before remove all, after added red'
        # self.printViewNodeIDs(displayNode)
        displayNode.RemoveAllViewNodeIDs()
        # print 'after removed all'
        # self.printViewNodeIDs(displayNode)
        displayNode.AddViewNodeID('vtkMRMLSliceNodeGreen')
        self.delayDisplay('Show only in green slice')
        if self.widgetVisibleOnSlice(
                fidNode,
                'vtkMRMLSliceNodeRed') != 0 or self.widgetVisibleOnSlice(
                    fidNode, 'vtkMRMLSliceNodeGreen') != 1:
            self.delayDisplay(
                "Test failed: widget not displayed only on green slice")
            print '\tred = ', self.widgetVisibleOnSlice(
                fidNode, 'vtkMRMLSliceNodeRed')
            print '\tgreen =', self.widgetVisibleOnSlice(
                fidNode, 'vtkMRMLSliceNodeGreen')
            self.printViewNodeIDs(displayNode)
            return False

        return True
コード例 #48
0
    def run(self):
        """
    Run the actual algorithm
    """
        print('Running test of the markups in compare viewers')

        #
        # first load the data
        #
        import SampleData
        sampleDataLogic = SampleData.SampleDataLogic()
        print("Getting MR Head Volume")
        mrHeadVolume = sampleDataLogic.downloadMRHead()

        #
        # link the viewers
        #
        sliceLogic = slicer.app.layoutManager().sliceWidget('Red').sliceLogic()
        compositeNode = sliceLogic.GetSliceCompositeNode()
        compositeNode.SetLinkedControl(1)

        #
        # MR Head in the background
        #
        sliceLogic.StartSliceCompositeNodeInteraction(1)
        compositeNode.SetBackgroundVolumeID(mrHeadVolume.GetID())
        sliceLogic.EndSliceCompositeNodeInteraction()

        #
        # switch to conventional layout
        #
        lm = slicer.app.layoutManager()
        lm.setLayout(2)

        # create a fiducial list
        displayNode = slicer.vtkMRMLMarkupsDisplayNode()
        slicer.mrmlScene.AddNode(displayNode)
        fidNode = slicer.vtkMRMLMarkupsFiducialNode()
        slicer.mrmlScene.AddNode(fidNode)
        fidNode.SetAndObserveDisplayNodeID(displayNode.GetID())

        # make it active
        selectionNode = slicer.mrmlScene.GetNodeByID(
            "vtkMRMLSelectionNodeSingleton")
        if (selectionNode is not None):
            selectionNode.SetReferenceActivePlaceNodeID(fidNode.GetID())

        # add some known points to it
        eye1 = [33.4975, 79.4042, -10.2143]
        eye2 = [-31.283, 80.9652, -16.2143]
        nose = [4.61944, 114.526, -33.2143]
        index = fidNode.AddFiducialFromArray(eye1)
        fidNode.SetNthFiducialLabel(index, "eye-1")
        index = fidNode.AddFiducialFromArray(eye2)
        fidNode.SetNthFiducialLabel(index, "eye-2")
        index = fidNode.AddFiducialFromArray(nose)
        fidNode.SetNthFiducialLabel(index, "nose")

        self.logicDelayDisplay("Placed 3 fiducials")

        #
        # switch to 2 viewers compare layout
        #
        lm.setLayout(12)
        self.logicDelayDisplay("Switched to Compare 2 viewers")

        #
        # get compare slice composite node
        #
        compareLogic1 = slicer.app.layoutManager().sliceWidget(
            'Compare1').sliceLogic()
        compareCompositeNode1 = compareLogic1.GetSliceCompositeNode()

        # set MRHead in the background
        compareLogic1.StartSliceCompositeNodeInteraction(1)
        compareCompositeNode1.SetBackgroundVolumeID(mrHeadVolume.GetID())
        compareLogic1.EndSliceCompositeNodeInteraction()
        compareLogic1.FitSliceToAll()
        # make it visible in 3D
        compareLogic1.GetSliceNode().SetSliceVisible(1)

        # scroll to a fiducial location
        compareLogic1.StartSliceOffsetInteraction()
        compareLogic1.SetSliceOffset(eye1[2])
        compareLogic1.EndSliceOffsetInteraction()
        self.logicDelayDisplay("MH Head in background, scrolled to a fiducial")

        # scroll around through the range of points
        offset = nose[2]
        while offset < eye1[2]:
            compareLogic1.StartSliceOffsetInteraction()
            compareLogic1.SetSliceOffset(offset)
            compareLogic1.EndSliceOffsetInteraction()
            msg = "Scrolled to " + str(offset)
            self.logicDelayDisplay(msg, 250)
            offset += 1.0

        # switch back to conventional
        lm.setLayout(2)
        self.logicDelayDisplay("Switched back to conventional layout")

        # switch to compare grid
        lm.setLayout(23)
        compareLogic1.FitSliceToAll()
        self.logicDelayDisplay("Switched to Compare grid")

        # switch back to conventional
        lm.setLayout(2)
        self.logicDelayDisplay("Switched back to conventional layout")

        return True
コード例 #49
0
  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)
コード例 #50
0
  def findAxisOfMotion(self, origins):
    #Following guide from: http://sebastianraschka.com/Articles/2014_pca_step_by_step.html

    #scale factor for better display:
    scale = 100

    #Calculate mean position
    meanVector = [0, 0 ,0]
    for i in range(3):
      meanVector[i] = np.mean(origins[i, :])


    #Computing covariance matrix
    convMatrix = np.cov([origins[0, :], origins[1, :], origins[2, :]])

    #Get eigenvectors
    eig_val, eig_vec = np.linalg.eig(convMatrix)

    # Make a list of (eigenvalue, eigenvector) tuples
    eig_pairs = [(np.abs(eig_val[i]), eig_vec[:,i]) for i in range(len(eig_val))]

    # Sort the (eigenvalue, eigenvector) tuples from high to low
    eig_pairs.sort()
    # eig_pairs.reverse()
    matrix_w = np.hstack((eig_pairs[0][1].reshape(3, 1),
                          eig_pairs[1][1].reshape(3, 1),
                          eig_pairs[2][1].reshape(3, 1)))
    print('Matrix W:\n', matrix_w)

    #Create linear transform for contour propagation

    vtkMatrix = vtk.vtkMatrix4x4()
    transform = slicer.vtkMRMLLinearTransformNode()
    slicer.mrmlScene.AddNode(transform)

    for i in range(3):
      for j in range(3):
        vtkMatrix.SetElement(j, i, matrix_w[i, j])

    transform.SetAndObserveMatrixTransformFromParent(vtkMatrix)

    #Plot eigenvectors from mean position
    fiducials = slicer.vtkMRMLMarkupsFiducialNode()
    displayNode = slicer.vtkMRMLMarkupsDisplayNode()
        # vtkNew<vtkMRMLMarkupsFiducialStorageNode> wFStorageNode;
    slicer.mrmlScene.AddNode(displayNode)
    slicer.mrmlScene.AddNode(fiducials)
    fiducials.SetAndObserveDisplayNodeID(displayNode.GetID())
    fiducials.AddFiducialFromArray(meanVector, "Mean Position")
    for i in range(len(eig_vec)):
      # fiducials.AddFiducialFromArray(meanVector + scale * eig_vec[i], " P " + str(i+1))
      #Plot ruler
      ruler = slicer.vtkMRMLAnnotationRulerNode()
      displayRuler = slicer.vtkMRMLAnnotationLineDisplayNode()
      displayRuler.SetLabelVisibility(0)
      displayRuler.SetMaxTicks(0)
      displayRuler.SetLineWidth(5)
      slicer.mrmlScene.AddNode(displayRuler)
      slicer.mrmlScene.AddNode(ruler)
      ruler.SetAndObserveDisplayNodeID(displayRuler.GetID())
      ruler.SetPosition1(meanVector)
      ruler.SetPosition2(meanVector + scale * eig_vec[i])

    return matrix_w  
コード例 #51
0
 def onImageChanged2(self):
   self.InputRegistrationTransformNodeX = slicer.vtkMRMLLinearTransformNode()
   slicer.mrmlScene.AddNode(self.InputRegistrationTransformNodeX)
   if self.imageNode2 is not None: 
     self.imageNode2.SetAndObserveTransformNodeID(None) 
     self.imageNode2 = None 
     self.imageNode2 = self.imageSelector2.currentNode()
     if self.imageNode2 is None: 
       print('Please select the right volume')
     if self.imageNode2 is not None:
       self.cropping = 1 
       self.imageNode2 = self.imageSelector2.currentNode()
       self.clippingModel2 = slicer.vtkMRMLModelNode()
       self.clippingModel.SetName('Clipping Model 2')
       slicer.mrmlScene.AddNode(self.clippingModel2)
       self.displayNode2 = slicer.vtkMRMLMarkupsDisplayNode()
       slicer.mrmlScene.AddNode(self.displayNode2)
       self.inputMarkup2 = slicer.vtkMRMLMarkupsFiducialNode()
       self.inputMarkup2.SetName('C')
       slicer.mrmlScene.AddNode(self.inputMarkup2)
       self.inputMarkup2.SetAndObserveDisplayNodeID(self.displayNode2.GetID())
       self.inputMarkup2.AddFiducial(234,509,-0.5)
       self.inputMarkup2.AddFiducial(234,509,0.0)
       self.inputMarkup2.AddFiducial(500,130,0)
       self.inputMarkup2.AddFiducial(242,36,0)
       self.inputMarkup2.AddFiducial(-26,162,0)
       self.inputMarkup2.SetDisplayVisibility(0)
       self.outputVolume2 = slicer.vtkMRMLScalarVolumeNode()
       slicer.mrmlScene.AddNode(self.outputVolume2) 
       self.logic.updateModelFromMarkup(self.inputMarkup2,self.clippingModel2)
       self.logic.clipVolumeWithModel(self.imageNode2, self.clippingModel2, True, 255, self.outputVolume2)
       self.logic.showInSliceViewers(self.outputVolume2, ["Yellow"])
       self.cropping == 0       
       self.rightMat.SetElement(0,0,0)
       self.rightMat.SetElement(2,0,-1)
       self.rightMat.SetElement(1,1,-1)
       self.rightMat.SetElement(0,2,-1)
       self.rightMat.SetElement(2,2,0)
       self.rightMat.SetElement(1,3,520)
       self.rightMat.SetElement(2,3,230)
       self.rightTransform.PostMultiply()
       self.rightTransform.Identity()
       self.rightTransform.Concatenate(self.rightMat)
       self.outputVolume2.GetDisplayNode().SetAutoWindowLevel(0)
       self.outputVolume2.GetDisplayNode().SetWindowLevelMinMax(25,100)
       self.yellowWidget.sliceLogic().GetSliceCompositeNode().SetBackgroundVolumeID(self.outputVolume2.GetID())
       self.resliceLogic.SetDriverForSlice(self.outputVolume2.GetID(), slicer.mrmlScene.GetNodeByID('vtkMRMLSliceNodeYellow'))
       self.resliceLogic.SetModeForSlice(self.resliceLogic.MODE_TRANSVERSE, slicer.mrmlScene.GetNodeByID('vtkMRMLSliceNodeYellow'))
       self.clippingModel2.SetDisplayVisibility(False)
       slicer.app.layoutManager().sliceWidget('Yellow').sliceLogic().GetSliceNode().SetSliceVisible(True)
       slicer.app.layoutManager().sliceWidget("Yellow").sliceController().fitSliceToBackground()
       self.outputVolume2.SetAndObserveTransformNodeID(self.InputRegistrationTransformNodeX.GetID())
       self.InputRegistrationTransformNodeX.SetMatrixTransformToParent(self.rightTransform.GetMatrix())
   if self.imageNode2 is None:
     self.cropping = 1 
     self.imageNode2 = self.imageSelector2.currentNode()
     self.clippingModel2 = slicer.vtkMRMLModelNode()
     self.clippingModel.SetName('Clipping Model 2')
     slicer.mrmlScene.AddNode(self.clippingModel2)
     self.displayNode2 = slicer.vtkMRMLMarkupsDisplayNode()
     slicer.mrmlScene.AddNode(self.displayNode2)
     self.inputMarkup2 = slicer.vtkMRMLMarkupsFiducialNode()
     self.inputMarkup2.SetName('C')
     slicer.mrmlScene.AddNode(self.inputMarkup2)
     self.inputMarkup2.SetAndObserveDisplayNodeID(self.displayNode2.GetID())
     self.inputMarkup2.AddFiducial(234,509,-0.5)
     self.inputMarkup2.AddFiducial(234,509,0.0)
     self.inputMarkup2.AddFiducial(500,130,0)
     self.inputMarkup2.AddFiducial(242,36,0)
     self.inputMarkup2.AddFiducial(-26,162,0)
     self.inputMarkup2.SetDisplayVisibility(0)
     self.outputVolume2 = slicer.vtkMRMLScalarVolumeNode()
     slicer.mrmlScene.AddNode(self.outputVolume2) 
     self.logic.updateModelFromMarkup(self.inputMarkup2,self.clippingModel2)
     self.logic.clipVolumeWithModel(self.imageNode2, self.clippingModel2, True, 255, self.outputVolume2)
     self.logic.showInSliceViewers(self.outputVolume2, ["Yellow"])
     self.cropping = 0       
     self.rightMat.SetElement(0,0,0)
     self.rightMat.SetElement(2,0,-1)
     self.rightMat.SetElement(1,1,-1)
     self.rightMat.SetElement(0,2,-1)
     self.rightMat.SetElement(2,2,0)
     self.rightMat.SetElement(1,3,520)
     self.rightMat.SetElement(2,3,230)
     self.rightTransform.PostMultiply()
     self.rightTransform.Identity()
     self.rightTransform.Concatenate(self.rightMat)
     self.outputVolume2.GetDisplayNode().SetAutoWindowLevel(0)
     self.outputVolume2.GetDisplayNode().SetWindowLevelMinMax(25,100)
     self.yellowWidget.sliceLogic().GetSliceCompositeNode().SetBackgroundVolumeID(self.outputVolume2.GetID())
     self.resliceLogic.SetDriverForSlice(self.outputVolume2.GetID(), slicer.mrmlScene.GetNodeByID('vtkMRMLSliceNodeYellow'))
     self.resliceLogic.SetModeForSlice(self.resliceLogic.MODE_TRANSVERSE, slicer.mrmlScene.GetNodeByID('vtkMRMLSliceNodeYellow'))
     self.clippingModel2.SetDisplayVisibility(False)
     slicer.app.layoutManager().sliceWidget('Yellow').sliceLogic().GetSliceNode().SetSliceVisible(True)
     slicer.app.layoutManager().sliceWidget("Yellow").sliceController().fitSliceToBackground()
     self.outputVolume2.SetAndObserveTransformNodeID(self.InputRegistrationTransformNodeX.GetID())
     self.InputRegistrationTransformNodeX.SetMatrixTransformToParent(self.rightTransform.GetMatrix())
コード例 #52
0
    def run(self, enableScreenshots=0, screenshotScaleFactor=1):
        """
    Run the actual algorithm
    """
        self.delayDisplay(
            'Running test of the Neurosurgical Planning tutorial')

        self.enableScreenshots = enableScreenshots
        self.screenshotScaleFactor = screenshotScaleFactor

        # conventional layout
        lm = slicer.app.layoutManager()
        lm.setLayout(2)

        moduleSelector = slicer.util.mainWindow().moduleSelector()
        #
        # first load the data
        #
        if self.enableScreenshots == 1:
            # for the tutorial, do it through the welcome module
            moduleSelector.selectModule('Welcome')
            self.delayDisplay("Screenshot")
            self.takeScreenshot('NeurosurgicalPlanning-Welcome',
                                'Welcome module', -1)
        else:
            # otherwise show the sample data module
            moduleSelector.selectModule('SampleData')

        # use the sample data module logic to load data for the self test
        import SampleData
        sampleDataLogic = SampleData.SampleDataLogic()

        self.delayDisplay("Getting Baseline volume")
        baselineVolume = sampleDataLogic.downloadWhiteMatterExplorationBaselineVolume(
        )

        self.delayDisplay("Getting DTI volume")
        dtiVolume = sampleDataLogic.downloadWhiteMatterExplorationDTIVolume()

        self.takeScreenshot('NeurosurgicalPlanning-Loaded', 'Data loaded', -1)

        #
        # create a label map and set it for editing
        #
        volumesLogic = slicer.modules.volumes.logic()
        baselineVolumeLabel = volumesLogic.CreateAndAddLabelVolume(
            slicer.mrmlScene, baselineVolume,
            baselineVolume.GetName() + '-label')
        baselineDisplayNode = baselineVolumeLabel.GetDisplayNode()
        baselineDisplayNode.SetAndObserveColorNodeID(
            'vtkMRMLColorTableNodeFileGenericAnatomyColors.txt')
        selectionNode = slicer.app.applicationLogic().GetSelectionNode()
        selectionNode.SetReferenceActiveVolumeID(baselineVolume.GetID())
        selectionNode.SetReferenceActiveLabelVolumeID(
            baselineVolumeLabel.GetID())
        slicer.app.applicationLogic().PropagateVolumeSelection(0)

        data = slicer.util.array(baselineVolume.GetName() + "-label")
        data[6:15, 110:140, 130:160] = 293

        #
        # link the viewers
        #

        if self.enableScreenshots == 1:
            # for the tutorial, pop up the linking control
            sliceController = slicer.app.layoutManager().sliceWidget(
                "Red").sliceController()
            popupWidget = sliceController.findChild("ctkPopupWidget")
            if popupWidget is not None:
                popupWidget.pinPopup(1)
                self.takeScreenshot('NeurosurgicalPlanning-Link',
                                    'Link slice viewers', -1)
                popupWidget.pinPopup(0)

        #
        # Tractography Label Map Seeding module
        #
        moduleSelector.selectModule('TractographyLabelMapSeeding')
        self.takeScreenshot('NeurosurgicalPlanning-LabelMapSeedingModule',
                            'Showing Tractography Label Seeding Module', -1)
        tractographyLabelSeeding = slicer.modules.tractographylabelmapseeding
        parameters = {}
        parameters['InputVolume'] = dtiVolume.GetID()
        baselinelabel293 = slicer.mrmlScene.GetFirstNodeByName(
            "BaselineVolume-label")
        # VTK6 TODO - set 'InputROIPipelineInfo'
        parameters['InputROI'] = baselinelabel293.GetID()
        fibers = slicer.vtkMRMLFiberBundleNode()
        slicer.mrmlScene.AddNode(fibers)
        parameters['OutputFibers'] = fibers.GetID()
        parameters['UseIndexSpace'] = 1
        parameters['StoppingValue'] = 0.15
        parameters['ROIlabel'] = 293
        parameters['ThresholdMode'] = 'FractionalAnisotropy'
        # defaults
        # parameters['ClTh'] = 0.3
        # parameters['MinimumLength'] = 20
        # parameters['MaximumLength'] = 800
        # parameters['StoppingCurvature'] = 0.7
        # parameters['IntegrationStepLength'] = 0.5
        # parameters['SeedSpacing'] = 2
        # and run it
        slicer.cli.run(tractographyLabelSeeding, None, parameters)
        self.takeScreenshot('NeurosurgicalPlanning-LabelMapSeeding',
                            'Showing Tractography Label Seeding Results', -1)

        #
        # tractography fiducial seeding
        #
        moduleSelector.selectModule('TractographyInteractiveSeeding')
        self.takeScreenshot('NeurosurgicalPlanning-TIS',
                            'Showing Tractography Interactive Seeding Module',
                            -1)

        # DTI in background
        sliceLogic = slicer.app.layoutManager().sliceWidget('Red').sliceLogic()
        sliceLogic.StartSliceCompositeNodeInteraction(1)
        compositeNode = sliceLogic.GetSliceCompositeNode()
        compositeNode.SetBackgroundVolumeID(dtiVolume.GetID())
        sliceLogic.EndSliceCompositeNodeInteraction()

        # DTI visible in 3D
        sliceNode = sliceLogic.GetSliceNode()
        sliceLogic.StartSliceNodeInteraction(128)
        sliceNode.SetSliceVisible(1)
        sliceLogic.EndSliceNodeInteraction()

        self.takeScreenshot(
            'NeurosurgicalPlanning-TIS-DTI',
            'DTI volume with Tractography Interactive Seeding Module', -1)

        # place a fiducial
        displayNode = slicer.vtkMRMLMarkupsDisplayNode()
        slicer.mrmlScene.AddNode(displayNode)
        fidNode = slicer.vtkMRMLMarkupsFiducialNode()
        fidNode.SetName('F')
        slicer.mrmlScene.AddNode(fidNode)
        fidNode.SetAndObserveDisplayNodeID(displayNode.GetID())
        r = 28.338526
        a = 34.064367
        sliceOffset = 58.7
        s = sliceOffset
        fidNode.AddFiducial(r, a, s)

        # make it active
        selectionNode = slicer.mrmlScene.GetNodeByID(
            "vtkMRMLSelectionNodeSingleton")
        if (selectionNode is not None):
            selectionNode.SetReferenceActivePlaceNodeID(fidNode.GetID())

        self.takeScreenshot(
            'NeurosurgicalPlanning-TIS-Fid1',
            'Fiducial in Tractography Interactive Seeding Module', -1)

        # set up the arguments
        wr = slicer.modules.tractographyinteractiveseeding.widgetRepresentation(
        )
        wr.setDiffusionTensorVolumeNode(dtiVolume)
        # create a fiber bundle
        fiducialFibers = slicer.vtkMRMLFiberBundleNode()
        slicer.mrmlScene.AddNode(fiducialFibers)
        wr.setFiberBundleNode(fiducialFibers)
        wr.setSeedingNode(fidNode)
        wr.setMinimumPath(10)
        wr.setStoppingValue(0.15)

        self.takeScreenshot('NeurosurgicalPlanning-TIS-Args',
                            'Tractography Interactive Seeding arguments', -1)

        self.delayDisplay("Moving the fiducial")
        for y in range(-20, 100, 5):
            msg = "Moving the fiducial to y = " + str(y)
            self.delayDisplay(msg, 250)
            fidNode.SetNthFiducialPosition(0, r, y, s)

        self.takeScreenshot(
            'NeurosurgicalPlanning-TIS-Moved',
            'Moved fiducial and did Tractography Interactive Seeding', -1)

        return True
コード例 #53
0
    def run(self):
        """
        Run the actual algorithm
        """
        print('Running test of the markups in different views')

        #
        # first load the data
        #
        print("Getting MR Head Volume")
        import SampleData
        mrHeadVolume = SampleData.downloadSample("MRHead")

        #
        # link the viewers
        #
        sliceLogic = slicer.app.layoutManager().sliceWidget('Red').sliceLogic()
        compositeNode = sliceLogic.GetSliceCompositeNode()
        compositeNode.SetLinkedControl(1)

        #
        # MR Head in the background
        #
        sliceLogic.StartSliceCompositeNodeInteraction(1)
        compositeNode.SetBackgroundVolumeID(mrHeadVolume.GetID())
        sliceLogic.EndSliceCompositeNodeInteraction()

        #
        # switch to conventional layout
        #
        lm = slicer.app.layoutManager()
        lm.setLayout(2)

        # create a control points list
        fidNode = slicer.vtkMRMLMarkupsFiducialNode()
        slicer.mrmlScene.AddNode(fidNode)
        fidNode.CreateDefaultDisplayNodes()
        displayNode = fidNode.GetDisplayNode()

        # make it active
        selectionNode = slicer.mrmlScene.GetNodeByID(
            "vtkMRMLSelectionNodeSingleton")
        if (selectionNode is not None):
            selectionNode.SetReferenceActivePlaceNodeID(fidNode.GetID())

        fidNodeObserverTags = []
        self.nodeEvents = []
        observedEvents = [
            slicer.vtkMRMLMarkupsNode.PointPositionDefinedEvent,
            slicer.vtkMRMLMarkupsNode.PointPositionUndefinedEvent
        ]
        for eventId in observedEvents:
            fidNodeObserverTags.append(
                fidNode.AddObserver(
                    eventId,
                    lambda caller, event, eventId=eventId: self.
                    onRecordNodeEvent(caller, event, eventId)))

        # add some known points to it
        eye1 = [33.4975, 79.4042, -10.2143]
        eye2 = [-31.283, 80.9652, -16.2143]
        nose = [4.61944, 114.526, -33.2143]
        controlPointIndex = fidNode.AddControlPoint(eye1)
        slicer.nodeEvents = self.nodeEvents
        assert (len(self.nodeEvents) == 1)
        assert (self.nodeEvents[0] ==
                slicer.vtkMRMLMarkupsNode.PointPositionDefinedEvent)
        fidNode.SetNthControlPointLabel(controlPointIndex, "eye-1")
        controlPointIndex = fidNode.AddControlPoint(eye2)
        fidNode.SetNthControlPointLabel(controlPointIndex, "eye-2")
        # hide the second eye as a test of visibility flags
        fidNode.SetNthControlPointVisibility(controlPointIndex,
                                             controlPointIndex)
        controlPointIndex = fidNode.AddControlPoint(nose)
        fidNode.SetNthControlPointLabel(controlPointIndex, "nose")

        for tag in fidNodeObserverTags:
            fidNode.RemoveObserver(tag)

        slicer.util.delayDisplay("Placed 3 control points")

        # self.printViewAndSliceNodes()

        if not self.controlPointVisible3D(fidNode, 'vtkMRMLViewNode1',
                                          controlPointIndex):
            slicer.util.delayDisplay(
                "Test failed: widget is not visible in view 1")
            # self.printViewNodeIDs(displayNode)
            return False

        #
        # switch to 2 3D views layout
        #
        lm.setLayout(15)
        slicer.util.delayDisplay("Switched to 2 3D views")
        # self.printViewAndSliceNodes()

        controlPointIndex = 0

        slicer.modules.markups.logic().FocusCamerasOnNthPointInMarkup(
            fidNode.GetID(), controlPointIndex)

        if (not self.controlPointVisible3D(fidNode, 'vtkMRMLViewNode1',
                                           controlPointIndex)
                or not self.controlPointVisible3D(fidNode, 'vtkMRMLViewNode2',
                                                  controlPointIndex)):
            slicer.util.delayDisplay(
                "Test failed: widget is not visible in view 1 and 2")
            # self.printViewNodeIDs(displayNode)
            return False

        #
        # show only in view 2
        #
        displayNode.AddViewNodeID("vtkMRMLViewNode2")
        slicer.util.delayDisplay("Showing only in view 2")
        if self.controlPointVisible3D(fidNode, 'vtkMRMLViewNode1',
                                      controlPointIndex):
            slicer.util.delayDisplay(
                "Test failed: widget is not supposed to be visible in view 1")
            # self.printViewNodeIDs(displayNode)
            return False
        if not self.controlPointVisible3D(fidNode, 'vtkMRMLViewNode2',
                                          controlPointIndex):
            slicer.util.delayDisplay(
                "Test failed: widget is not visible in view 2")
            # self.printViewNodeIDs(displayNode)
            return False

        #
        # remove it so show in all
        #
        displayNode.RemoveAllViewNodeIDs()
        slicer.util.delayDisplay("Showing in both views")
        if (not self.controlPointVisible3D(fidNode, 'vtkMRMLViewNode1',
                                           controlPointIndex)
                or not self.controlPointVisible3D(fidNode, 'vtkMRMLViewNode2',
                                                  controlPointIndex)):
            slicer.util.delayDisplay(
                "Test failed: widget is not visible in view 1 and 2")
            self.printViewNodeIDs(displayNode)
            return False

        #
        # show only in view 1
        #
        displayNode.AddViewNodeID("vtkMRMLViewNode1")
        slicer.util.delayDisplay("Showing only in view 1")
        if self.controlPointVisible3D(fidNode, 'vtkMRMLViewNode2',
                                      controlPointIndex):
            slicer.util.delayDisplay(
                "Test failed: widget is not supposed to be visible in view 2")
            # self.printViewNodeIDs(displayNode)
            return False
        if not self.controlPointVisible3D(fidNode, 'vtkMRMLViewNode1',
                                          controlPointIndex):
            slicer.util.delayDisplay(
                "Test failed: widget is not visible in view 1")
            # self.printViewNodeIDs(displayNode)
            return False

        # switch back to conventional
        lm.setLayout(2)
        slicer.util.delayDisplay("Switched back to conventional layout")
        # self.printViewAndSliceNodes()

        # test of the visibility in slice views
        displayNode.RemoveAllViewNodeIDs()

        # jump to the last control point
        slicer.modules.markups.logic().JumpSlicesToNthPointInMarkup(
            fidNode.GetID(), controlPointIndex, True)
        # refocus the 3D cameras as well
        slicer.modules.markups.logic().FocusCamerasOnNthPointInMarkup(
            fidNode.GetID(), controlPointIndex)

        # show only in red
        displayNode.AddViewNodeID('vtkMRMLSliceNodeRed')
        slicer.util.delayDisplay("Show only in red slice")
        if not self.controlPointVisibleSlice(fidNode, 'vtkMRMLSliceNodeRed',
                                             controlPointIndex):
            slicer.util.delayDisplay(
                "Test failed: widget not displayed on red slice")
            # self.printViewNodeIDs(displayNode)
            return False

        # remove all, add green
        # print 'before remove all, after added red'
        # self.printViewNodeIDs(displayNode)
        displayNode.RemoveAllViewNodeIDs()
        # print 'after removed all'
        # self.printViewNodeIDs(displayNode)
        displayNode.AddViewNodeID('vtkMRMLSliceNodeGreen')
        slicer.util.delayDisplay('Show only in green slice')
        if (self.controlPointVisibleSlice(fidNode, 'vtkMRMLSliceNodeRed',
                                          controlPointIndex)
                or not self.controlPointVisibleSlice(
                    fidNode, 'vtkMRMLSliceNodeGreen', controlPointIndex)):
            slicer.util.delayDisplay(
                "Test failed: widget not displayed only on green slice")
            print(
                '\tred = ',
                self.controlPointVisibleSlice(fidNode, 'vtkMRMLSliceNodeRed',
                                              controlPointIndex))
            print(
                '\tgreen =',
                self.controlPointVisibleSlice(fidNode, 'vtkMRMLSliceNodeGreen',
                                              controlPointIndex))
            self.printViewNodeIDs(displayNode)
            return False

        return True