def onCalibrate2Button(self):
   self.inverseTransform = slicer.vtkMRMLLinearTransformNode()
   self.inverseTransform.SetName("InverseTransform")
   orientationTransform = self.IMUTransformNode
   self.inverseTransform.SetMatrixTransformFromParent(orientationTransform.GetMatrixTransformFromParent())
   self.inverseTransform.Inverse()
   slicer.mrmlScene.AddNode(self.inverseTransform)
           
   self.translateTransform = slicer.vtkMRMLLinearTransformNode()
   self.translateTransform.SetName("TranslateTransform")
   matrix = self.translateTransform.GetMatrixTransformFromParent()
   matrix.SetElement(1,3,-80)
   self.translateTransform.SetMatrixTransformToParent(matrix)
   slicer.mrmlScene.AddNode(self.translateTransform)
    
   self.probeTransform = slicer.vtkMRMLLinearTransformNode()
   self.probeTransform.SetName("ProbeTransform")
   matrix.SetElement(1,3,-60)
   self.probeTransform.SetMatrixTransformToParent(matrix)
   slicer.mrmlScene.AddNode(self.probeTransform)
   slicer.util.loadVolume("H:/src/S4Mods/UltrasoundSimulator/Data/Linear_probe.mha")
   self.maskVolumeNode = slicer.util.getNode("Linear_probe")
   self.maskVolumeNode.SetAndObserveTransformNodeID(self.probeTransform.GetID())
   
   slicer.util.loadVolume("H:/Data/CT/CT_abdominal_phantom.mha")
   self.volumeCurrentlyLoaded = slicer.util.getNode("CT_abdominal_phantom")
   
   self.volumeCurrentlyLoaded.SetAndObserveTransformNodeID(self.translateTransform.GetID())
   
   self.IMUTransformNode.SetAndObserveTransformNodeID(self.inverseTransform.GetID())
   self.translateTransform.SetAndObserveTransformNodeID(self.IMUTransformNode.GetID())
   
   self.volumeCurrentlyLoaded.GetScalarVolumeDisplayNode().SetAutoWindowLevel(False)
   self.volumeCurrentlyLoaded.GetScalarVolumeDisplayNode().SetWindowLevel(350, 40)
   
   #xyzOrigSampleVol = self.volumeCurrentlyLoaded.GetOrigin()
   #self.volumeCurrentlyLoaded.SetOrigin(xyzOrigSampleVol[0], xyzOrigSampleVol[1] - xyzOrigSampleVol[1] / 2, xyzOrigSampleVol[2])
   
   self.redSliceNode.SetSliceOrigin(0, -80, 0)
   self.redSliceNode.SetFieldOfView(180, 180,0)
   
   self.lm.setLayout(slicer.vtkMRMLLayoutNode.SlicerLayoutOneUpRedSliceView)
   
   self.redSliceCompositeNode.SetForegroundVolumeID(self.volumeCurrentlyLoaded.GetID())
   #self.redSliceFGLayer.SetVolumeNode(self.volumeCurrentlyLoaded)
   self.redSliceCompositeNode.SetForegroundOpacity(1.0)
   self.applicationLogic.PropagateForegroundVolumeSelection() # Not working
   
   self.redSliceCompositeNode.SetBackgroundVolumeID(self.maskVolumeNode.GetID())
   #self.redSliceBGLayer.SetVolumeNode(self.maskVolumeNode)    
   self.applicationLogic.PropagateBackgroundVolumeSelection() # Not working
   
   maskVolumeDisplayNode = self.maskVolumeNode.GetVolumeDisplayNode()
   maskVolumeDisplayNode.SetLowerThreshold(10)
   maskVolumeDisplayNode.ApplyThresholdOn ()
   
   '''
示例#2
0
  def connectWithTracker(self):
    self.connectorNode.SetTypeClient("localhost",18944)
    print("Status before start(): " + str(self.connectorNode.GetState()))
    self.startTracking()
    print("Connected with Plus Server in Slicelet Class ")
    print("Status after start(): " + str(self.connectorNode.GetState()))
    
    ## The nodes StylusTipToReference and ProbeToReference are added 
    stylusTipToReference=slicer.vtkMRMLLinearTransformNode()
    slicer.mrmlScene.AddNode(stylusTipToReference)
    stylusTipToReference.SetName("StylusTipToReference")

    probeToReference=slicer.vtkMRMLLinearTransformNode()
    slicer.mrmlScene.AddNode(probeToReference)
    probeToReference.SetName("ProbeToReference")
示例#3
0
  def cameraTransform(self):
    """Create the transform and the observer for the camera
    """
    transformName = 'Camera-To-RAS'
    transformNode = slicer.util.getNode(transformName)
    if not transformNode:
      # Create transform node
      transformNode = slicer.vtkMRMLLinearTransformNode()
      transformNode.SetName(transformName)
      slicer.mrmlScene.AddNode(transformNode)

    camera = self.cameraNode().GetCamera()

    import numpy
    position = numpy.array(camera.GetPosition())
    focalPoint = numpy.array(camera.GetFocalPoint())
    viewUp = numpy.array(camera.GetViewUp())
    viewPlaneNormal = numpy.array(camera.GetViewPlaneNormal())
    viewAngle = camera.GetViewAngle()
    viewRight = numpy.cross(viewUp,viewPlaneNormal)
    viewDistance = numpy.linalg.norm(focalPoint - position)

    cameraToRAS = vtk.vtkMatrix4x4()
    for row in xrange(3):
      cameraToRAS.SetElement(row, 0, viewRight[row])
      cameraToRAS.SetElement(row, 1, viewUp[row])
      cameraToRAS.SetElement(row, 2, viewPlaneNormal[row])
      cameraToRAS.SetElement(row, 3, position[row])

    transformNode.GetMatrixTransformToParent().DeepCopy(cameraToRAS)
    return transformNode,viewDistance
  def putInfo(self, caller, event):  # caller: vtkMRMLIGTLConnectorNode
    self.times1 = self.times1+1
    #print "********************"
    #print ("into caller", self.times1)

    if caller.IsA('vtkMRMLIGTLConnectorNode'):
      nInNode =  caller.GetNumberOfIncomingMRMLNodes()
      for i in range(nInNode):  # start from 0
        node = caller.GetIncomingMRMLNode(i)

        if node.IsA("vtkMRMLLinearTransformNode"):  # lineartransform node
          if node.GetName() == "CURRENT":  # node name the same robot controller part

            if self.receiveCurrentNode == None:
              self.receiveCurrentNode = slicer.vtkMRMLLinearTransformNode()
              self.receiveCurrentNode.SetName("receiveCurrent")
              slicer.mrmlScene.AddNode(self.receiveCurrentNode)

            else:
              mat4x4 = self.receiveCurrentNode.GetMatrixTransformToParent()
              self.matR = mat4x4.GetElement(0, 3)
              self.matA = mat4x4.GetElement(1, 3)
              self.matS = mat4x4.GetElement(2, 3)

              strCurrent = "(%.3f, %.3f, %.3f)" %(self.matR, self.matA, self.matS)
              self.lineEditCurrent.setText(strCurrent)
              self.connectNode.UnregisterIncomingMRMLNode(node)


        elif node.IsA("vtkMRMLTextNode"):  # text node
          if node.GetName() == "feedStatus":
            self.lineEditStatus.setText(node.GetText())
            self.lineEditStatus.setStyleSheet("background-color: green")
            self.connectNode.UnregisterIncomingMRMLNode(node)

          elif node.GetName() == "feedInfoRegistTime":
            self.lineEditRegistTime.setText(node.GetText())
            qt.QMessageBox.information(
              slicer.util.mainWindow(),
              "Slicer Python", "Registration Accepted!")
            self.connectNode.UnregisterIncomingMRMLNode(node)
            self.buttonSendTarget.setEnabled(True)

          elif node.GetName() == "feedTarget":
            print node.GetText()
            qt.QMessageBox.information(
              slicer.util.mainWindow(),
              "Slicer Python", "Target Accepted!")
            self.connectNode.UnregisterIncomingMRMLNode(node)
            self.buttonCurrent.setEnabled(True)

          elif node.GetName() == "feedTargetCell":
            print node.GetText()
            qt.QMessageBox.information(
              slicer.util.mainWindow(),
              "Slicer Python", "Cell Accepted!")
            self.connectNode.UnregisterIncomingMRMLNode(node)

        else:  # else to node.IsA
          print "no feedBack!!!!!"
示例#5
0
    def onSendButtonClicked(self):
        """Send the data to the Extral Devices which support the OpenIGTLink protocal"""
        # Get the number of the 'vtkMRMLIGTLConnectorNode'
        n = slicer.mrmlScene.GetNumberOfNodesByClass('vtkMRMLIGTLConnectorNode')
        # Set the 'vtkMRMLIGTLConnectorNode' node
        if n > 0:
            for i in range(n):
                if slicer.mrmlScene.GetNthNodeByClass(i, 'vtkMRMLIGTLConnectorNode').GetName() == 'Send-Data':
                    connectorNode = slicer.mrmlScene.GetNthNodeByClass(i, 'vtkMRMLIGTLConnectorNode')
                else:
                    connectorNode = slicer.vtkMRMLIGTLConnectorNode()
                    slicer.mrmlScene.AddNode(connectorNode)
                    connectorNode.SetName('Send-Data')
        else:
            connectorNode = slicer.vtkMRMLIGTLConnectorNode()
            slicer.mrmlScene.AddNode(connectorNode)
            connectorNode.SetName('Send-Data')

        hostname = self.hostnameLineEdit.text
        port = int(self.portLineEdit.text)
        connectorNode.SetTypeClient(hostname, port)
        checker = connectorNode.Start()

        #Get the number of the 'vtkMRMLLinearTransformNode'
        n = slicer.mrmlScene.GetNumberOfNodesByClass('vtkMRMLLinearTransformNode')
        #Set the 'vtkMRMLLinearTransformNode' node
        nodes = []
        for i in range(n):
            nodes.append(slicer.mrmlScene.GetNthNodeByClass(i, 'vtkMRMLLinearTransformNode'))
        for i in range(n):
            if nodes[i].GetName() == 'Result-Data':
                slicer.mrmlScene.RemoveNode(nodes[i])
        transformNode = slicer.vtkMRMLLinearTransformNode()
        slicer.mrmlScene.AddNode(transformNode)
        transformNode.SetName('Result-Data')

        connectorNode.RegisterOutgoingMRMLNode(transformNode)
        matrix = transformNode.GetMatrixTransformToParent()
        theta = self.result.angleRed
        omega = self.result.angleGreen
        phi = self.result.angleBlue
        e1 = numpy.cos(phi)*numpy.cos(omega)
        e2 = numpy.sin(phi)*numpy.cos(theta) + numpy.cos(phi)*numpy.sin(omega)*numpy.sin(theta)
        e3 = numpy.sin(phi)*numpy.sin(theta) - numpy.cos(phi)*numpy.sin(omega)*numpy.cos(theta)
        e4 = self.result.distance

        e5 = numpy.sin(phi)*numpy.cos(omega)*(-1)
        e6 = numpy.cos(phi)*numpy.cos(theta) - numpy.sin(phi)*numpy.sin(omega)*numpy.sin(theta)
        e7 = numpy.cos(phi)*numpy.sin(theta) + numpy.sin(phi)*numpy.sin(omega)*numpy.cos(theta)
        e8 = 0

        e9 = numpy.sin(omega)
        e10 = numpy.cos(omega)*numpy.sin(theta)*(-1)
        e11 = numpy.cos(omega)*numpy.cos(theta)
        e12 = 0
        
        time.sleep(1)
        matrix.DeepCopy((e1,e2,e3,e4,e5,e6,e7,e8,e9,e10,e11,e12,0,0,0,1))
        time.sleep(1)
        connectorNode.Stop()       
  def registerVolumes(self, fixedVolumeName, fixedTransformName, movingVolumeName, movingTransformName, registrationTransformName):
    # self.Registered = False
    
    # get the nodes
    fixedTransformNode = slicer.util.getNode(fixedTransformName)
    movingTransformNode = slicer.util.getNode(movingTransformName)   
    fixedVolumeNode = slicer.util.getNode(fixedVolumeName)
    movingVolumeNode = slicer.util.getNode(movingVolumeName)
    
    # check volumes
    if not fixedVolumeNode or not movingVolumeNode:
      print('Registration failed: the volume nodes are not set correctly')
      return False
    
    # setup the brainsfit CLI module
    parameters = {}
    parameters["fixedVolume"] = fixedVolumeNode.GetID()
    parameters["movingVolume"] = movingVolumeNode.GetID()
    parameters["useRigid"] = True
    
    transformNode = slicer.util.getNode(registrationTransformName);
    if not transformNode == None:
        slicer.mrmlScene.RemoveNode(transformNode) 
        
    registrationTransformNode = slicer.vtkMRMLLinearTransformNode()
    registrationTransformNode.SetName(registrationTransformName)
    slicer.mrmlScene.AddNode(registrationTransformNode)
    parameters["linearTransform"] = registrationTransformNode.GetID()
    parameters["initializeTransformMode"] = "useCenterOfHeadAlign"
    
    outputVolumeName = movingVolumeNode.GetName() + "_" + fixedVolumeNode.GetName();
    outputVolumeNode = slicer.util.getNode(outputVolumeName)
    if outputVolumeNode is None:
      outputVolumeNode = slicer.vtkMRMLScalarVolumeNode()
      slicer.mrmlScene.AddNode(outputVolumeNode)
      outputVolumeNode.SetName(outputVolumeName)

    parameters["outputVolume"] = outputVolumeNode.GetID()
    brainsfit = slicer.modules.brainsfit
    
    # run the registration
    cliBrainsFitRigidNode = slicer.cli.run(brainsfit, None, parameters)  
    # cliBrainsFitRigidNode = slicer.cli.run(brainsfit, None, parameters, True)  # El ultimo true es para que espere hasta la finalizacion
    
    waitCount = 0
    while cliBrainsFitRigidNode.GetStatusString() != 'Completed' and waitCount < self.REGISTRATION_TIMEOUT:
      self.delayDisplay("Register " + movingVolumeNode.GetName() + " to " + fixedVolumeNode.GetName() + "... %d" % waitCount)
      waitCount += 1
    self.delayDisplay("Register " + movingVolumeNode.GetName() + "to " + fixedVolumeNode.GetName() + " finished")
    qt.QApplication.restoreOverrideCursor()
    
    if not cliBrainsFitRigidNode:
      slicer.mrmlScene.RemoveNode(registrationTransformNode.GetID()) 
      print('Registration failed: Brainsfit module failed')
    else:  
      # attach the transform to the moving volume
      movingVolumeNode.SetAndObserveTransformNodeID(registrationTransformNode.GetID())
      pass
       
    return cliBrainsFitRigidNode
示例#7
0
 def testingData(self):
   """Load some default data for development
   and set up a transform and viewing scenario for it.
   """
   if not slicer.util.getNodes('MRHead*'):
     import os
     fileName = "C:/Work/data/MR-head.nrrd"
     vl = slicer.modules.volumes.logic()
     volumeNode = vl.AddArchetypeScalarVolume (fileName, "MRHead", 0)
   if not slicer.util.getNodes('neutral*'):
     import os
     fileName = "C:/Work/data/neutral.nrrd"
     vl = slicer.modules.volumes.logic()
     volumeNode = vl.AddArchetypeScalarVolume (fileName, "neutral", 0)
   if not slicer.util.getNodes('movingToFixed'):
     # Create transform node
     transform = slicer.vtkMRMLLinearTransformNode()
     transform.SetName('movingToFixed')
     slicer.mrmlScene.AddNode(transform)
   head = slicer.util.getNode('MRHead')
   self.neutral = slicer.util.getNode('neutral')
   self.transformNode = slicer.util.getNode('movingToFixed')
   self.neutral.SetAndObserveTransformNodeID(self.transformNode.GetID())
   compositeNodes = slicer.util.getNodes('vtkMRMLSliceCompositeNode*')
   for compositeNode in compositeNodes.values():
     compositeNode.SetBackgroundVolumeID(head.GetID())
     compositeNode.SetForegroundVolumeID(self.neutral.GetID())
     compositeNode.SetForegroundOpacity(0.5)
   applicationLogic = slicer.app.applicationLogic()
   applicationLogic.FitSliceToAll()
示例#8
0
 def createMovingLRSToFixedLRS(self, movingLRS = None):
   if movingLRS.GetNumberOfFiducials() < 3:
     logging.warning('Moving LRS fiducials list needs to contain at least three fiducials!')
     return False
     
   fixedLRS = slicer.util.getNode('FixedLRS')    
   if not fixedLRS:
     # Create FixedLRS markups node
     fixedLRS = slicer.vtkMRMLMarkupsFiducialNode()
     fixedLRS.SetName('FixedLRS')
     fixedLRS.AddFiducial(-100.0, 0.0, 0.0)
     fixedLRS.SetNthFiducialLabel(0, 'FixedL')
     fixedLRS.AddFiducial(100.0, 0.0, 0.0)
     fixedLRS.SetNthFiducialLabel(1, 'FixedR')
     fixedLRS.AddFiducial(0.0, 0.0, 100.0)
     fixedLRS.SetNthFiducialLabel(2, 'FixedS')
     slicer.mrmlScene.AddNode(fixedLRS)
     fixedLRS.SetDisplayVisibility(False)
  
   movingLRSToFixedLRS = slicer.util.getNode('MovingLRSToFixedLRS')    
   if not movingLRSToFixedLRS:
     # Create MovingLRSToFixedLRS transform node
     movingLRSToFixedLRS = slicer.vtkMRMLLinearTransformNode()
     movingLRSToFixedLRS.SetName('MovingLRSToFixedLRS')
     slicer.mrmlScene.AddNode(movingLRSToFixedLRS)
   
   self.fiducialRegistration(movingLRSToFixedLRS, fixedLRS, movingLRS, "Rigid")
   
   return True
示例#9
0
  def babyVolume(self,filePath=None,name='baby'):
    """Make a volume node as the target for the babys"""

    babyVolume = slicer.util.getNode(name)
    # create the volume for displaying the baby
    if not babyVolume:
      volumeLogic = slicer.modules.volumes.logic()
      babyVolume = volumeLogic.AddArchetypeScalarVolume (filePath, "baby", 0, None)
      displayNode = babyVolume.GetDisplayNode()
      displayNode.SetAutoWindowLevel(False)
      displayNode.SetWindow(470)
      displayNode.SetLevel(250)

      # automatically select the volume to display
      mrmlLogic = slicer.app.applicationLogic()
      selNode = mrmlLogic.GetSelectionNode()
      selNode.SetReferenceActiveVolumeID(babyVolume.GetID())
      mrmlLogic.PropagateVolumeSelection()

      # Create transform node
      transform = slicer.vtkMRMLLinearTransformNode()
      transform.SetName('Baby to Template' )
      slicer.mrmlScene.AddNode(transform)
      babyVolume.SetAndObserveTransformNodeID(transform.GetID())
    return babyVolume
示例#10
0
 def setupMRMLTracking(self):
   if not hasattr(self, "trackingDevice"):
     """ set up the mrml parts or use existing """
     nodes = slicer.mrmlScene.GetNodesByName('trackingDevice')
     if nodes.GetNumberOfItems() > 0:
       self.trackingDevice = nodes.GetItemAsObject(0)
       nodes = slicer.mrmlScene.GetNodesByName('tracker')
       self.tracker = nodes.GetItemAsObject(0)
     else:
       # trackingDevice cursor
       self.cube = vtk.vtkCubeSource()
       self.cube.SetXLength(30)
       self.cube.SetYLength(70)
       self.cube.SetZLength(5)
       self.cube.Update()
       # display node
       self.modelDisplay = slicer.vtkMRMLModelDisplayNode()
       self.modelDisplay.SetColor(1,1,0) # yellow
       slicer.mrmlScene.AddNode(self.modelDisplay)
       # self.modelDisplay.SetPolyData(self.cube.GetOutputPort())
       # Create model node
       self.trackingDevice = slicer.vtkMRMLModelNode()
       self.trackingDevice.SetScene(slicer.mrmlScene)
       self.trackingDevice.SetName("trackingDevice")
       self.trackingDevice.SetAndObservePolyData(self.cube.GetOutputDataObject(0))
       self.trackingDevice.SetAndObserveDisplayNodeID(self.modelDisplay.GetID())
       slicer.mrmlScene.AddNode(self.trackingDevice)
       # tracker
       self.tracker = slicer.vtkMRMLLinearTransformNode()
       self.tracker.SetName('tracker')
       slicer.mrmlScene.AddNode(self.tracker)
       self.trackingDevice.SetAndObserveTransformNodeID(self.tracker.GetID())
	def ROIPrep(self):

		""" vtk, the image analysis library, and Slicer use different coordinate
			systems: IJK and RAS, respectively. This prep calculates a simple matrix 
			transformation on a ROI transform node to be used in the next step.
		"""

		pNode = self.parameterNode()

		subtractVolume = Helper.getNodeByID(pNode.GetParameter('subtractVolumeID'))
		roiTransformID = pNode.GetParameter('roiTransformID')
		roiTransformNode = None

		if roiTransformID != '':
			roiTransformNode = Helper.getNodeByID(roiTransformID)
		else:
			roiTransformNode = slicer.vtkMRMLLinearTransformNode()
			slicer.mrmlScene.AddNode(roiTransformNode)
			pNode.SetParameter('roiTransformID', roiTransformNode.GetID())

		# TO-DO: Understand the precise math behind this section of code..
		dm = vtk.vtkMatrix4x4()
		subtractVolume.GetIJKToRASDirectionMatrix(dm)
		dm.SetElement(0,3,0)
		dm.SetElement(1,3,0)
		dm.SetElement(2,3,0)
		dm.SetElement(0,0,abs(dm.GetElement(0,0)))
		dm.SetElement(1,1,abs(dm.GetElement(1,1)))
		dm.SetElement(2,2,abs(dm.GetElement(2,2)))
		roiTransformNode.SetAndObserveMatrixTransformToParent(dm)
示例#12
0
  def setupScene(self):
    logging.info("UltraSound.setupScene")

    '''
      ReferenceToRas transform is used in almost all IGT applications. Reference is the coordinate system
      of a tool fixed to the patient. Tools are tracked relative to Reference, to compensate for patient
      motion. ReferenceToRas makes sure that everything is displayed in an anatomical coordinate system, i.e.
      R, A, and S (Right, Anterior, and Superior) directions in Slicer are correct relative to any
      images or tracked tools displayed.
      ReferenceToRas is needed for initialization, so we need to set it up before calling Guidelet.setupScene().
    '''

    if self.referenceToRas is None or (self.referenceToRas and slicer.mrmlScene.GetNodeByID(self.referenceToRas.GetID()) is None):
      self.referenceToRas = slicer.mrmlScene.GetFirstNodeByName('ReferenceToRas')
      if self.referenceToRas is None:
        self.referenceToRas = slicer.vtkMRMLLinearTransformNode()
        self.referenceToRas.SetName("ReferenceToRas")
        m = self.guideletParent.logic.readTransformFromSettings('ReferenceToRas', self.guideletParent.configurationName)
        if m is None:
          m = self.guideletParent.logic.createMatrixFromString('1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1')
        self.referenceToRas.SetMatrixTransformToParent(m)
        slicer.mrmlScene.AddNode(self.referenceToRas)

    # live ultrasound
    liveUltrasoundNodeName = self.guideletParent.parameterNode.GetParameter('LiveUltrasoundNodeName')
    self.liveUltrasoundNode_Reference = slicer.mrmlScene.GetFirstNodeByName(liveUltrasoundNodeName)
    if not self.liveUltrasoundNode_Reference:
      imageSpacing=[0.2, 0.2, 0.2]
      # Create an empty image volume
      imageData=vtk.vtkImageData()
      imageData.SetDimensions(self.DEFAULT_IMAGE_SIZE)
      imageData.AllocateScalars(vtk.VTK_UNSIGNED_CHAR, 1)
      thresholder=vtk.vtkImageThreshold()
      thresholder.SetInputData(imageData)
      thresholder.SetInValue(0)
      thresholder.SetOutValue(0)
      # Create volume node
      self.liveUltrasoundNode_Reference=slicer.vtkMRMLScalarVolumeNode()
      self.liveUltrasoundNode_Reference.SetName(liveUltrasoundNodeName)
      self.liveUltrasoundNode_Reference.SetSpacing(imageSpacing)
      self.liveUltrasoundNode_Reference.SetImageDataConnection(thresholder.GetOutputPort())
      # Add volume to scene
      slicer.mrmlScene.AddNode(self.liveUltrasoundNode_Reference)
      displayNode=slicer.vtkMRMLScalarVolumeDisplayNode()
      slicer.mrmlScene.AddNode(displayNode)
      colorNode = slicer.mrmlScene.GetFirstNodeByName('Grey')
      displayNode.SetAndObserveColorNodeID(colorNode.GetID())
      self.liveUltrasoundNode_Reference.SetAndObserveDisplayNodeID(displayNode.GetID())

    self.plusRemoteNode = slicer.mrmlScene.GetFirstNodeByClass('vtkMRMLPlusRemoteNode')
    if self.plusRemoteNode is None:
      self.plusRemoteNode = slicer.vtkMRMLPlusRemoteNode()
      self.plusRemoteNode.SetName("PlusRemoteNode")
      slicer.mrmlScene.AddNode(self.plusRemoteNode)
    self.plusRemoteNode.AddObserver(slicer.vtkMRMLPlusRemoteNode.RecordingStartedEvent, self.recordingCommandCompleted)
    self.plusRemoteNode.AddObserver(slicer.vtkMRMLPlusRemoteNode.RecordingCompletedEvent, self.recordingCommandCompleted)
    self.plusRemoteNode.SetAndObserveOpenIGTLinkConnectorNode(self.guideletParent.connectorNode)

    self.setupResliceDriver()
  def __init__(self, targetFiducialListNode, radius):
    target = targetFiducialListNode
    
    scene = slicer.mrmlScene
    
    sphere = vtk.vtkSphereSource()
    sphere.SetRadius(radius)
    sphere.SetThetaResolution(20)
    sphere.SetPhiResolution(20)
    sphere.Update()

    # Create model node
    insertionRadiusModel = slicer.vtkMRMLModelNode()
    insertionRadiusModel.SetScene(scene)
    insertionRadiusModel.SetName("InsertionSphere-%s" % target.GetName())
    insertionRadiusModel.SetAndObservePolyData(sphere.GetOutput())

    # Create display node
    insertionRadiusModelDisplay = slicer.vtkMRMLModelDisplayNode()
    insertionRadiusModelDisplay.SetColor(0.8,0.8,0.8)
    insertionRadiusModelDisplay.SetOpacity(0.3)
    insertionRadiusModelDisplay.SliceIntersectionVisibilityOn()
    
    insertionRadiusModelDisplay.SetScene(scene)
    scene.AddNode(insertionRadiusModelDisplay)
    insertionRadiusModel.SetAndObserveDisplayNodeID(insertionRadiusModelDisplay.GetID())

    # Add to scene
    insertionRadiusModelDisplay.SetPolyData(sphere.GetOutput())
    
    scene.AddNode(insertionRadiusModel)
    
    # Create insertionRadiusTransform node
    insertionRadiusTransform = slicer.vtkMRMLLinearTransformNode()
    insertionRadiusTransform.SetName('InsertionRadiusTransform-%s' % target.GetName())
    
    scene.AddNode(insertionRadiusTransform)
    
    # Translation
    transformMatrix = vtk.vtkMatrix4x4()
    
    # get coordinates from current fiducial
    currentFiducialCoordinatesRAS = [0, 0, 0]
    
    target.GetFiducialCoordinates(currentFiducialCoordinatesRAS)
    
    transformMatrix.SetElement(0, 3, currentFiducialCoordinatesRAS[0])
    transformMatrix.SetElement(1, 3, currentFiducialCoordinatesRAS[1])
    transformMatrix.SetElement(2, 3, currentFiducialCoordinatesRAS[2])
    
    insertionRadiusTransform.ApplyTransformMatrix(transformMatrix)
    
    insertionRadiusModel.SetAndObserveTransformNodeID(insertionRadiusTransform.GetID())
    
    self.sphere = sphere
    self.insertionRadiusModel = insertionRadiusModel
    self.insertionRadiusModelDisplay = insertionRadiusModelDisplay
    self.insertionRadiusTransform = insertionRadiusTransform
示例#14
0
 def doStepProcessing(self):
     #transforms center of imported volume to world origin
     coords = [0,0,0]
     coords = self.__baseline.GetOrigin()
     
     transformVolmat = vtk.vtkMatrix4x4()
     transformVolmat.SetElement(0,3,coords[0]*-1)
     transformVolmat.SetElement(1,3,coords[1]*-1)
     transformVolmat.SetElement(2,3,coords[2]*-1)
     
     transformVol = slicer.vtkMRMLLinearTransformNode()
     slicer.mrmlScene.AddNode(transformVol)
     transformVol.ApplyTransformMatrix(transformVolmat)
     
     #harden transform
     self.__baseline.SetAndObserveTransformNodeID(transformVol.GetID())
     slicer.vtkSlicerTransformLogic.hardenTransform(self.__baseline)
     
     #offsets volume so its center is registered to world origin
     newCoords = [0,0,0,0,0,0]
     self.__baseline.GetRASBounds(newCoords)
     print newCoords
     shift = [0,0,0]
     shift[0] = 0.5*(newCoords[1] - newCoords[0])
     shift[1] = 0.5*(newCoords[3] - newCoords[2])
     shift[2] = 0.5*(newCoords[4] - newCoords[5])
     
     transformVolmat2 = vtk.vtkMatrix4x4()
     transformVolmat2.SetElement(0,3,shift[0])
     transformVolmat2.SetElement(1,3,shift[1])
     transformVolmat2.SetElement(2,3,shift[2])
     
     transformVol2 = slicer.vtkMRMLLinearTransformNode()
     slicer.mrmlScene.AddNode(transformVol2)
     transformVol2.ApplyTransformMatrix(transformVolmat2)
     
     #harden transform
     self.__baseline.SetAndObserveTransformNodeID(transformVol2.GetID())
     slicer.vtkSlicerTransformLogic.hardenTransform(self.__baseline)
     
     #remove transformations from scene
     slicer.mrmlScene.RemoveNode(transformVol)
     slicer.mrmlScene.RemoveNode(transformVol2)
     
     print('Done')
示例#15
0
  def test_Regimatic1(self):
    """Set up two copies of the same data and try to recover identity"""

    self.delayDisplay("Starting the test",50)

    #
    # first, get some data
    #
    import urllib
    downloads = (
        ('http://www.slicer.org/slicerWiki/images/4/43/MR-head.nrrd', 'Head_moving.nrrd', slicer.util.loadVolume),
        ('http://www.slicer.org/slicerWiki/images/4/43/MR-head.nrrd', 'Head_fixed.nrrd', slicer.util.loadVolume),
        )

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

    volumeNode = slicer.util.getNode(pattern="Head")

    # Create transform node
    movingToFixed = slicer.vtkMRMLLinearTransformNode()
    movingToFixed.SetName('movingToFixed')
    slicer.mrmlScene.AddNode(movingToFixed)

    # set up the nodes for viewing
    fixed = slicer.util.getNode('Head_fixed')
    moving = slicer.util.getNode('Head_moving')
    moving.SetAndObserveTransformNodeID(movingToFixed.GetID())
    compositeNodes = slicer.util.getNodes('vtkMRMLSliceCompositeNode*')
    for compositeNode in compositeNodes.values():
      compositeNode.SetBackgroundVolumeID(fixed.GetID())
      compositeNode.SetForegroundVolumeID(moving.GetID())
      compositeNode.SetForegroundOpacity(0.5)
    applicationLogic = slicer.app.applicationLogic()
    applicationLogic.FitSliceToAll()

    # apply an initial transform
    transform = vtk.vtkTransform()
    # transform.RotateWXYZ(.1, 1,1,1) # TODO: fix quaternion
    transform.Translate(50, 33, -32)
    movingToFixed.SetMatrixTransformToParent(transform.GetMatrix())

    mainWindow = slicer.util.mainWindow()
    mainWindow.moduleSelector().selectModule('Regimatic')

    regimaticWidget = slicer.modules.RegimaticWidget
    regimaticWidget.fixedSelector.setCurrentNode(fixed)
    regimaticWidget.movingSelector.setCurrentNode(moving)

    self.delayDisplay('Test passed!',50)
 def onCalculateTransformButton(self): 
   self.calibrationInstructionsLabel42.setStyleSheet("QLabel {color: #000000;  text-decoration: line-through;}")
   self.calculateTransformButton.setEnabled(False)   
   self.saveTransform = slicer.vtkMRMLLinearTransformNode()
   self.saveTransform.SetName("EndToStartTransform")
   slicer.mrmlScene.AddNode(self.saveTransform)
   logic = UltrasoundSimulatorLogic()  
   logic.calculateStartToEnd(self.saveTransform, self.startFiducialNode, self.endFiducialNode)
   self.currentCalibrationState = "APPLY_AND_FINALIZE_CALIBRATION" 
 def clipping(self):
     planeCollection = vtk.vtkPlaneCollection()
     harden = slicer.vtkSlicerTransformLogic()
     tempTransform = slicer.vtkMRMLLinearTransformNode()
     tempTransform.HideFromEditorsOn()
     slicer.mrmlScene.AddNode(tempTransform)
     numNodes = slicer.mrmlScene.GetNumberOfNodesByClass("vtkMRMLModelNode")
     dictionnaryModel = dict()
     hardenModelIDdict = dict()
     landmarkDescriptionDict = dict()
     modelIDdict = dict()
     for i in range(3, numNodes):
         planeCollection.RemoveAllItems()
         mh = slicer.mrmlScene.GetNthNodeByClass(i, "vtkMRMLModelNode")
         if mh.GetDisplayVisibility() == 0:
             continue
         model = slicer.util.getNode(mh.GetName())
         transform = model.GetParentTransformNode()
         if transform:
             tempTransform.Copy(transform)
             harden.hardenTransform(tempTransform)
             m = vtk.vtkMatrix4x4()
             tempTransform.GetMatrixTransformToParent(m)
             m.Invert(m, m)
         else:
             m = vtk.vtkMatrix4x4()
         for key, planeDef in self.planeDict.iteritems():
             hardenP = m.MultiplyPoint(planeDef.P)
             hardenN = m.MultiplyPoint(planeDef.n)
             if planeDef.boxState:
                 planeDef.vtkPlane.SetOrigin(hardenP[0], hardenP[1], hardenP[2])
                 if planeDef.negState:
                     planeDef.vtkPlane.SetNormal(-hardenN[0], -hardenN[1], -hardenN[2])
                 if planeDef.posState:
                     planeDef.vtkPlane.SetNormal(hardenN[0], hardenN[1], hardenN[2])
                 planeCollection.AddItem(planeDef.vtkPlane)
         dictionnaryModel[model.GetID()]= model.GetPolyData()
         polyData = model.GetPolyData()
         clipper = vtk.vtkClipClosedSurface()
         clipper.SetClippingPlanes(planeCollection)
         clipper.SetInputData(polyData)
         clipper.SetGenerateFaces(1)
         clipper.SetScalarModeToLabels()
         clipper.Update()
         polyDataNew = clipper.GetOutput()
         model.SetAndObservePolyData(polyDataNew)
         # Checking if one ore more fiducial list are connected to this model
         list = slicer.mrmlScene.GetNodesByClass("vtkMRMLMarkupsFiducialNode")
         end = list.GetNumberOfItems()
         for i in range(0,end):
             fidList = list.GetItemAsObject(i)
             if fidList.GetAttribute("connectedModelID"):
                 if fidList.GetAttribute("connectedModelID") == model.GetID():
                     modelIDdict[fidList.GetID()], hardenModelIDdict[fidList.GetID()], landmarkDescriptionDict[fidList.GetID()] = \
                         self.unprojectLandmarks(fidList)
     return dictionnaryModel, modelIDdict, hardenModelIDdict, landmarkDescriptionDict
  def TestNeedleDetection(self):
    
    parameters = {}
    scene = slicer.mrmlScene
    collection = scene.GetNodesByClass('vtkMRMLScalarVolumeNode');
    nimages = collection.GetNumberOfItems()
    collection.InitTraversal()
    n = 0
    cliList = []
    while n < nimages:
      inImage = collection.GetNextItemAsObject()
      if inImage == None:
        break
      
      id = inImage.GetID()
      print('Processing image node = %s...' % id)
      
      # Create a new image node
      outImage = slicer.vtkMRMLScalarVolumeNode()
      name = inImage.GetName() + '_Needle'
      outImage.SetName(name)
      scene.AddNode(outImage)
      outImage.SetLabelMap(1)

      # Create a new linear transform node (for needle position/orientation)
      needleTransform = slicer.vtkMRMLLinearTransformNode()
      name = inImage.GetName() + '_Transform'
      needleTransform.SetName(name)
      scene.AddNode(needleTransform)

      parameters = {}
      parameters['inputVolume'] = inImage.GetID()
      parameters['outputVolume'] = outImage.GetID()
      parameters['needleTransform'] = needleTransform.GetID()

      parameters['sigma1'] = 0.5
      parameters['minsigma'] = 0.5
      parameters['maxsigma'] = 1.3
      parameters['stepsigma'] = 5
      parameters['minlinemeasure'] = 40
      parameters['alpha1'] = 0.5
      parameters['alpha2'] = 2
      parameters['anglethreshold'] = 25
      parameters['normal'] = [0.0, 0.0, 1.0]
      parameters['numberOfBins'] = 128
      parameters['minimumObjectSize'] = 50
      parameters['minPrincipalAxisLength'] = 50
      parameters['closestPoint'] = [0.0, 0.0, 0.0]

      nd = slicer.modules.needledetection
      c = slicer.cli.run(nd, None, parameters)
      c.AddObserver('ModifiedEvent', self.printStatus)
      self.cliList.append(c)
      n = n + 1
示例#19
0
 def loadScrew(self):    
     print "load screw button"
     self.fidChanged
     
     fid = self.fidNode
     
     collectionS = slicer.mrmlScene.GetNodesByName('Screw at point %s' % self.currentFidLabel)
     screwCheck = collectionS.GetItemAsObject(0)
     
     if screwCheck == None:
         screwDescrip = ["0","0","0","0","0","0"]
         screwModel = slicer.modules.models.logic().AddModel(self.screwPath)
         if screwModel != None:
           fid.AddObserver('ModifiedEvent', self.fidMove)
         
           matrix = vtk.vtkMatrix4x4()
           matrix.DeepCopy((1, 0, 0, self.coords[0],
                            0, -1, 0, self.coords[1],
                            0, 0, -1, self.coords[2],
                            0, 0, 0, 1))
         
           transformScrewTemp = slicer.vtkMRMLLinearTransformNode()
           transformScrewTemp.SetName("Transform-%s" % self.currentFidLabel)
           slicer.mrmlScene.AddNode(transformScrewTemp)
           transformScrewTemp.ApplyTransformMatrix(matrix)
         
         
           screwModel.SetName('Screw at point %s' % self.currentFidLabel)
           screwModel.SetAndObserveTransformNodeID(transformScrewTemp.GetID())
        
         
           modelDisplay = screwModel.GetDisplayNode()
           modelDisplay.SetColor(0.12,0.73,0.91)
           modelDisplay.SetDiffuse(0.90)
           modelDisplay.SetAmbient(0.10)
           modelDisplay.SetSpecular(0.20)
           modelDisplay.SetPower(10.0)
           modelDisplay.SetSliceIntersectionVisibility(True)
           screwModel.SetAndObserveDisplayNodeID(modelDisplay.GetID())
           
           
           screwDescrip[0] = self.currentFidLabel
           screwDescrip[1] = self.__length
           screwDescrip[2] = self.__diameter
           
           self.screwList.append(screwDescrip)
           
         
           
         else:
             return
     
     else:
         return
示例#20
0
  def ZFrameRegistrationTransform(self):
    self.dataNodeZFrame = slicer.vtkMRMLLinearTransformNode()
    self.dataNodeZFrame.SetName('ZFrameTransform')
    slicer.mrmlScene.AddNode(self.dataNodeZFrame)

    self.connectNode.RegisterOutgoingMRMLNode(self.dataNodeZFrame)
    self.connectNode.PushNode(self.dataNodeZFrame)

    print self.connectNode.PushNode(self.dataNodeZFrame)

    '''query the status of server, if registration -> stop node and delete the node'''
示例#21
0
  def onButtonRegistrationClicked(self):
    if self.registTag:  # check already has a registration data node
      self.connectNode.PushNode(self.dataNodeZFrame)

    else:  # fist time to creat the registration data node
      self.dataNodeZFrame = slicer.vtkMRMLLinearTransformNode()
      self.dataNodeZFrame.SetName("ZFrameTransform")
      slicer.mrmlScene.AddNode(self.dataNodeZFrame)
      self.connectNode.RegisterOutgoingMRMLNode(self.dataNodeZFrame)

      self.connectNode.PushNode(self.dataNodeZFrame)  # send the ZFrameTransform data to controller
      self.registTag = True
示例#22
0
  def TargetTransform(self):
    ## change -> up func
    self.dataNodeZFrame.Stop()
    self.connectNode.UnregisterOutgoingMRMLNode(self.dataNodeZFrame)
    ##

    self.dataNodeTarget = slicer.vtkMRMLLinearTransformNode()
    self.dataNodeTarget.SetName('TARGET')
    slicer.mrmlScene.AddNode(self.dataNodeTarget)

    self.connectNode.RegisterOutgoingMRMLNode(self.dataNodeTarget)

    '''check node status'''
示例#23
0
  def register(self,fixedVolume,movingVolume,parameters={}):
    """
    Run BRAINSFit to register movingVolume in the space of fixedVolume.
    Parameters is and optional dictionary.
    Returns parameters with any defaults filled in.
    """

    self.delayDisplay('Running the BRAINSFit')

    # required parameters
    parameters["fixedVolume"] = fixedVolume.GetID()
    parameters["movingVolume"] = movingVolume.GetID()

    # type of transform is optional, default to linear
    keys = parameters.keys()
    if "useBSpline" in keys:
      if not 'bsplineTransform' in keys:
        transform = slicer.vtkMRMLBSplineTransformNode()
        slicer.mrmlScene.AddNode(transform)
        parameters['bsplineTransform'] = transform.GetID()
    else:
      if not 'linearTransform' in keys:
        transform = slicer.vtkMRMLLinearTransformNode()
        slicer.mrmlScene.AddNode(transform)
        parameters['linearTransform'] = transform.GetID()

    # if no phase picked, default to rigid
    if not self.availablePhases.intersection(parameters):
      parameters['useRigid'] = True

    # if no output volume specified, clone the moving
    if not "outputVolume" in parameters.keys():
      outputName = movingVolume.GetName() + "-transformed"
      volumesLogic = slicer.modules.volumes.logic()
      outputVolume = volumesLogic.CloneVolume(slicer.mrmlScene, movingVolume, outputName)
      parameters['outputVolume'] = outputVolume.GetID()

    self.delayDisplay(parameters)

    cliNode = slicer.cli.run(slicer.modules.brainsfit, None, parameters, delete_temporary_files=False)
    waitCount = 0
    maxWait = 10000
    while cliNode.GetStatusString() != 'Completed' and waitCount < maxWait:
      self.delayDisplay( "Running BRAINSFit... %d seconds" % waitCount )
      waitCount += 1

    if waitCount == maxWait:
      raise Exception("Registration took too long to run!")

    self.delayDisplay( "Finished after %d seconds" % waitCount )
    return parameters
示例#24
0
  def activeEvent(self):
    print "into activeEvent"
    self.tempLinearNode = slicer.vtkMRMLLinearTransformNode()
    self.tempLinearNode.SetName('temp')

    #self.tagTemp = self.tempLinearNode.AddObserver('ModifiedEvent', self.putInfo)
    #self.tagTemp = self.connectNode.AddObserver('ModifiedEvent', self.putInfo)
    #self.tagTemp = self.connectNode.AddObserver(slicer.vtkMRMLIGTLConnectorNode.ReceiveEvent, self.putInfo)
    #self.tagTemp = self.tempLinearNode.AddObserver(vtk.vtkCommand.ModifiedEvent, self.putInfo)
    #self.tagTemp = self.tempLinearNode.AddObserver(self.connectNode.ReceiveEvent, self.putInfo)
    self.tagTemp = self.connectNode.AddObserver(self.connectNode.ReceiveEvent, self.putInfo)

    #test
    self.times1 = 0
示例#25
0
    def loadScrew(self):    
        print "load screw button"
        #self.fidChanged

        screwCheck = slicer.util.getNode('Screw at point %s' % self.currentFidLabel)
        if screwCheck != None:
            # screw already loaded
            return

        screwDescrip = ["0","0","0","0","0","0"]
        screwModel = slicer.modules.models.logic().AddModel(self.screwPath)
        if screwModel is None:
            logging.error("Failed to load screw model: "+self.screwPath)
            return

        matrix = vtk.vtkMatrix4x4()
        matrix.DeepCopy((1, 0, 0, self.coords[0],
                       0, -1, 0, self.coords[1],
                       0, 0, -1, self.coords[2],
                       0, 0, 0, 1))

        transformScrewTemp = slicer.vtkMRMLLinearTransformNode()
        transformScrewTemp.SetName("Transform-%s" % self.currentFidLabel)
        slicer.mrmlScene.AddNode(transformScrewTemp)
        transformScrewTemp.ApplyTransformMatrix(matrix)

        screwModel.SetName('Screw at point %s' % self.currentFidLabel)
        screwModel.SetAndObserveTransformNodeID(transformScrewTemp.GetID())

        modelDisplay = screwModel.GetDisplayNode()
        modelDisplay.SetColor(0.12,0.73,0.91)
        modelDisplay.SetDiffuse(0.90)
        modelDisplay.SetAmbient(0.10)
        modelDisplay.SetSpecular(0.20)
        modelDisplay.SetPower(10.0)
        modelDisplay.SetSliceIntersectionVisibility(True)
        screwModel.SetAndObserveDisplayNodeID(modelDisplay.GetID())

        screwDescrip[0] = self.currentFidLabel
        screwDescrip[1] = self.__length
        screwDescrip[2] = self.__diameter

        self.screwList.append(screwDescrip)

        self.insertScrewButton.enabled = True
        self.backoutScrewButton.enabled = False
        self.b.enabled = True
        self.transformSlider1.enabled = True
        self.transformSlider2.enabled = True
示例#26
0
  def RegisterImageSequence(self, fixedVolumeNode, movingVolumeSequenceNode, linearTransformSequenceNode, outputVolumeSequenceNode, initializeTransformMode='useGeometryAlign', initialTransformNode=None, maskVolumeNode=None):
    if linearTransformSequenceNode:
      linearTransformSequenceNode.RemoveAllDataNodes()
    if outputVolumeSequenceNode:
      outputVolumeSequenceNode.RemoveAllDataNodes()
  
    numOfImageNodes = movingVolumeSequenceNode.GetNumberOfDataNodes()
    lastTransformNode = None
    for i in range(numOfImageNodes):
      movingVolumeNode = movingVolumeSequenceNode.GetNthDataNode(i)
      movingVolumeIndexValue = movingVolumeSequenceNode.GetNthIndexValue(i)
      slicer.mrmlScene.AddNode(movingVolumeNode)

      outputTransformNode = slicer.vtkMRMLLinearTransformNode()
      #outputTransformNode = slicer.vtkMRMLBSplineTransformNode()
      slicer.mrmlScene.AddNode(outputTransformNode)
    
      outputVolumeNode = None	
      if outputVolumeSequenceNode:
        outputVolumeNode = slicer.vtkMRMLScalarVolumeNode()
        slicer.mrmlScene.AddNode(outputVolumeNode)

      initialTransformNode = linearTransformSequenceNode.GetNthDataNode(i-1)
      if initialTransformNode:
        slicer.mrmlScene.AddNode(initialTransformNode)
      else:
        initialTransformNode = None

      self.RegisterImage(fixedVolumeNode, movingVolumeNode, outputTransformNode, outputVolumeNode, initializeTransformMode, initialTransformNode, maskVolumeNode)
      if linearTransformSequenceNode:
        linearTransformSequenceNode.SetDataNodeAtValue(outputTransformNode, movingVolumeIndexValue)
      if outputVolumeSequenceNode:
        outputVolumeSequenceNode.SetDataNodeAtValue(outputVolumeNode, movingVolumeIndexValue)
     
      if initialTransformNode:
        slicer.mrmlScene.RemoveNode(initialTransformNode)
      slicer.mrmlScene.RemoveNode(movingVolumeNode)
      if outputVolumeNode:
        slicer.mrmlScene.RemoveNode(outputVolumeNode)
      # Initialize the lastTransform so the next registration can start with this transform
      lastTransform = outputTransformNode
      slicer.mrmlScene.RemoveNode(outputTransformNode)
    # This is required as a temp workaround to use the transform sequence to map baseline ROI to sequence ROI
    
    if linearTransformSequenceNode:  
      for i in range(numOfImageNodes):
        transformNode = linearTransformSequenceNode.GetNthDataNode(i)
        transformNode.Inverse()
示例#27
0
  def ZFrameRegistrationTransform(self):
    self.dataNodeZFrame = slicer.vtkMRMLLinearTransformNode()
    self.dataNodeZFrame.SetName('ZFrameTransform')
    slicer.mrmlScene.AddNode(self.dataNodeZFrame)

    self.connectNode.RegisterOutgoingMRMLNode(self.dataNodeZFrame)
    self.connectNode.PushNode(self.dataNodeZFrame)

    print self.connectNode.PushNode(self.dataNodeZFrame)

    '''query the status of server, if registration -> stop node and delete the node'''


#  def TargetTransform(self):
#    ## change -> up func
#    self.dataNodeZFrame.Stop()
#    self.connectNode.UnregisterOutgoingMRMLNode(self.dataNodeZFrame)
#    ##
#
#    self.dataNodeTarget = slicer.vtkMRMLLinearTransformNode()
#    self.dataNodeTarget.SetName('TARGET')
#    slicer.mrmlScene.AddNode(self.dataNodeTarget)
#
#    self.connectNode.RegisterOutgoingMRMLNode(self.dataNodeTarget)
#
#    '''check node status'''
#
#
#  def SendTargetTransform(self):
#    '''check whether dataNodeTarget exist'''
#    self.connectNode.PushNode(self.dataNodeTarget)
#
#
#  def CurrentTransform(self):
#    self.dataNodeCurrent = slicer.vtkMRMLLinearTransformNode
#    self.dataNodeCurrent.SetName('CURRENT')
#    slicer.mrmlScene.AddNode(self.dataNodeCurrent)
#    self.connectNode.RegisterIncomingMRMLNode(self.dataNodeCurrent)
#

    '''queryNode = slicer.vtkMRMLIGTQueryNode()
       '''
    # self.connectNode.PushQuery
    '''check node status'''
示例#28
0
  def __init__(self):
    self.scene = slicer.mrmlScene
    self.scene.SetUndoOn()
    self.scene.SaveStateForUndo(self.scene.GetNodes())
    
    self.currentSlice = Slice('/luscinia/ProstateStudy/invivo/Patient59/loupas/RadialImagesCC_imwrite/arfi_ts3_26.57.png')

    # yay, adding images to slicer
    planeSource = vtk.vtkPlaneSource()
    planeSource.SetCenter(self.currentSlice.x, self.currentSlice.y, self.currentSlice.z)
    reader = vtk.vtkPNGReader()
    reader.SetFileName(self.currentSlice.name)

    # model node
    self.model = slicer.vtkMRMLModelNode()
    self.model.SetScene(self.scene)
    self.model.SetName(self.currentSlice.name)
    self.model.SetAndObservePolyData(planeSource.GetOutput())

    # model display node
    self.modelDisplay = slicer.vtkMRMLModelDisplayNode()
    self.modelDisplay.BackfaceCullingOff() # so plane can be seen from both front and back face
    self.modelDisplay.SetScene(self.scene)
    self.scene.AddNode(self.modelDisplay)

    # connecting model node w/ its model display node
    self.model.SetAndObserveDisplayNodeID(self.modelDisplay.GetID())

    # adding tiff file as texture to modelDisplay
    self.modelDisplay.SetAndObserveTextureImageData(reader.GetOutput())
    self.scene.AddNode(self.model)

    # now doing a linear transform to set coordinates and orientation of plane
    self.transform = slicer.vtkMRMLLinearTransformNode()
    self.scene.AddNode(self.transform)
    self.model.SetAndObserveTransformNodeID(self.transform.GetID())
    vTransform = vtk.vtkTransform()
    vTransform.Scale(150, 150, 150)
    vTransform.RotateX(0)
    vTransform.RotateY(0)
    vTransform.RotateZ(0)

    self.transform.SetAndObserveMatrixTransformToParent(vTransform.GetMatrix())
示例#29
0
    def setupScene(self):

        # create transforms
        self.ReferenceToRas = slicer.util.getNode("ReferenceToRas")
        if not self.ReferenceToRas:
            self.ReferenceToRas = slicer.vtkMRMLLinearTransformNode()
            self.ReferenceToRas.SetName("ReferenceToRas")
            m = vtk.vtkMatrix4x4()
            m.SetElement(0, 0, 0)
            m.SetElement(0, 2, -1)
            m.SetElement(1, 1, 0)
            m.SetElement(1, 1, -1)
            m.SetElement(2, 2, 0)
            m.SetElement(2, 0, -1)
            self.ReferenceToRas.SetMatrixTransformToParent(m)
            slicer.mrmlScene.AddNode(self.ReferenceToRas)

        # setup feature scene
        self.ultrasound.setupScene()
示例#30
0
  def selectSlice(self, index):
    self.scene.Undo()
    self.scene.SaveStateForUndo(self.scene.GetNodes())
    imgFilePrefix = './data/test'
    imgFileSuffix = '.tiff'
    # yay, adding images to slicer
    planeSource = vtk.vtkPlaneSource()

    reader = vtk.vtkTIFFReader()
    reader.SetFileName(imgFilePrefix + str(self.imageList[index]) + imgFileSuffix)
    #reader.CanReadFile('imgFilePrefix + str(self.imageList[0]) + imgFileSuffix')

    # model node
    model = slicer.vtkMRMLModelNode()
    model.SetScene(self.scene)
    model.SetName("test " + str(self.imageList[index]) + "cow")
    model.SetAndObservePolyData(planeSource.GetOutput())

    # model display node
    modelDisplay = slicer.vtkMRMLModelDisplayNode()
    modelDisplay.BackfaceCullingOff() # so plane can be seen from both front and back face
    modelDisplay.SetScene(self.scene)
    self.scene.AddNode(modelDisplay)

    # connecting model node w/ its model display node
    model.SetAndObserveDisplayNodeID(modelDisplay.GetID())

    # adding tiff file as texture to modelDisplay
    modelDisplay.SetAndObserveTextureImageData(reader.GetOutput())
    self.scene.AddNode(model)

    # now doing a linear transform to set coordinates and orientation of plane
    transform = slicer.vtkMRMLLinearTransformNode()
    self.scene.AddNode(transform)
    model.SetAndObserveTransformNodeID(transform.GetID())
    vTransform = vtk.vtkTransform()
    vTransform.Scale(150, 150, 150)
    vTransform.RotateX(self.rotateXList[index])
    vTransform.RotateY(self.rotateYList[index])
    vTransform.RotateZ(self.rotateZList[index])

    transform.SetAndObserveMatrixTransformToParent(vTransform.GetMatrix())
示例#31
0
    def test_BreachWarningSelfTest1(self):
        """Ideally you should have several levels of tests.  At the lowest level
    tests sould exercise the functionality of the logic with different inputs
    (both valid and invalid).  At higher levels your tests should emulate the
    way the user would interact with your code and confirm that it still works
    the way you intended.
    One of the most important features of the tests is that it should alert other
    developers when their changes will have an impact on the behavior of your
    module.  For example, if a developer removes a feature that you depend on,
    your test should break so they know that the feature is needed.
    """

        self.delayDisplay("Starting the test")

        self.delayDisplay("Create models")
        modelNodes = []
        createModelsLogic = slicer.modules.createmodels.logic()
        sphereRadius = 10.0
        sphereModel = createModelsLogic.CreateSphere(
            sphereRadius)  # watched model
        toolModel = createModelsLogic.CreateNeedle(50.0, 1.5, 0.0, False)

        self.delayDisplay("Set up module GUI")
        mainWindow = slicer.util.mainWindow()
        mainWindow.moduleSelector().selectModule('BreachWarning')
        bwWidget = slicer.modules.breachwarning.widgetRepresentation()
        bwColorPickerButton = slicer.util.findChildren(
            widget=bwWidget,
            className='ctkColorPickerButton',
            name='ColorPickerButton')[0]
        bwModelNodeCombobox = slicer.util.findChildren(
            widget=bwWidget, name='ModelNodeComboBox')[0]
        bwToolNodeCombobox = slicer.util.findChildren(widget=bwWidget,
                                                      name='ToolComboBox')[0]

        bwModelNodeCombobox.setCurrentNodeID(sphereModel.GetID())

        warningColor = (1.0, 0.0, 0.0)
        color = qt.QColor(warningColor[0] * 255, warningColor[1] * 255,
                          warningColor[2] * 255, 1)
        bwColorPickerButton.setColor(color)

        # Transform the sphere somewhere
        sphereTransform = slicer.vtkMRMLLinearTransformNode()
        sphereTransformMatrix = vtk.vtkMatrix4x4()
        sphereTransformMatrix.SetElement(0, 3, 80)
        sphereTransformMatrix.SetElement(1, 3, 40)
        sphereTransformMatrix.SetElement(2, 3, 30)
        sphereTransform.SetMatrixTransformToParent(sphereTransformMatrix)
        slicer.mrmlScene.AddNode(sphereTransform)
        sphereModel.SetAndObserveTransformNodeID(sphereTransform.GetID())

        # Create transforms node hierarchy for the tool
        transforms = []
        numberOfTransforms = 3
        for i in range(numberOfTransforms):
            transforms.append(slicer.vtkMRMLLinearTransformNode())
            transformName = "Tool_" + str(i)
            transforms[i].SetName(
                slicer.mrmlScene.GenerateUniqueName(transformName))
            slicer.mrmlScene.AddNode(transforms[i])
            if i > 0:
                transforms[i].SetAndObserveTransformNodeID(
                    transforms[i - 1].GetID())

        # Tool transform is the one at the bottom of the transform hierarchy
        # (to make sure transform changes in the middle of the transform hierarchy are used correctly)
        toolModel.SetAndObserveTransformNodeID(transforms[-1].GetID())
        bwToolNodeCombobox.setCurrentNodeID(transforms[-1].GetID())

        # Pick a transform in the middle of the transform hierarchy that we change to simulate tool motion,
        # leave the rest of the transforms unchanged
        toolToWorldTransform = transforms[1]

        transformMatrixOutside = vtk.vtkMatrix4x4()
        transformMatrixOutside.DeepCopy(sphereTransformMatrix)
        transformMatrixOutside.SetElement(
            0, 3,
            transformMatrixOutside.GetElement(0, 3) + sphereRadius * 2.1)
        transformMatrixOutside.SetElement(
            1, 3,
            transformMatrixOutside.GetElement(1, 3) + sphereRadius * 1.3)
        transformMatrixOutside.SetElement(
            2, 3,
            transformMatrixOutside.GetElement(2, 3) + sphereRadius * 3.2)

        transformMatrixInside = vtk.vtkMatrix4x4()
        transformMatrixInside.DeepCopy(sphereTransformMatrix)
        transformMatrixInside.SetElement(
            0, 3,
            transformMatrixInside.GetElement(0, 3) + sphereRadius * 0.1)
        transformMatrixInside.SetElement(
            1, 3,
            transformMatrixInside.GetElement(1, 3) + sphereRadius * 0.3)
        transformMatrixInside.SetElement(
            2, 3,
            transformMatrixInside.GetElement(2, 3) + sphereRadius * 0.2)

        # Start breach warning checks

        self.delayDisplay('Tool is outside the sphere')
        toolToWorldTransform.SetMatrixTransformToParent(transformMatrixOutside)
        sphereColor = sphereModel.GetDisplayNode().GetColor()
        self.assertNotEqual(sphereColor, warningColor)

        self.delayDisplay('Tool is inside the sphere')
        toolToWorldTransform.SetMatrixTransformToParent(transformMatrixInside)
        sphereColor = sphereModel.GetDisplayNode().GetColor()
        self.assertEqual(sphereColor, warningColor)

        self.delayDisplay('Tool is outside the sphere')
        toolToWorldTransform.SetMatrixTransformToParent(transformMatrixOutside)
        sphereColor = sphereModel.GetDisplayNode().GetColor()
        self.assertNotEqual(sphereColor, warningColor)

        self.delayDisplay('Test passed!')
    def rigido(self):

        escena = slicer.mrmlScene
        #Se recupera la escena cargada
        volumen4D = self.inputSelector.currentNode()
        imagenvtk4D = volumen4D.GetImageData()

        extract1 = vtk.vtkImageExtractComponents()
        extract1.SetInputData(imagenvtk4D)
        imagen_fija = extract1.SetComponents(0)
        extract1.Update()
        #Matriz de transformacion
        ras2ijk = vtk.vtkMatrix4x4()
        ijk2ras = vtk.vtkMatrix4x4()

        #Se solicita al volumen original que devuelva las matrices
        volumen4D.GetRASToIJKMatrix(ras2ijk)
        volumen4D.GetIJKToRASMatrix(ijk2ras)

        #Se crea un volumen nuevo
        volumenFijo = slicer.vtkMRMLScalarVolumeNode()
        #Se asignan las transformaciones
        volumenFijo.SetRASToIJKMatrix(ras2ijk)
        volumenFijo.SetIJKToRASMatrix(ijk2ras)
        #Se asigna el volumen 3D
        volumenFijo.SetAndObserveImageData(extract1.GetOutput())
        escena.AddNode(volumenFijo)

        numero_imagenes = volumen4D.GetNumberOfFrames()
        valor1 = []
        # vector donde se guarda los valores de LR despues aplicar la transformada rigida
        valor2 = []
        # vector donde se guarda los valores de PA despues aplicar la transformada rigida
        valor3 = []
        # vector donde se guarda los valores de IS despues aplicar la transformada rigida
        vecvolmay = []
        # vector que muestra el frame, los volumenes que tienen un movimiento mayor a 4 mm
        valor1.append(0)
        valor2.append(0)
        valor3.append(0)

        #En esta parte se evaluan todos los volumenes moviles
        for i in range(0, numero_imagenes, 1):
            #extraer la imagen movil
            extract2 = vtk.vtkImageExtractComponents()
            extract2.SetInputData(imagenvtk4D)
            imagen_movil = extract2.SetComponents(i)
            extract2.Update()

            #Se crea un volumen movil, y se realiza el mismo procedimiento que con el fijo
            volumenMovil = slicer.vtkMRMLScalarVolumeNode()

            volumenSalida = slicer.vtkMRMLScalarVolumeNode()
            escena.AddNode(volumenSalida)
            volumenMovil.SetRASToIJKMatrix(ras2ijk)
            volumenMovil.SetIJKToRASMatrix(ijk2ras)
            volumenMovil.SetAndObserveImageData(extract2.GetOutput())
            escena.AddNode(volumenMovil)

            #Se crea la transformada para alinear los volumenes
            transformadaSalida = slicer.vtkMRMLLinearTransformNode()
            transformadaSalida.SetName(
                'Transformada de registro rigido' +
                str(i))  #se le da un nombre especifico a la transformada
            slicer.mrmlScene.AddNode(transformadaSalida)

            parameters = {}
            parameters['fixedVolume'] = volumenFijo.GetID()
            parameters['movingVolume'] = volumenMovil.GetID()
            parameters[
                'transformType'] = 'Rigid'  #Se coloca segun lo que se quiera hacer si rigido, afin o bspline
            parameters['outputTransform'] = transformadaSalida.GetID()
            parameters['outputVolume'] = volumenSalida.GetID()

            cliNode = slicer.cli.run(slicer.modules.brainsfit,
                                     None,
                                     parameters,
                                     wait_for_completion=True)
            slicer.util.saveNode(
                volumenSalida, 'volumenrigido' + str(i + 1) + '.nrrd'
            )  #se guarda el volumen registrado en la carpeta de documentos

    # Este for se hace con el fin de ver los volumenes que tienen un desplazamiento mayor a 4 mm con respecto al fijo
        for i in range(0, numero_imagenes):
            nodo = escena.GetNodesByName('Transformada de registro rigido' +
                                         str(i))
            nodo = nodo.GetItemAsObject(0)
            matriztransformada = nodo.GetMatrixTransformToParent(
            )  # Se obtiene la matriz de transformacion

            # se obtiene para cada frame la ubicacion en las 3 direcciones
            valor1inicial = matriztransformada.GetElement(
                0, 3
            )  #se agrega el valor en la posicion 0 3 de la transformada valor que corresponde a LR
            valor2inicial = matriztransformada.GetElement(
                1, 3
            )  #se agrega el valor en la posicion 0 3 de la transformada valor que corresponde a PA
            valor3inicial = matriztransformada.GetElement(
                2, 3
            )  #se agrega el valor en la posicion 0 3 de la transformada valor que corresponde a IS
            valor1.append(valor1inicial)
            valor2.append(valor2inicial)
            valor3.append(valor3inicial)
            # Si la posicion en cualquier direccion de un volumen es mayor a 4mm respecto al del primer frame se obtiene un vector con su posicion
            if ((abs(valor1[i]) > 4) or (abs(valor2[i]) > 4)
                    or (abs(valor3[i]) > 4)):
                vecvolmay.append(i)

        print("Los volumenes con los que se mueve mas de 4mm son")
        print("Volumen")
        print(vecvolmay)
        if (len(vecvolmay) == 0):  # Si no hay alguni no se muestra nada
            print("Ningun volumen se movio mas de 4mm")
示例#33
0
    def setupScene(self):  #applet specific
        logging.debug('setupScene')
        Guidelet.setupScene(self)

        logging.debug('Create transforms')

        self.cauteryTipToCautery = slicer.util.getNode('CauteryTipToCautery')
        if not self.cauteryTipToCautery:
            self.cauteryTipToCautery = slicer.vtkMRMLLinearTransformNode()
            self.cauteryTipToCautery.SetName("CauteryTipToCautery")
            m = self.readTransformFromSettings('CauteryTipToCautery')
            if m:
                self.cauteryTipToCautery.SetMatrixTransformToParent(m)
            slicer.mrmlScene.AddNode(self.cauteryTipToCautery)

        self.cauteryModelToCauteryTip = slicer.util.getNode(
            'CauteryModelToCauteryTip')
        if not self.cauteryModelToCauteryTip:
            self.cauteryModelToCauteryTip = slicer.vtkMRMLLinearTransformNode()
            self.cauteryModelToCauteryTip.SetName("CauteryModelToCauteryTip")
            m = self.readTransformFromSettings('CauteryModelToCauteryTip')
            if m:
                self.cauteryModelToCauteryTip.SetMatrixTransformToParent(m)
            self.cauteryModelToCauteryTip.SetMatrixTransformToParent(m)
            slicer.mrmlScene.AddNode(self.cauteryModelToCauteryTip)

        self.needleTipToNeedle = slicer.util.getNode('NeedleTipToNeedle')
        if not self.needleTipToNeedle:
            self.needleTipToNeedle = slicer.vtkMRMLLinearTransformNode()
            self.needleTipToNeedle.SetName("NeedleTipToNeedle")
            m = self.readTransformFromSettings('NeedleTipToNeedle')
            if m:
                self.needleTipToNeedle.SetMatrixTransformToParent(m)
            slicer.mrmlScene.AddNode(self.needleTipToNeedle)

        self.needleModelToNeedleTip = slicer.util.getNode(
            'NeedleModelToNeedleTip')
        if not self.needleModelToNeedleTip:
            self.needleModelToNeedleTip = slicer.vtkMRMLLinearTransformNode()
            self.needleModelToNeedleTip.SetName("NeedleModelToNeedleTip")
            m = self.readTransformFromSettings('NeedleModelToNeedleTip')
            if m:
                self.needleModelToNeedleTip.SetMatrixTransformToParent(m)
            self.needleModelToNeedleTip.SetMatrixTransformToParent(m)
            slicer.mrmlScene.AddNode(self.needleModelToNeedleTip)

        self.cauteryCameraToCautery = slicer.util.getNode(
            'CauteryCameraToCautery')
        if not self.cauteryCameraToCautery:
            self.cauteryCameraToCautery = slicer.vtkMRMLLinearTransformNode()
            self.cauteryCameraToCautery.SetName("CauteryCameraToCautery")
            m = vtk.vtkMatrix4x4()
            m.SetElement(0, 0, 0)
            m.SetElement(0, 2, -1)
            m.SetElement(1, 1, 0)
            m.SetElement(1, 0, 1)
            m.SetElement(2, 2, 0)
            m.SetElement(2, 1, -1)
            self.cauteryCameraToCautery.SetMatrixTransformToParent(m)
            slicer.mrmlScene.AddNode(self.cauteryCameraToCautery)

        self.CauteryToNeedle = slicer.util.getNode('CauteryToNeedle')
        if not self.CauteryToNeedle:
            self.CauteryToNeedle = slicer.vtkMRMLLinearTransformNode()
            self.CauteryToNeedle.SetName("CauteryToNeedle")
            slicer.mrmlScene.AddNode(self.CauteryToNeedle)

        # Create transforms that will be updated through OpenIGTLink

        self.cauteryToReference = slicer.util.getNode('CauteryToReference')
        if not self.cauteryToReference:
            self.cauteryToReference = slicer.vtkMRMLLinearTransformNode()
            self.cauteryToReference.SetName("CauteryToReference")
            slicer.mrmlScene.AddNode(self.cauteryToReference)

        self.needleToReference = slicer.util.getNode('NeedleToReference')
        if not self.needleToReference:
            self.needleToReference = slicer.vtkMRMLLinearTransformNode()
            self.needleToReference.SetName("NeedleToReference")
            slicer.mrmlScene.AddNode(self.needleToReference)

        # Cameras
        logging.debug('Create cameras')

        self.LeftCamera = slicer.util.getNode('Left Camera')
        if not self.LeftCamera:
            self.LeftCamera = slicer.vtkMRMLCameraNode()
            self.LeftCamera.SetName("Left Camera")
            slicer.mrmlScene.AddNode(self.LeftCamera)

        self.RightCamera = slicer.util.getNode('Right Camera')
        if not self.RightCamera:
            self.RightCamera = slicer.vtkMRMLCameraNode()
            self.RightCamera.SetName("Right Camera")
            slicer.mrmlScene.AddNode(self.RightCamera)

        # Models
        logging.debug('Create models')

        self.cauteryModel_CauteryTip = slicer.util.getNode('CauteryModel')
        if not self.cauteryModel_CauteryTip:
            if (self.parameterNode.GetParameter('TestMode') == 'True'):
                moduleDirectoryPath = slicer.modules.lumpnav.path.replace(
                    'LumpNav.py', '')
                slicer.util.loadModel(
                    qt.QDir.toNativeSeparators(
                        moduleDirectoryPath +
                        '../../../models/temporary/cautery.stl'))
                self.cauteryModel_CauteryTip = slicer.util.getNode(
                    pattern="cautery")
            else:
                slicer.modules.createmodels.logic().CreateNeedle(
                    100, 1.0, 2.5, 0)
                self.cauteryModel_CauteryTip = slicer.util.getNode(
                    pattern="NeedleModel")
                self.cauteryModel_CauteryTip.GetDisplayNode().SetColor(
                    1.0, 1.0, 0)
            self.cauteryModel_CauteryTip.SetName("CauteryModel")

        self.needleModel_NeedleTip = slicer.util.getNode('NeedleModel')
        if not self.needleModel_NeedleTip:
            slicer.modules.createmodels.logic().CreateNeedle(80, 1.0, 2.5, 0)
            self.needleModel_NeedleTip = slicer.util.getNode(
                pattern="NeedleModel")
            self.needleModel_NeedleTip.GetDisplayNode().SetColor(
                0.333333, 1.0, 1.0)
            self.needleModel_NeedleTip.SetName("NeedleModel")
            self.needleModel_NeedleTip.GetDisplayNode(
            ).SliceIntersectionVisibilityOn()

        # Create surface from point set

        logging.debug('Create surface from point set')

        self.tumorModel_Needle = slicer.util.getNode('TumorModel')
        if not self.tumorModel_Needle:
            self.tumorModel_Needle = slicer.vtkMRMLModelNode()
            self.tumorModel_Needle.SetName("TumorModel")
            sphereSource = vtk.vtkSphereSource()
            sphereSource.SetRadius(0.001)
            self.tumorModel_Needle.SetPolyDataConnection(
                sphereSource.GetOutputPort())
            slicer.mrmlScene.AddNode(self.tumorModel_Needle)
            # Add display node
            modelDisplayNode = slicer.vtkMRMLModelDisplayNode()
            modelDisplayNode.SetColor(0, 1, 0)  # Green
            modelDisplayNode.BackfaceCullingOff()
            modelDisplayNode.SliceIntersectionVisibilityOn()
            modelDisplayNode.SetSliceIntersectionThickness(4)
            modelDisplayNode.SetOpacity(0.3)  # Between 0-1, 1 being opaque
            slicer.mrmlScene.AddNode(modelDisplayNode)
            self.tumorModel_Needle.SetAndObserveDisplayNodeID(
                modelDisplayNode.GetID())

        tumorMarkups_Needle = slicer.util.getNode('T')
        if not tumorMarkups_Needle:
            tumorMarkups_Needle = slicer.vtkMRMLMarkupsFiducialNode()
            tumorMarkups_Needle.SetName("T")
            slicer.mrmlScene.AddNode(tumorMarkups_Needle)
            tumorMarkups_Needle.CreateDefaultDisplayNodes()
            tumorMarkups_Needle.GetDisplayNode().SetTextScale(0)
        self.setAndObserveTumorMarkupsNode(tumorMarkups_Needle)

        # Set up breach warning node
        logging.debug('Set up breach warning')
        self.breachWarningNode = slicer.util.getNode('LumpNavBreachWarning')

        if not self.breachWarningNode:
            self.breachWarningNode = slicer.mrmlScene.CreateNodeByClass(
                'vtkMRMLBreachWarningNode')
            self.breachWarningNode.SetName("LumpNavBreachWarning")
            slicer.mrmlScene.AddNode(self.breachWarningNode)
            self.breachWarningNode.SetPlayWarningSound(True)
            self.breachWarningNode.SetWarningColor(1, 0, 0)
            self.breachWarningNode.SetOriginalColor(
                self.tumorModel_Needle.GetDisplayNode().GetColor())
            self.breachWarningNode.SetAndObserveToolTransformNodeId(
                self.cauteryTipToCautery.GetID())
            self.breachWarningNode.SetAndObserveWatchedModelNodeID(
                self.tumorModel_Needle.GetID())

        # Set up breach warning light
        import BreachWarningLight
        logging.debug('Set up breach warning light')
        self.breachWarningLightLogic = BreachWarningLight.BreachWarningLightLogic(
        )
        self.breachWarningLightLogic.setMarginSizeMm(
            float(
                self.parameterNode.GetParameter(
                    'BreachWarningLightMarginSizeMm')))
        if (self.parameterNode.GetParameter('EnableBreachWarningLight') ==
                'True'):
            logging.debug("BreachWarningLight: active")
            self.breachWarningLightLogic.startLightFeedback(
                self.breachWarningNode, self.connectorNode)
        else:
            logging.debug("BreachWarningLight: shutdown")
            self.breachWarningLightLogic.shutdownLight(self.connectorNode)

        # Build transform tree
        logging.debug('Set up transform tree')
        self.cauteryToReference.SetAndObserveTransformNodeID(
            self.ReferenceToRas.GetID())
        self.cauteryCameraToCautery.SetAndObserveTransformNodeID(
            self.cauteryToReference.GetID())
        self.cauteryTipToCautery.SetAndObserveTransformNodeID(
            self.cauteryToReference.GetID())
        self.cauteryModelToCauteryTip.SetAndObserveTransformNodeID(
            self.cauteryTipToCautery.GetID())
        self.needleToReference.SetAndObserveTransformNodeID(
            self.ReferenceToRas.GetID())
        self.needleTipToNeedle.SetAndObserveTransformNodeID(
            self.needleToReference.GetID())
        self.needleModelToNeedleTip.SetAndObserveTransformNodeID(
            self.needleTipToNeedle.GetID())
        self.cauteryModel_CauteryTip.SetAndObserveTransformNodeID(
            self.cauteryModelToCauteryTip.GetID())
        self.needleModel_NeedleTip.SetAndObserveTransformNodeID(
            self.needleModelToNeedleTip.GetID())
        self.tumorModel_Needle.SetAndObserveTransformNodeID(
            self.needleToReference.GetID())
        self.tumorMarkups_Needle.SetAndObserveTransformNodeID(
            self.needleToReference.GetID())
        # self.liveUltrasoundNode_Reference.SetAndObserveTransformNodeID(self.ReferenceToRas.GetID())

        # Hide slice view annotations (patient name, scale, color bar, etc.) as they
        # decrease reslicing performance by 20%-100%
        logging.debug('Hide slice view annotations')
        import DataProbe
        dataProbeUtil = DataProbe.DataProbeLib.DataProbeUtil()
        dataProbeParameterNode = dataProbeUtil.getParameterNode()
        dataProbeParameterNode.SetParameter('showSliceViewAnnotations', '0')
示例#34
0
    def transform(self, cmd):
        if not hasattr(self, 'p'):
            self.p = numpy.zeros(3)
            self.dpdt = numpy.zeros(3)
            self.d2pdt2 = numpy.zeros(3)
            self.o = numpy.zeros(3)
            self.dodt = numpy.zeros(3)
            self.d2odt2 = numpy.zeros(3)
        p = urlparse.urlparse(cmd)
        q = urlparse.parse_qs(p.query)
        self.logMessage(q)
        dt = float(q['interval'][0])
        self.d2pdt2 = 1000 * numpy.array(
            [float(q['x'][0]),
             float(q['y'][0]),
             float(q['z'][0])])
        if not hasattr(self, 'g0'):
            self.g0 = self.d2pdt2
        self.d2pdt2 = self.d2pdt2 - self.g0
        self.dpdt = self.dpdt + dt * self.d2pdt2
        self.p = self.p + dt * self.dpdt
        # TODO: integrate rotations

        if not hasattr(self, "idevice"):
            """ set up the mrml parts or use existing """
            nodes = slicer.mrmlScene.GetNodesByName('idevice')
            if nodes.GetNumberOfItems() > 0:
                self.idevice = nodes.GetItemAsObject(0)
                nodes = slicer.mrmlScene.GetNodesByName('tracker')
                self.tracker = nodes.GetItemAsObject(0)
            else:
                # idevice cursor
                self.cube = vtk.vtkCubeSource()
                self.cube.SetXLength(30)
                self.cube.SetYLength(70)
                self.cube.SetZLength(5)
                self.cube.Update()
                # display node
                self.modelDisplay = slicer.vtkMRMLModelDisplayNode()
                self.modelDisplay.SetColor(1, 1, 0)  # yellow
                slicer.mrmlScene.AddNode(self.modelDisplay)
                self.modelDisplay.SetPolyData(self.cube.GetOutput())
                # Create model node
                self.idevice = slicer.vtkMRMLModelNode()
                self.idevice.SetScene(slicer.mrmlScene)
                self.idevice.SetName("idevice")
                self.idevice.SetAndObservePolyData(self.cube.GetOutput())
                self.idevice.SetAndObserveDisplayNodeID(
                    self.modelDisplay.GetID())
                slicer.mrmlScene.AddNode(self.idevice)
                # tracker
                self.tracker = slicer.vtkMRMLLinearTransformNode()
                self.tracker.SetName('tracker')
                slicer.mrmlScene.AddNode(self.tracker)
                self.idevice.SetAndObserveTransformNodeID(self.tracker.GetID())
        m = self.tracker.GetMatrixTransformToParent()
        m.Identity()
        up = numpy.zeros(3)
        up[2] = 1
        d = self.d2pdt2
        dd = d / numpy.sqrt(numpy.dot(d, d))
        xx = numpy.cross(dd, up)
        yy = numpy.cross(dd, xx)
        for row in xrange(3):
            m.SetElement(row, 0, dd[row])
            m.SetElement(row, 1, xx[row])
            m.SetElement(row, 2, yy[row])
            #m.SetElement(row,3, self.p[row])

        return ("got it")
示例#35
0
  def associateTransformations(self):

    # # The nodes StylusTipToReference and ProbeToReference are added 
    stylusTipToTrackerNode = slicer.util.getNode("StylusTipToTracker")
    if stylusTipToTrackerNode == None:
      stylusTipToTrackerNode = slicer.vtkMRMLLinearTransformNode()
      slicer.mrmlScene.AddNode(stylusTipToTrackerNode)
      stylusTipToTrackerNode.SetName("StylusTipToTracker")
    
#     probeToTrackerNode = slicer.util.getNode("ProbeToTracker")
#     if probeToTrackerNode == None:
#       probeToTrackerNode = slicer.vtkMRMLLinearTransformNode()
#       slicer.mrmlScene.AddNode(probeToTrackerNode)
#       probeToTrackerNode.SetName("ProbeToTracker")
      
    trackerToProbeNode = slicer.util.getNode("TrackerToProbe")
    if trackerToProbeNode == None:
      trackerToProbeNode = slicer.vtkMRMLLinearTransformNode()
      slicer.mrmlScene.AddNode(trackerToProbeNode)
      trackerToProbeNode.SetName("TrackerToProbe")  
      
    stylusTipToProbeNode = slicer.util.getNode("StylusTipToProbe")
    if stylusTipToProbeNode == None:
      stylusTipToProbeNode = slicer.vtkMRMLLinearTransformNode()
      slicer.mrmlScene.AddNode(stylusTipToProbeNode)
      stylusTipToProbeNode.SetName("StylusTipToProbe")  
      
    imageToProbeNode = slicer.util.getNode("ImageToProbe")
    if imageToProbeNode == None:
      imageToProbeNode = slicer.vtkMRMLLinearTransformNode()
      slicer.mrmlScene.AddNode(imageToProbeNode)
      imageToProbeNode.SetName("ImageToProbe")   
      
    #imageNode = slicer.util.getNode("Image_Image")          
      
        
    # referenceToRASNode=slicer.util.getNode("ReferenceToRAS")           
         
    # imageReferenceNode=slicer.util.getNode("Image_Reference")
    #imageNode.SetAndObserveTransformNodeID(imageToProbeNode.GetID()) 
#     stylusTipToProbeNode.SetAndObserveTransformNodeID(probeToTrackerNode.GetID())   
    stylusTipToTrackerNode.SetAndObserveTransformNodeID(trackerToProbeNode.GetID()) 
     
    self.stylusModelNode = slicer.util.getNode("Stylus_Example")    
    if self.stylusModelNode == None:    
        # Add the stylus model
        modelsModule = slicer.modules.models
        modelsModuleLogic = modelsModule.logic()
        modelsModuleLogic.SetMRMLScene(slicer.mrmlScene)
        path = slicer.modules.stylusbasedusprobecalibration.path
        modulePath = os.path.dirname(path)
        stylusModelFile = os.path.join(modulePath, "models/Stylus_Example.stl")
        modelsModuleLogic.AddModel(stylusModelFile)
        self.stylusModelNode = slicer.util.getNode("Stylus_Example")
    
    self.stylusModelNode.RemoveAllNodeReferenceIDs("transform")
  
    # # Associate the model of the stylus with the stylus tip transforms
    stylusTipModelToStylusTipTransform = slicer.util.getNode("StylusTipModelToStylusTip")
    if stylusTipModelToStylusTipTransform == None:
        stylusTipModelToStylusTipTransform = slicer.vtkMRMLLinearTransformNode()
        slicer.mrmlScene.AddNode(stylusTipModelToStylusTipTransform) 
        stylusTipModelToStylusTipTransform.SetName("StylusTipModelToStylusTip") 
        
    matrix = vtk.vtkMatrix4x4()
    matrix.SetElement(0, 3, -210)
    stylusTipModelToStylusTipTransform.SetAndObserveMatrixTransformToParent(matrix)
    stylusTipModelToStylusTipTransform.SetAndObserveTransformNodeID(stylusTipToTrackerNode.GetID())
    
    self.stylusModelNode.SetAndObserveTransformNodeID(stylusTipModelToStylusTipTransform.GetID())
示例#36
0
    def setupScene(self):  # applet specific
        logging.debug('setupScene')

        # Add a Qt timer, that fires every X ms (16.7ms = 60 FPS, 33ms = 30FPS)
        # Connect the timeout() signal of the qt timer to a function in this class that you will write
        self.timer.connect('timeout()', self.onTimerTimeout)
        self.timer.start(16.7)

        # ReferenceToRas is needed for ultrasound initialization, so we need to
        # set it up before calling Guidelet.setupScene().
        self.referenceToRasTransform = slicer.util.getNode('ReferenceToRas')
        if not self.referenceToRasTransform:
            self.referenceToRasTransform = slicer.vtkMRMLLinearTransformNode()
            self.referenceToRasTransform.SetName("ReferenceToRas")
            m = self.logic.readTransformFromSettings('ReferenceToRas',
                                                     self.configurationName)
            if m is None:
                # Create identity matrix
                m = self.logic.createMatrixFromString(
                    '1.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 1.0 0.0 0 0 0 1')
            self.referenceToRasTransform.SetMatrixTransformToParent(m)
            slicer.mrmlScene.AddNode(self.referenceToRasTransform)

        Guidelet.setupScene(self)

        logging.debug('Create transforms')
        # Coordinate system definitions: https://app.assembla.com/spaces/slicerigt/wiki/Coordinate_Systems

        self.needleTipToNeedleTransform = slicer.util.getNode(
            'NeedleTipToNeedle')
        if not self.needleTipToNeedleTransform:
            self.needleTipToNeedleTransform = slicer.vtkMRMLLinearTransformNode(
            )
            self.needleTipToNeedleTransform.SetName("NeedleTipToNeedle")
            m = self.logic.readTransformFromSettings('NeedleTipToNeedle',
                                                     self.configurationName)
            if m:
                self.needleTipToNeedleTransform.SetMatrixTransformToParent(m)
            slicer.mrmlScene.AddNode(self.needleTipToNeedleTransform)

        self.needleModelToNeedleTipTransform = slicer.util.getNode(
            'NeedleModelToNeedleTip')
        if not self.needleModelToNeedleTipTransform:
            self.needleModelToNeedleTipTransform = slicer.vtkMRMLLinearTransformNode(
            )
            self.needleModelToNeedleTipTransform.SetName(
                "NeedleModelToNeedleTip")
            m = self.logic.readTransformFromSettings('NeedleModelToNeedleTip',
                                                     self.configurationName)
            if m:
                self.needleModelToNeedleTipTransform.SetMatrixTransformToParent(
                    m)
            slicer.mrmlScene.AddNode(self.needleModelToNeedleTipTransform)

        self.trajModelToNeedleTipTransform = slicer.util.getNode(
            'TrajModelToNeedleTip')
        if not self.trajModelToNeedleTipTransform:
            self.trajModelToNeedleTipTransform = slicer.vtkMRMLLinearTransformNode(
            )
            self.trajModelToNeedleTipTransform.SetName("TrajModelToNeedleTip")
            m = self.logic.readTransformFromSettings('TrajModelToNeedleTip',
                                                     self.configurationName)
            if m:
                self.trajModelToNeedleTipTransform.SetMatrixTransformToParent(
                    m)
            slicer.mrmlScene.AddNode(self.trajModelToNeedleTipTransform)

        # Create transforms that will be updated through OpenIGTLink
        self.needleToReferenceTransform = slicer.util.getNode(
            'NeedleToReference')
        if not self.needleToReferenceTransform:
            self.needleToReferenceTransform = slicer.vtkMRMLLinearTransformNode(
            )
            self.needleToReferenceTransform.SetName("NeedleToReference")
            slicer.mrmlScene.AddNode(self.needleToReferenceTransform)

        # Models
        logging.debug('Create models')

        self.needleWithTipModel = slicer.util.getNode('NeedleModel')
        if not self.needleWithTipModel:
            # length, radius, tipradius, bool markers, vtkMRMLModelNode(1 or 0: creates a ring close to tip)
            # length, radius, tipradius, bool markers, vtkMRMLModelNode(1 or 0: creates a ring close to tip)
            slicer.modules.createmodels.logic().CreateNeedle(
                65, 1.0, self.needleModelTipRadius, 0)
            self.needleWithTipModel = slicer.util.getNode(
                pattern="NeedleModel")
            self.needleWithTipModel.GetDisplayNode().SetColor(0.08, 0.84,
                                                              0.1)  # (1,0,1)#
            self.needleWithTipModel.SetName("NeedleModel")
            self.needleWithTipModel.GetDisplayNode(
            ).SliceIntersectionVisibilityOn()

        self.trajectoryModel_needleModel = slicer.util.getNode(
            'TrajectoryModel')
        cylinderLength = 100
        if not self.trajectoryModel_needleModel:
            self.trajectoryModel_needleModel = slicer.modules.createmodels.logic(
            ).CreateCylinder(cylinderLength, 0.1)  # 0.5mm tall, 4mm radius
            self.trajectoryModel_needleModel.SetName('TrajectoryModel')
            self.trajectoryModel_needleModel.GetDisplayNode().SetColor(
                0.69, 0.93, 0.93)  # (1, 1, 0.5)
            # here, we want to bake in a transform to move the origin of the cylinder to one of the ends (instead
            # of being in the middle)
            transformFilter = vtk.vtkTransformPolyDataFilter()
            transformFilter.SetInputConnection(
                self.trajectoryModel_needleModel.GetPolyDataConnection())
            trans = vtk.vtkTransform()
            trans.Translate(0, 0, cylinderLength / 2)
            transformFilter.SetTransform(trans)
            transformFilter.Update()
            self.trajectoryModel_needleModel.SetPolyDataConnection(
                transformFilter.GetOutputPort())

        # number of balls = cylinderLength / distance between markers (may be -1, depending on ball at tip (giggggity))
        number_spheres = cylinderLength / 10
        for i in range(0, number_spheres):
            # create sphere model if non-existent
            model = slicer.util.getNode('DistanceMarkerModel_' + str(i))
            if model is None:
                model = slicer.modules.createmodels.logic().CreateSphere(0.7)
                model.SetName('DistanceMarkerModel_' + str(i))
                R = 1.0
                G = 1.0
                B = 0.1 + i * (0.7 / (number_spheres - 1.0)
                               )  # yellow spectrum ranging from 0.1-0.7
                model.GetDisplayNode().SetColor(R, G, B)

            # create transform node, apply z translation i*distanceBetweenMarkers
            node = slicer.util.getNode('DistanceMarkerTransform_' + str(i))
            if node is None:
                node = slicer.vtkMRMLLinearTransformNode()
                node.SetName('DistanceMarkerTransform_' + str(i))
                slicer.mrmlScene.AddNode(node)

            m = self.logic.createMatrixFromString('1.0 0.0 0.0 0.0 '
                                                  '0.0 1.0 0.0 0.0 '
                                                  '0.0 0.0 1.0 ' +
                                                  str((i + 1) * 10.0) + ' '
                                                  '0.0 0.0 0.0 1.0')
            node.SetMatrixTransformToParent(m)
            model.SetAndObserveTransformNodeID(node.GetID())
            node.SetAndObserveTransformNodeID(
                self.needleTipToNeedleTransform.GetID())

        # Setup the needle tip hierarchy
        self.needleToReferenceTransform.SetAndObserveTransformNodeID(
            self.referenceToRasTransform.GetID())
        self.needleTipToNeedleTransform.SetAndObserveTransformNodeID(
            self.needleToReferenceTransform.GetID())
        self.needleWithTipModel.SetAndObserveTransformNodeID(
            self.needleTipToNeedleTransform.GetID())

        # Build transform tree
        logging.debug('Set up transform tree')
        self.needleModelToNeedleTipTransform.SetAndObserveTransformNodeID(
            self.needleTipToNeedleTransform.GetID())
        self.needleWithTipModel.SetAndObserveTransformNodeID(
            self.needleModelToNeedleTipTransform.GetID())
        # self.liveUltrasoundNode_Reference.SetAndObserveTransformNodeID(self.referenceToRasTransform.GetID()) # always commented out

        # self.needleToReferenceTransform.SetAndObserveTransformNodeID(self.referenceToRasTransform.GetID())
        # self.needleTipToNeedleTransform.SetAndObserveTransformNodeID(self.needleToReferenceTransform.GetID())
        # self.needleModelToNeedleTipTransform.SetAndObserveTransformNodeID(self.needleTipToNeedleTransform.GetID())
        self.trajModelToNeedleTipTransform.SetAndObserveTransformNodeID(
            self.needleTipToNeedleTransform.GetID())
        self.trajectoryModel_needleModel.SetAndObserveTransformNodeID(
            self.trajModelToNeedleTipTransform.GetID())
    def onEntry(self, comingFrom, transitionType):
        super(DefineROIStep, self).onEntry(comingFrom, transitionType)

        # setup the interface
        lm = slicer.app.layoutManager()
        lm.setLayout(3)

        #create progress bar dialog
        self.progress = qt.QProgressDialog(slicer.util.mainWindow())
        self.progress.minimumDuration = 0
        self.progress.show()
        self.progress.setValue(0)
        self.progress.setMaximum(0)
        self.progress.setCancelButton(0)
        self.progress.setMinimumWidth(500)
        self.progress.setWindowModality(2)

        self.progress.setLabelText('Generating Volume Rendering...')
        slicer.app.processEvents(qt.QEventLoop.ExcludeUserInputEvents)
        self.progress.repaint()

        #read scalar volume node ID from previous step
        pNode = self.parameterNode()
        baselineVolume = Helper.getNodeByID(
            pNode.GetParameter('baselineVolumeID'))
        self.__baselineVolume = baselineVolume

        #if ROI was created previously, get its transformation matrix and update current ROI
        roiTransformID = pNode.GetParameter('roiTransformID')
        roiTransformNode = None

        if roiTransformID != '':
            roiTransformNode = Helper.getNodeByID(roiTransformID)
        else:
            roiTransformNode = slicer.vtkMRMLLinearTransformNode()
            slicer.mrmlScene.AddNode(roiTransformNode)
            pNode.SetParameter('roiTransformID', roiTransformNode.GetID())

        dm = vtk.vtkMatrix4x4()
        baselineVolume.GetIJKToRASDirectionMatrix(dm)
        dm.SetElement(0, 3, 0)
        dm.SetElement(1, 3, 0)
        dm.SetElement(2, 3, 0)
        dm.SetElement(0, 0, abs(dm.GetElement(0, 0)))
        dm.SetElement(1, 1, abs(dm.GetElement(1, 1)))
        dm.SetElement(2, 2, abs(dm.GetElement(2, 2)))
        roiTransformNode.SetAndObserveMatrixTransformToParent(dm)

        Helper.SetBgFgVolumes(pNode.GetParameter('baselineVolumeID'))
        Helper.SetLabelVolume(None)

        # use this transform node to align ROI with the axes of the baseline
        # volume
        roiTfmNodeID = pNode.GetParameter('roiTransformID')
        if roiTfmNodeID != '':
            self.__roiTransformNode = Helper.getNodeByID(roiTfmNodeID)
        else:
            Helper.Error(
                'Internal error! Error code CT-S2-NRT, please report!')

        # get the roiNode from parameters node, if it exists, and initialize the
        # GUI
        self.updateWidgetFromParameterNode(pNode)

        # start VR
        if self.__roi != None:
            self.__roi.SetDisplayVisibility(1)
            self.InitVRDisplayNode()

        #close progress bar
        self.progress.setValue(2)
        self.progress.repaint()
        slicer.app.processEvents(qt.QEventLoop.ExcludeUserInputEvents)
        self.progress.close()
        self.progress = None

        #pNode.SetParameter('currentStep', self.stepid)

        qt.QTimer.singleShot(0, self.killButton)
    def onApplyCargar(self):

        self.nombre = self.seleccionDeEstudianteComboBox.currentText
        con = mysql.connector.connect(user="******",
                                      password="******",
                                      host="127.0.0.1",
                                      database="basedatos_simulador_ttp")
        cursor = con.cursor()
        estudiantes = []
        cursor.execute("SELECT * FROM estudiantes")
        rows = cursor.fetchall()
        for row in rows:
            estudiantes.append(row)
        for i in range(0, len(estudiantes)):
            if (self.nombre == estudiantes[i][1]):
                self.idEstudiante = estudiantes[i][0]
                self.tornillo_1 = str(estudiantes[i][3])
                self.tornillo_2 = str(estudiantes[i][4])
                self.tranformadaTornillo1 = estudiantes[i][5]
                self.tranformadaTornillo2 = estudiantes[i][6]
                break

        nombreTornillo1 = self.tornillo_1
        nombreTornillo1 = nombreTornillo1.split('.')
        nombreTornillo1 = nombreTornillo1[0]

        nombreTornillo2 = self.tornillo_2
        nombreTornillo2 = nombreTornillo2.split('.')
        nombreTornillo2 = nombreTornillo2[0]

        x = 0
        c = []
        for i in self.tranformadaTornillo1:
            if (i == '[' or i == ']' or i == ',' or i == '' or i == "'"):
                pass
            else:
                c.append(self.tranformadaTornillo1[x])
            x = x + 1
        d = ''.join(c)
        d.split(' ')

        self.tranformadaTornillo1 = [float(x) for x in d.split()]

        mt1 = vtk.vtkMatrix4x4()

        mt1.SetElement(0, 0, float(self.tranformadaTornillo1[0]))
        mt1.SetElement(0, 1, float(self.tranformadaTornillo1[1]))
        mt1.SetElement(0, 2, float(self.tranformadaTornillo1[2]))
        mt1.SetElement(0, 3, float(self.tranformadaTornillo1[3]))
        mt1.SetElement(1, 0, float(self.tranformadaTornillo1[4]))
        mt1.SetElement(1, 1, float(self.tranformadaTornillo1[5]))
        mt1.SetElement(1, 2, float(self.tranformadaTornillo1[6]))
        mt1.SetElement(1, 3, float(self.tranformadaTornillo1[7]))
        mt1.SetElement(2, 0, float(self.tranformadaTornillo1[8]))
        mt1.SetElement(2, 1, float(self.tranformadaTornillo1[9]))
        mt1.SetElement(2, 2, float(self.tranformadaTornillo1[10]))
        mt1.SetElement(2, 3, float(self.tranformadaTornillo1[11]))

        mt1.SetElement(3, 0, 0)
        mt1.SetElement(3, 1, 0)
        mt1.SetElement(3, 2, 0)
        mt1.SetElement(3, 3, 1)

        x = 0
        c = []
        for i in self.tranformadaTornillo2:
            if (i == '[' or i == ']' or i == ',' or i == '' or i == "'"):
                pass
            else:
                c.append(self.tranformadaTornillo2[x])
            x = x + 1
        d = ''.join(c)
        d.split(' ')

        self.tranformadaTornillo2 = [float(x) for x in d.split()]

        mt2 = vtk.vtkMatrix4x4()

        mt2.SetElement(0, 0, float(self.tranformadaTornillo2[0]))
        mt2.SetElement(0, 1, float(self.tranformadaTornillo2[1]))
        mt2.SetElement(0, 2, float(self.tranformadaTornillo2[2]))
        mt2.SetElement(0, 3, float(self.tranformadaTornillo2[3]))
        mt2.SetElement(1, 0, float(self.tranformadaTornillo2[4]))
        mt2.SetElement(1, 1, float(self.tranformadaTornillo2[5]))
        mt2.SetElement(1, 2, float(self.tranformadaTornillo2[6]))
        mt2.SetElement(1, 3, float(self.tranformadaTornillo2[7]))
        mt2.SetElement(2, 0, float(self.tranformadaTornillo2[8]))
        mt2.SetElement(2, 1, float(self.tranformadaTornillo2[9]))
        mt2.SetElement(2, 2, float(self.tranformadaTornillo2[10]))
        mt2.SetElement(2, 3, float(self.tranformadaTornillo2[11]))
        mt2.SetElement(3, 0, 0)
        mt2.SetElement(3, 1, 0)
        mt2.SetElement(3, 2, 0)
        mt2.SetElement(3, 3, 1)

        moduleName = 'simuladorTornillosPediculares'
        scriptedModulesPath = eval(
            'slicer.modules.%s.path' %
            moduleName.lower())  # devuelve la ruta del .py
        scriptedModulesPath = os.path.dirname(
            scriptedModulesPath)  # lleva a la carpeta del modulo

        path2 = os.path.join(scriptedModulesPath,
                             'simuladorTornillosPedicularesWizard', 'Modelos',
                             'Lumbar 2.5 B31s - 4/4 Lumbar  2.5  B31s.nrrd')
        path1 = os.path.join(scriptedModulesPath,
                             'simuladorTornillosPedicularesWizard', 'Modelos',
                             'nucleos.stl')
        path3 = os.path.join(scriptedModulesPath,
                             'simuladorTornillosPedicularesWizard', 'Modelos',
                             'stlcolumna.stl')

        #path1='C:\Users\Camilo_Q\Documents\GitHub\simuladorTornillosPediculares\simuladorTornillosPedicularesWizard\Modelos/stlcolumna.stl' #Se obtiene direccion de la unbicación del tornillo
        #path2='C:\Users\Camilo_Q\Documents\GitHub\simuladorTornillosPediculares\simuladorTornillosPedicularesWizard\Modelos\Lumbar 2.5 B31s - 4/4 Lumbar  2.5  B31s.nrrd'
        #path3='C:\Users\Camilo_Q\Documents\GitHub\simuladorTornillosPediculares\simuladorTornillosPedicularesWizard\Modelos/nucleos.stl'

        columna = slicer.util.getNode(
            'stlcolumna')  # Se obtiene el nodo del objeto en escena
        if (columna == None):

            slicer.util.loadModel(path1)
            slicer.util.loadModel(path3)
            slicer.util.loadVolume(path2)
            columna = slicer.util.getNode('stlcolumna')
            nucleo = slicer.util.getNode('nucleos')
            nucleoModelDisplayNode = nucleo.GetDisplayNode()
            nucleoModelDisplayNode.SetColor(0.729411, 0.7529411, 0.8745098)
            nucleoModelDisplayNode.SetAmbient(0.10)
            nucleoModelDisplayNode.SetDiffuse(0.90)
            nucleoModelDisplayNode.SetSpecular(0.20)
            nucleoModelDisplayNode.SetPower(10)
            nucleoModelDisplayNode.SetSliceIntersectionVisibility(1)

            columnaModelDisplayNode = columna.GetDisplayNode()

            columnaModelDisplayNode.SetColor(
                0.9451, 0.8392, 0.5686)  #Colores parametrizados sobre 255
            columnaModelDisplayNode.SetSliceIntersectionVisibility(1)
            columnaModelDisplayNode.SetAmbient(0.33)
            columnaModelDisplayNode.SetDiffuse(0.78)
            columnaModelDisplayNode.SetSpecular(0.13)
            columnaModelDisplayNode.SetPower(15.5)

        self.layoutManager = slicer.app.layoutManager()
        threeDWidget = self.layoutManager.threeDWidget(0)
        self.threeDView = threeDWidget.threeDView()
        self.threeDView.resetFocalPoint()

        try:
            slicer.mrmlScene.RemoveNode(self.tornillo1)
        except:
            pass
        try:
            slicer.mrmlScene.RemoveNode(self.tornillo2)
        except:
            pass
        a = slicer.util.getNode('Transformada Tornillo 1')
        try:
            slicer.mrmlScene.RemoveNode(a)
        except:
            pass
        a = slicer.util.getNode('Transformada Tornillo 2')
        try:
            slicer.mrmlScene.RemoveNode(a)
        except:
            pass

        self.pathTornillos = os.path.join(
            scriptedModulesPath, 'simuladorTornillosPedicularesWizard',
            'Modelos', 'Tornillos', '%s' % self.tornillo_1)
        #self.pathTornillos = 'C:\Users\Camilo_Q\Documents\GitHub\simuladorTornillosPediculares\simuladorTornillosPedicularesWizard\Modelos\Tornillos/'+self.tornillo_1
        slicer.util.loadModel(self.pathTornillos)

        self.pathTornillos = os.path.join(
            scriptedModulesPath, 'simuladorTornillosPedicularesWizard',
            'Modelos', 'Tornillos', '%s' % self.tornillo_2)
        #self.pathTornillos = 'C:\Users\Camilo_Q\Documents\GitHub\simuladorTornillosPediculares\simuladorTornillosPedicularesWizard\Modelos\Tornillos/'+self.tornillo_2
        slicer.util.loadModel(self.pathTornillos)

        for i in range(0, 20):

            if self.contadorTornillos1 == 1:
                self.tornillo1 = slicer.util.getNode(
                    str(nombreTornillo1) + "_" + str(i))

            if self.contadorTornillos1 == 0:
                self.tornillo1 = slicer.util.getNode(str(nombreTornillo1))
                self.contadorTornillos1 = 1

            if self.tornillo1 != None:
                self.contadorTornillos1 = 0
                self.tornillo1.SetName("Tornillo_1")
                break

        for i in range(0, 20):

            if self.contadorTornillos2 == 1:
                self.tornillo2 = slicer.util.getNode(
                    str(nombreTornillo2) + "_" + str(i))

            if self.contadorTornillos2 == 0:
                self.tornillo2 = slicer.util.getNode(str(nombreTornillo2))
                self.contadorTornillos2 = 1

            if self.tornillo2 != None:
                self.contadorTornillos2 = 0
                self.tornillo2.SetName("Tornillo_2")
                break

        tornilloModelDisplayNode = self.tornillo1.GetDisplayNode()
        tornilloModelDisplayNode.SetColor(0.847059, 0.847059, 0.847059)
        tornilloModelDisplayNode.SetAmbient(0.10)
        tornilloModelDisplayNode.SetDiffuse(0.6)
        tornilloModelDisplayNode.SetSpecular(1)
        tornilloModelDisplayNode.SetPower(40)
        tornilloModelDisplayNode.SetSliceIntersectionVisibility(1)

        self.transformadaTornillo1 = slicer.vtkMRMLLinearTransformNode(
        )  #Se crea una transformada lineal
        self.transformadaTornillo1.SetName(
            'Transformada Tornillo 1')  #Se asigna nombre a la transformada
        slicer.mrmlScene.AddNode(self.transformadaTornillo1)  #
        self.tornillo1.SetAndObserveTransformNodeID(
            self.transformadaTornillo1.GetID())
        self.transformadaTornillo1.SetAndObserveMatrixTransformToParent(mt1)

        tornilloModelDisplayNode = self.tornillo2.GetDisplayNode()
        tornilloModelDisplayNode.SetColor(0.847059, 0.847059, 0.847059)
        tornilloModelDisplayNode.SetAmbient(0.10)
        tornilloModelDisplayNode.SetDiffuse(0.6)
        tornilloModelDisplayNode.SetSpecular(1)
        tornilloModelDisplayNode.SetPower(40)
        tornilloModelDisplayNode.SetSliceIntersectionVisibility(1)

        self.transformadaTornillo2 = slicer.vtkMRMLLinearTransformNode(
        )  #Se crea una transformada lineal
        self.transformadaTornillo2.SetName(
            'Transformada Tornillo 2')  #Se asigna nombre a la transformada
        slicer.mrmlScene.AddNode(self.transformadaTornillo2)  #
        self.tornillo2.SetAndObserveTransformNodeID(
            self.transformadaTornillo2.GetID())
        self.transformadaTornillo2.SetAndObserveMatrixTransformToParent(mt2)
示例#39
0
    def onHelloWorldButtonClicked(self):

        scene = slicer.mrmlScene
        inputModel = self.inputSelector.currentNode()

        bounds = [0, 0, 0, 0, 0, 0]
        inputModel.GetBounds(bounds)

        print('Model Name is:')
        print(inputModel.GetName())

        X = bounds[1] - bounds[0]
        Y = bounds[3] - bounds[2]
        Z = bounds[5] - bounds[4]

        mid = (bounds[0] + X / 2, bounds[2] + Y / 2, bounds[4] + Z / 2)

        X_thick = .1  #TODO resolution input
        Y_thick = .1  #TODO resolution input
        Z_thick = .1  #TODO resolution input

        z_slices = int(math.ceil(Z / Z_thick))
        y_slices = int(math.ceil(Y / Y_thick))
        x_slices = int(math.ceil(X / X_thick))

        x_thick = X / x_slices
        y_thick = Y / y_slices
        z_thick = Z / z_slices

        print('number of slices')
        print((x_slices, y_slices, z_slices))
        print('midpoint')
        print(mid)
        #TODO Bounding box calculation
        imageSize = [x_slices, y_slices, z_slices]
        imageSpacing = [x_thick, y_thick, z_thick]

        voxelType = vtk.VTK_UNSIGNED_CHAR

        imageData = vtk.vtkImageData()
        imageData.SetDimensions(imageSize)
        imageData.AllocateScalars(voxelType, 1)
        thresholder = vtk.vtkImageThreshold()
        thresholder.SetInputData(imageData)
        thresholder.SetInValue(1)
        thresholder.SetOutValue(1)
        # Create volume node
        volumeNode = slicer.vtkMRMLScalarVolumeNode()
        volumeNode.SetSpacing(imageSpacing)
        volumeNode.SetImageDataConnection(thresholder.GetOutputPort())
        # Add volume to scene
        slicer.mrmlScene.AddNode(volumeNode)
        displayNode = slicer.vtkMRMLScalarVolumeDisplayNode()
        slicer.mrmlScene.AddNode(displayNode)
        colorNode = slicer.util.getNode('Grey')
        displayNode.SetAndObserveColorNodeID(colorNode.GetID())
        volumeNode.SetAndObserveDisplayNodeID(displayNode.GetID())
        volumeNode.CreateDefaultStorageNode()

        #Transform the Volume to Fit Around the Model
        transform = slicer.vtkMRMLLinearTransformNode()
        scene.AddNode(transform)
        volumeNode.SetAndObserveTransformNodeID(transform.GetID())

        vTransform = vtk.vtkTransform()
        vTransform.Translate(
            (-X / 2 + mid[0], -Y / 2 + mid[1], -Z / 2 + mid[2]))
        transform.SetAndObserveMatrixTransformToParent(vTransform.GetMatrix())

        #Create a segmentation Node
        segmentationNode = slicer.vtkMRMLSegmentationNode()
        slicer.mrmlScene.AddNode(segmentationNode)
        segmentationNode.CreateDefaultDisplayNodes()
        segmentationNode.SetReferenceImageGeometryParameterFromVolumeNode(
            volumeNode)

        #Add the model as a segmentation
        #sphereSource = vtk.vtkSphereSource()
        #sphereSource.SetRadius(10)
        #sphereSource.SetCenter(6,30,28)
        #sphereSource.Update()
        #segmentationNode.AddSegmentFromClosedSurfaceRepresentation(sphereSource.GetOutput(), "Test")

        segmentID = segmentationNode.GetSegmentation().GenerateUniqueSegmentID(
            "Test")
        segmentationNode.AddSegmentFromClosedSurfaceRepresentation(
            inputModel.GetPolyData(), segmentID)
        #TODO, Unique ID
        segmentationNode.SetMasterRepresentationToBinaryLabelmap()

        modelLabelMap = segmentationNode.GetBinaryLabelmapRepresentation(
            segmentID)  #TODO Unique ID

        segmentationNode.SetMasterRepresentationToBinaryLabelmap()

        shape = list(modelLabelMap.GetDimensions())
        shape.reverse()  #why reverse?
        labelArray = vtk.util.numpy_support.vtk_to_numpy(
            modelLabelMap.GetPointData().GetScalars()).reshape(shape)

        for n in range(1, shape[0] - 1):
            labelArray[n, :, :] = numpy.maximum(labelArray[n, :, :],
                                                labelArray[n - 1, :, :])

        outputPolyData = vtk.vtkPolyData()
        slicer.vtkSlicerSegmentationsModuleLogic.GetSegmentClosedSurfaceRepresentation(
            segmentationNode, segmentID, outputPolyData)

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

        model.SetAndObservePolyData(outputPolyData)

        # Create display node
        modelDisplay = slicer.vtkMRMLModelDisplayNode()
        modelDisplay.SetColor(1, 1, 0)  # yellow
        modelDisplay.SetBackfaceCulling(0)
        modelDisplay.SetScene(scene)
        scene.AddNode(modelDisplay)
        model.SetAndObserveDisplayNodeID(modelDisplay.GetID())

        # Add to scene
        scene.AddNode(model)
示例#40
0
    def __init__(self, path, fiducialListNode):

        fids = fiducialListNode
        scene = slicer.mrmlScene

        points = vtk.vtkPoints()
        polyData = vtk.vtkPolyData()
        polyData.SetPoints(points)

        lines = vtk.vtkCellArray()
        polyData.SetLines(lines)
        linesIDArray = lines.GetData()
        linesIDArray.Reset()
        linesIDArray.InsertNextTuple1(0)

        polygons = vtk.vtkCellArray()
        polyData.SetPolys(polygons)
        idArray = polygons.GetData()
        idArray.Reset()
        idArray.InsertNextTuple1(0)

        for point in path:
            pointIndex = points.InsertNextPoint(*point)
            linesIDArray.InsertNextTuple1(pointIndex)
            linesIDArray.SetTuple1(0, linesIDArray.GetNumberOfTuples() - 1)
            lines.SetNumberOfCells(1)

        # Create model node
        model = slicer.vtkMRMLModelNode()
        model.SetScene(scene)
        model.SetName("Path-%s" % fids.GetName())
        model.SetAndObservePolyData(polyData)

        # Create display node
        modelDisplay = slicer.vtkMRMLModelDisplayNode()
        modelDisplay.SetColor(1, 1, 0)  # yellow
        modelDisplay.SetScene(scene)
        scene.AddNode(modelDisplay)
        model.SetAndObserveDisplayNodeID(modelDisplay.GetID())

        # Add to scene
        modelDisplay.SetInputPolyData(model.GetPolyData())
        scene.AddNode(model)

        # Camera cursor
        sphere = vtk.vtkSphereSource()
        sphere.Update()

        # Create model node
        cursor = slicer.vtkMRMLModelNode()
        cursor.SetScene(scene)
        cursor.SetName("Cursor-%s" % fids.GetName())
        cursor.SetAndObservePolyData(sphere.GetOutput())

        # Create display node
        cursorModelDisplay = slicer.vtkMRMLModelDisplayNode()
        cursorModelDisplay.SetColor(1, 0, 0)  # red
        cursorModelDisplay.SetScene(scene)
        scene.AddNode(cursorModelDisplay)
        cursor.SetAndObserveDisplayNodeID(cursorModelDisplay.GetID())

        # Add to scene
        cursorModelDisplay.SetInputPolyData(sphere.GetOutput())
        scene.AddNode(cursor)

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

        self.transform = transform
示例#41
0
    def setupScene(self):
        logging.info("UltraSound.setupScene")
        '''
      ReferenceToRas transform is used in almost all IGT applications. Reference is the coordinate system
      of a tool fixed to the patient. Tools are tracked relative to Reference, to compensate for patient
      motion. ReferenceToRas makes sure that everything is displayed in an anatomical coordinate system, i.e.
      R, A, and S (Right, Anterior, and Superior) directions in Slicer are correct relative to any
      images or tracked tools displayed.
      ReferenceToRas is needed for initialization, so we need to set it up before calling Guidelet.setupScene().
    '''

        if self.referenceToRas is None or (
                self.referenceToRas and slicer.mrmlScene.GetNodeByID(
                    self.referenceToRas.GetID()) is None):
            self.referenceToRas = slicer.mrmlScene.GetFirstNodeByName(
                'ReferenceToRas')
            if self.referenceToRas is None:
                self.referenceToRas = slicer.vtkMRMLLinearTransformNode()
                self.referenceToRas.SetName("ReferenceToRas")
                m = self.guideletParent.logic.readTransformFromSettings(
                    'ReferenceToRas', self.guideletParent.configurationName)
                if m is None:
                    m = self.guideletParent.logic.createMatrixFromString(
                        '1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1')
                self.referenceToRas.SetMatrixTransformToParent(m)
                slicer.mrmlScene.AddNode(self.referenceToRas)

        # live ultrasound
        liveUltrasoundNodeName = self.guideletParent.parameterNode.GetParameter(
            'LiveUltrasoundNodeName')
        self.liveUltrasoundNode_Reference = slicer.mrmlScene.GetFirstNodeByName(
            liveUltrasoundNodeName)
        if not self.liveUltrasoundNode_Reference:
            imageSpacing = [0.2, 0.2, 0.2]
            # Create an empty image volume
            imageData = vtk.vtkImageData()
            imageData.SetDimensions(self.DEFAULT_IMAGE_SIZE)
            imageData.AllocateScalars(vtk.VTK_UNSIGNED_CHAR, 1)
            thresholder = vtk.vtkImageThreshold()
            thresholder.SetInputData(imageData)
            thresholder.SetInValue(0)
            thresholder.SetOutValue(0)
            # Create volume node
            self.liveUltrasoundNode_Reference = slicer.vtkMRMLScalarVolumeNode(
            )
            self.liveUltrasoundNode_Reference.SetName(liveUltrasoundNodeName)
            self.liveUltrasoundNode_Reference.SetSpacing(imageSpacing)
            self.liveUltrasoundNode_Reference.SetImageDataConnection(
                thresholder.GetOutputPort())
            # Add volume to scene
            slicer.mrmlScene.AddNode(self.liveUltrasoundNode_Reference)
            displayNode = slicer.vtkMRMLScalarVolumeDisplayNode()
            slicer.mrmlScene.AddNode(displayNode)
            colorNode = slicer.mrmlScene.GetFirstNodeByName('Grey')
            displayNode.SetAndObserveColorNodeID(colorNode.GetID())
            self.liveUltrasoundNode_Reference.SetAndObserveDisplayNodeID(
                displayNode.GetID())

        self.plusRemoteNode = slicer.mrmlScene.GetFirstNodeByClass(
            'vtkMRMLPlusRemoteNode')
        if self.plusRemoteNode is None:
            self.plusRemoteNode = slicer.vtkMRMLPlusRemoteNode()
            self.plusRemoteNode.SetName("PlusRemoteNode")
            slicer.mrmlScene.AddNode(self.plusRemoteNode)
        self.plusRemoteNode.AddObserver(
            slicer.vtkMRMLPlusRemoteNode.RecordingStartedEvent,
            self.recordingCommandCompleted)
        self.plusRemoteNode.AddObserver(
            slicer.vtkMRMLPlusRemoteNode.RecordingCompletedEvent,
            self.recordingCommandCompleted)
        self.plusRemoteNode.SetAndObserveOpenIGTLinkConnectorNode(
            self.guideletParent.connectorNode)

        self.setupResliceDriver()
示例#42
0
    def setupScene(self):  #applet specific
        logging.debug('setupScene')
        '''
    ReferenceToRas transform is used in almost all IGT applications. Reference is the coordinate system
    of a tool fixed to the patient. Tools are tracked relative to Reference, to compensate for patient
    motion. ReferenceToRas makes sure that everything is displayed in an anatomical coordinate system, i.e.
    R, A, and S (Right, Anterior, and Superior) directions in Slicer are correct relative to any
    images or tracked tools displayed.
    ReferenceToRas is needed for initialization, so we need to set it up before calling Guidelet.setupScene().
    '''

        self.referenceToRas = slicer.util.getNode('ReferenceToRas')
        if not self.referenceToRas:
            self.referenceToRas = slicer.vtkMRMLLinearTransformNode()
            self.referenceToRas.SetName("ReferenceToRas")
            m = self.logic.readTransformFromSettings('ReferenceToRas',
                                                     self.configurationName)
            if m is None:
                m = self.logic.createMatrixFromString(
                    '1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1')
            self.referenceToRas.SetMatrixTransformToParent(m)
            slicer.mrmlScene.AddNode(self.referenceToRas)

        Guidelet.setupScene(self)

        # Transforms

        logging.debug('Create transforms')
        '''
    In this example we assume that there is a tracked needle in the system. The needle is not
    tracked at its tip, so we need a NeedleTipToNeedle transform to define where the needle tip is.
    In your application Needle may be called Stylus, or maybe you don't need such a tool at all.
    '''

        self.needleToReference = slicer.util.getNode('NeedleToReference')
        if not self.needleToReference:
            self.needleToReference = slicer.vtkMRMLLinearTransformNode()
            self.needleToReference.SetName('NeedleToReference')
            slicer.mrmlScene.AddNode(self.needleToReference)

        self.needleTipToNeedle = slicer.util.getNode('NeedleTipToNeedle')
        if not self.needleTipToNeedle:
            self.needleTipToNeedle = slicer.vtkMRMLLinearTransformNode()
            self.needleTipToNeedle.SetName('NeedleTipToNeedle')
            m = self.logic.readTransformFromSettings('NeedleTipToNeedle',
                                                     self.configurationName)
            if m:
                self.needleTipToNeedle.SetMatrixTransformToParent(m)
            slicer.mrmlScene.AddNode(self.needleTipToNeedle)

        # Models
        logging.debug('Create models')

        self.needleModel = slicer.util.getNode('NeedleModel')
        if not self.needleModel:
            self.needleModel = slicer.modules.createmodels.logic(
            ).CreateNeedle(80, 1.0, 2.5, 0)
            self.needleModel.SetName('NeedleModel')

        # Build transform tree
        logging.debug('Set up transform tree')

        self.needleToReference.SetAndObserveTransformNodeID(
            self.referenceToRas.GetID())
        self.needleTipToNeedle.SetAndObserveTransformNodeID(
            self.needleToReference.GetID())
        self.needleModel.SetAndObserveTransformNodeID(
            self.needleTipToNeedle.GetID())

        # Hide slice view annotations (patient name, scale, color bar, etc.) as they
        # decrease reslicing performance by 20%-100%
        logging.debug('Hide slice view annotations')
        import DataProbe
        dataProbeUtil = DataProbe.DataProbeLib.DataProbeUtil()
        dataProbeParameterNode = dataProbeUtil.getParameterNode()
        dataProbeParameterNode.SetParameter('showSliceViewAnnotations', '0')
    def refineLandmark(self, state):
        """Refine the specified landmark"""
        # Refine landmark, or if none, do nothing
        #     Crop images around the fiducial
        #     Affine registration of the cropped images
        #     Transform the fiducial using the transformation
        #
        # No need to take into account the current transformation because landmarks are in World RAS
        timing = False
        if self.VerboseMode == "Verbose":
            timing = True

        if state.fixed == None or state.moving == None or state.fixedFiducials == None or state.movingFiducials == None or state.currentLandmarkName == None:
            print "Cannot refine landmarks. Images or landmarks not selected."
            return

        print("Refining landmark " +
              state.currentLandmarkName) + " using " + self.name

        start = time.time()

        volumes = (state.fixed, state.moving)
        (fixedVolume, movingVolume) = volumes

        slicer.mrmlScene.StartState(slicer.mrmlScene.BatchProcessState)
        landmarks = state.logic.landmarksForVolumes(volumes)

        cvpn = slicer.vtkMRMLCropVolumeParametersNode()
        cvpn.SetInterpolationMode(1)
        cvpn.SetVoxelBased(1)
        fixedPoint = [
            0,
        ] * 3
        movingPoint = [
            0,
        ] * 3

        (fixedFiducial, movingFiducial) = landmarks[state.currentLandmarkName]

        (fixedList, fixedIndex) = fixedFiducial
        (movingList, movingIndex) = movingFiducial

        # define an roi for the fixed
        if timing: roiStart = time.time()
        roiFixed = slicer.vtkMRMLAnnotationROINode()
        slicer.mrmlScene.AddNode(roiFixed)

        fixedList.GetNthFiducialPosition(fixedIndex, fixedPoint)
        roiFixed.SetDisplayVisibility(0)
        roiFixed.SelectableOff()
        roiFixed.SetXYZ(fixedPoint)
        roiFixed.SetRadiusXYZ(30, 30, 30)

        # crop the fixed. note we hide the display node temporarily to avoid the automated
        # window level calculation on temporary nodes created by cloning
        cvpn.SetROINodeID(roiFixed.GetID())
        cvpn.SetInputVolumeNodeID(fixedVolume.GetID())
        fixedDisplayNode = fixedVolume.GetDisplayNode()
        fixedVolume.SetAndObserveDisplayNodeID(
            'This is not a valid DisplayNode ID')
        if timing: roiEnd = time.time()
        if timing: cropStart = time.time()
        state.logic.cropLogic.Apply(cvpn)
        if timing: cropEnd = time.time()
        croppedFixedVolume = slicer.mrmlScene.GetNodeByID(
            cvpn.GetOutputVolumeNodeID())
        fixedVolume.SetAndObserveDisplayNodeID(fixedDisplayNode.GetID())

        # define an roi for the moving
        if timing: roi2Start = time.time()
        roiMoving = slicer.vtkMRMLAnnotationROINode()
        slicer.mrmlScene.AddNode(roiMoving)

        movingList.GetNthFiducialPosition(movingIndex, movingPoint)
        roiMoving.SetDisplayVisibility(0)
        roiMoving.SelectableOff()
        roiMoving.SetXYZ(movingPoint)
        if self.LocalBRAINSFitMode == "Small":
            roiMoving.SetRadiusXYZ(45, 45, 45)
        else:
            roiMoving.SetRadiusXYZ(60, 60, 60)

        # crop the moving. note we hide the display node temporarily to avoid the automated
        # window level calculation on temporary nodes created by cloning
        cvpn.SetROINodeID(roiMoving.GetID())
        cvpn.SetInputVolumeNodeID(movingVolume.GetID())
        movingDisplayNode = movingVolume.GetDisplayNode()
        movingVolume.SetAndObserveDisplayNodeID(
            'This is not a valid DisplayNode ID')
        if timing: roi2End = time.time()
        if timing: crop2Start = time.time()
        state.logic.cropLogic.Apply(cvpn)
        if timing: crop2End = time.time()
        croppedMovingVolume = slicer.mrmlScene.GetNodeByID(
            cvpn.GetOutputVolumeNodeID())
        movingVolume.SetAndObserveDisplayNodeID(movingDisplayNode.GetID())

        if timing:
            print 'Time to set up fixed ROI was ' + str(roiEnd -
                                                        roiStart) + ' seconds'
        if timing:
            print 'Time to set up moving ROI was ' + str(
                roi2End - roi2Start) + ' seconds'
        if timing:
            print 'Time to crop fixed volume ' + str(cropEnd -
                                                     cropStart) + ' seconds'
        if timing:
            print 'Time to crop moving volume ' + str(crop2End -
                                                      crop2Start) + ' seconds'

        #
        transform = slicer.vtkMRMLLinearTransformNode()
        slicer.mrmlScene.AddNode(transform)
        matrix = vtk.vtkMatrix4x4()

        # define the registration parameters
        minPixelSpacing = min(croppedFixedVolume.GetSpacing())
        parameters = {}
        parameters['fixedVolume'] = croppedFixedVolume.GetID()
        parameters['movingVolume'] = croppedMovingVolume.GetID()
        parameters['linearTransform'] = transform.GetID()
        parameters['useRigid'] = True
        parameters['initializeTransformMode'] = 'useGeometryAlign'
        parameters['samplingPercentage'] = 0.2
        parameters['minimumStepLength'] = 0.1 * minPixelSpacing
        parameters['maximumStepLength'] = minPixelSpacing

        # run the registration
        if timing: regStart = time.time()
        slicer.cli.run(slicer.modules.brainsfit,
                       None,
                       parameters,
                       wait_for_completion=True)
        if timing: regEnd = time.time()
        if timing:
            print 'Time for local registration ' + str(regEnd -
                                                       regStart) + ' seconds'

        # apply the local transform to the landmark
        #print transform
        if timing: resultStart = time.time()
        transform.GetMatrixTransformToWorld(matrix)
        matrix.Invert()
        tp = [
            0,
        ] * 4
        tp = matrix.MultiplyPoint(fixedPoint + [
            1,
        ])
        #print fixedPoint, movingPoint, tp[:3]

        movingList.SetNthFiducialPosition(movingIndex, tp[0], tp[1], tp[2])
        if timing: resultEnd = time.time()
        if timing:
            print 'Time for transforming landmark was ' + str(
                resultEnd - resultStart) + ' seconds'

        # clean up cropped volmes, need to reset the foreground/background display before we delete it
        if timing: cleanUpStart = time.time()
        slicer.mrmlScene.RemoveNode(croppedFixedVolume)
        slicer.mrmlScene.RemoveNode(croppedMovingVolume)
        slicer.mrmlScene.RemoveNode(roiFixed)
        slicer.mrmlScene.RemoveNode(roiMoving)
        slicer.mrmlScene.RemoveNode(transform)
        roiFixed = None
        roiMoving = None
        transform = None
        matrix = None
        if timing: cleanUpEnd = time.time()
        if timing:
            print 'Cleanup took ' + str(cleanUpEnd - cleanUpStart) + ' seconds'

        end = time.time()
        print 'Refined landmark ' + state.currentLandmarkName + ' in ' + str(
            end - start) + ' seconds'

        slicer.mrmlScene.EndState(slicer.mrmlScene.BatchProcessState)
示例#44
0
    def registrarButton(self):
        mvNode = self.outputRegSelector.currentNode()
        inputVolume = self.inputRegSelector.currentNode()
        """
    Run the actual algorithm
    """
        #se obtiene la escena y se obtiene el volumen 4D a partir del Volumen 4D de
        #entrada de la ventana desplegable
        escena = slicer.mrmlScene
        imagenvtk4D = inputVolume.GetImageData()
        #Se obtiene el número de volúmenes que tiene el volumen 4D
        numero_imagenes = inputVolume.GetNumberOfFrames()
        print('imagenes: ' + str(numero_imagenes))
        #filtro vtk para descomponer un volumen 4D
        extract1 = vtk.vtkImageExtractComponents()
        extract1.SetInputData(imagenvtk4D)
        #matriz de transformación
        ras2ijk = vtk.vtkMatrix4x4()
        ijk2ras = vtk.vtkMatrix4x4()
        #le solicitamos al volumen original que nos devuelva sus matrices
        inputVolume.GetRASToIJKMatrix(ras2ijk)
        inputVolume.GetIJKToRASMatrix(ijk2ras)
        #creo un volumen nuevo
        volumenFijo = slicer.vtkMRMLScalarVolumeNode()
        volumenSalida = slicer.vtkMRMLMultiVolumeNode()

        #le asigno las transformaciones
        volumenFijo.SetRASToIJKMatrix(ras2ijk)
        volumenFijo.SetIJKToRASMatrix(ijk2ras)
        #le asigno el volumen 3D fijo
        imagen_fija = extract1.SetComponents(0)
        extract1.Update()
        volumenFijo.SetName('fijo')
        volumenFijo.SetAndObserveImageData(extract1.GetOutput())
        #anado el nuevo volumen a la escena
        escena.AddNode(volumenFijo)
        #se crea un vector para guardar el número del volumen que tenga un
        #desplazamiento de mas de 4mm en cualquier dirección
        v = []

        #se hace un ciclo for para registrar todos los demás volúmenes del volumen 4D
        #con el primer volumen que se definió como fijo
        frameLabelsAttr = ''
        frames = []
        volumeLabels = vtk.vtkDoubleArray()

        volumeLabels.SetNumberOfTuples(numero_imagenes)
        volumeLabels.SetNumberOfComponents(1)
        volumeLabels.Allocate(numero_imagenes)

        for i in range(numero_imagenes):
            # extraigo la imagen móvil en la posición i+1 ya que el primero es el fijo
            imagen_movil = extract1.SetComponents(
                i + 1)  #Seleccionar un volumen i+1
            extract1.Update()
            #Creo el volumen móvil, y realizo el mismo procedimiento que con el fijo
            volumenMovil = slicer.vtkMRMLScalarVolumeNode()
            volumenMovil.SetRASToIJKMatrix(ras2ijk)
            volumenMovil.SetIJKToRASMatrix(ijk2ras)
            volumenMovil.SetAndObserveImageData(extract1.GetOutput())
            volumenMovil.SetName('movil ' + str(i + 1))
            escena.AddNode(volumenMovil)

            #creamos la transformada para alinear los volúmenes
            transformadaSalida = slicer.vtkMRMLLinearTransformNode()
            transformadaSalida.SetName('Transformadaderegistro' + str(i + 1))
            slicer.mrmlScene.AddNode(transformadaSalida)
            #parámetros para la operación de registro
            parameters = {}
            #parameters['InitialTransform'] = transI.GetID()
            parameters['fixedVolume'] = volumenFijo.GetID()
            parameters['movingVolume'] = volumenMovil.GetID()
            parameters['transformType'] = 'Rigid'
            parameters['outputTransform'] = transformadaSalida.GetID()
            frames.append(volumenMovil)
            ##      parameters['outputVolume']=volumenSalida.GetID()
            #Realizo el registro
            cliNode = slicer.cli.run(slicer.modules.brainsfit,
                                     None,
                                     parameters,
                                     wait_for_completion=True)
            #obtengo la transformada lineal que se usó en el registro
            transformada = escena.GetFirstNodeByName('Transformadaderegistro' +
                                                     str(i + 1))
            #Obtengo la matriz de la transformada, esta matriz es de dimensiones 4x4
            #en la cual estan todos los desplazamientos y rotaciones que se hicieron
            #en la transformada, a partir de ella se obtienen los volumenes que se
            #desplazaron mas de 4mm en cualquier direccion

            hm = vtk.vtkMatrix4x4()
            transformadaSalida.GetMatrixTransformToWorld(hm)
            volumenMovil.ApplyTransformMatrix(hm)
            volumenMovil.SetAndObserveTransformNodeID(None)

            frameId = i
            volumeLabels.SetComponent(i, 0, frameId)
            frameLabelsAttr += str(frameId) + ','

##      Matriz=transformada.GetMatrixTransformToParent()
##      LR=Matriz.GetElement(0,3)#dirección izquierda o derecha en la fila 1, columna 4
##      PA=Matriz.GetElement(1,3)#dirección anterior o posterior en la fila 2, columna 4
##      IS=Matriz.GetElement(2,3)#dirección inferior o superior en la fila 3, columna 4
##      #Se mira si el volumen "i" en alguna dirección tuvo un desplazamiento
##      #mayor a 4mm, en caso de ser cierto se guarda en el vector "v"
##      if abs(LR)>4:
##        v.append(i+2)
##      elif abs(PA)>4:
##        v.append(i+2)
##      elif abs(IS)>4:
##        v.append(i+2)
##    print("MovilExtent: "+str(volumenMovil.GetImageData().GetExtent()))
####    print("valor de f: "+ str(volumenMovil))
##    frameLabelsAttr = frameLabelsAttr[:-1]

        mvImage = vtk.vtkImageData()
        mvImage.SetExtent(volumenMovil.GetImageData().GetExtent()
                          )  ##Se le asigna la dimensión del miltuvolumen
        mvImage.AllocateScalars(
            volumenMovil.GetImageData().GetScalarType(), numero_imagenes
        )  ##Se le asigna el tipo y número de cortes al multivolumen
        mvImageArray = vtk.util.numpy_support.vtk_to_numpy(
            mvImage.GetPointData().GetScalars()
        )  ## Se crea la matriz de datos donde va a ir la imagen

        mat = vtk.vtkMatrix4x4()

        ##Se hace la conversión y se obtiene la matriz de transformación del nodo
        volumenMovil.GetRASToIJKMatrix(mat)
        mvNode.SetRASToIJKMatrix(mat)
        volumenMovil.GetIJKToRASMatrix(mat)
        mvNode.SetIJKToRASMatrix(mat)

        print("frameId: " + str(frameId))
        print("# imag: " + str(numero_imagenes))
        ##    print("Long frame1: "+str(len(frame)))
        print("Long frames: " + str(len(frames)))

        ##
        for frameId in range(numero_imagenes):
            # TODO: check consistent size and orientation!
            frame = frames[frameId]
            frameImage = frame.GetImageData()
            frameImageArray = vtk.util.numpy_support.vtk_to_numpy(
                frameImage.GetPointData().GetScalars())
            mvImageArray.T[frameId] = frameImageArray


##Se crea el nodo del multivolumen

        mvDisplayNode = slicer.mrmlScene.CreateNodeByClass(
            'vtkMRMLMultiVolumeDisplayNode')
        mvDisplayNode.SetScene(slicer.mrmlScene)
        slicer.mrmlScene.AddNode(mvDisplayNode)
        mvDisplayNode.SetReferenceCount(mvDisplayNode.GetReferenceCount() - 1)
        mvDisplayNode.SetDefaultColorMap()

        mvNode.SetAndObserveDisplayNodeID(mvDisplayNode.GetID())
        mvNode.SetAndObserveImageData(mvImage)
        mvNode.SetNumberOfFrames(numero_imagenes)

        mvNode.SetLabelArray(volumeLabels)
        mvNode.SetLabelName('na')
        mvNode.SetAttribute('MultiVolume.FrameLabels', frameLabelsAttr)
        mvNode.SetAttribute('MultiVolume.NumberOfFrames', str(numero_imagenes))
        mvNode.SetAttribute('MultiVolume.FrameIdentifyingDICOMTagName', 'NA')
        mvNode.SetAttribute('MultiVolume.FrameIdentifyingDICOMTagUnits', 'na')

        mvNode.SetName('MultiVolume Registrado')
        Helper.SetBgFgVolumes(mvNode.GetID(), None)

        print('Registro completo')
        #al terminar el ciclo for con todos los volúmenes registrados se genera una
        #ventana emergente con un mensaje("Registro completo!") y mostrando los
        #volúmenes que se desplazaron mas de 4mm
        qt.QMessageBox.information(slicer.util.mainWindow(), 'Slicer Python',
                                   'Registro completo')
        return True
示例#45
0
    def computeSpline(self, spline, startVertexID, endVertexID, startPointPosition, endPointPosition, resolution):
        print ("compute spline")
        scene = slicer.mrmlScene

        dijkstra = vtk.vtkDijkstraGraphGeodesicPath()
        dijkstra.SetInputData(self.modelNode.GetPolyData())
        dijkstra.SetStartVertex(startVertexID)
        dijkstra.SetEndVertex(endVertexID)
        dijkstra.Update()

        #compute step size in according to resolution

        vertices = dijkstra.GetOutput().GetPoints()
        numVertices = vertices.GetNumberOfPoints()
        resStepSize = float(numVertices) / (float(resolution) - 1.0)# -2 because of start and end point

        print (numVertices)
        print (resolution)
        print (resStepSize)
        equidistantIndices = []

        curStep = 0
        for i in range(0, int(resolution)):
            curStep = (i * resStepSize) - 1
            equidistantIndices.append(int(curStep + 0.5))

        #create spline
        splinePoints = []
        points = vtk.vtkPoints()
        for index in equidistantIndices:
            print ("index")
            print (index)
            print ("position")
            position = [0, 0, 0]
            vertices.GetPoint(index, position)
            print (position)
            points.InsertNextPoint(position)
            splinePoints.append(position)

        spline.points = splinePoints

        parametricSpline = vtk.vtkParametricSpline()
        parametricSpline.SetPoints(points)

        functionSource = vtk.vtkParametricFunctionSource()
        functionSource.SetParametricFunction(parametricSpline)
        functionSource.Update()

        #create model node
        splineModel = slicer.vtkMRMLModelNode()
        splineModel.SetScene(scene)
        splineModel.SetName("splineModel-%i" % 1) #todo
        splineModel.SetAndObservePolyData(functionSource.GetOutput())

        #create display node
        splineModelDisplay = slicer.vtkMRMLModelDisplayNode()
        splineModelDisplay.SetColor(1, 0, 0)
        splineModelDisplay.SetOpacity(1)
        splineModelDisplay.SetLineWidth(4)
        splineModelDisplay.SliceIntersectionVisibilityOn()

        splineModelDisplay.SetScene(scene)
        scene.AddNode(splineModelDisplay)
        splineModel.SetAndObserveDisplayNodeID(splineModelDisplay.GetID())

        # add to scene
        splineModelDisplay.GetPolyData = functionSource.GetOutput()

        scene.AddNode(splineModel)

        splineModelTransform = slicer.vtkMRMLLinearTransformNode()
        splineModelTransform.SetName("SplineModelTransform-%i" % 1) # todo

        scene.AddNode(splineModelTransform)
示例#46
0
 def clipping(self):
     planeCollection = vtk.vtkPlaneCollection()
     harden = slicer.vtkSlicerTransformLogic()
     tempTransform = slicer.vtkMRMLLinearTransformNode()
     tempTransform.HideFromEditorsOn()
     slicer.mrmlScene.AddNode(tempTransform)
     numNodes = slicer.mrmlScene.GetNumberOfNodesByClass("vtkMRMLModelNode")
     dictionnaryModel = dict()
     hardenModelIDdict = dict()
     landmarkDescriptionDict = dict()
     modelIDdict = dict()
     for i in range(3, numNodes):
         planeCollection.RemoveAllItems()
         mh = slicer.mrmlScene.GetNthNodeByClass(i, "vtkMRMLModelNode")
         if mh.GetDisplayVisibility() == 0:
             continue
         model = slicer.util.getNode(mh.GetName())
         transform = model.GetParentTransformNode()
         if transform:
             tempTransform.Copy(transform)
             harden.hardenTransform(tempTransform)
             m = vtk.vtkMatrix4x4()
             tempTransform.GetMatrixTransformToParent(m)
             m.Invert(m, m)
         else:
             m = vtk.vtkMatrix4x4()
         for key, planeDef in self.planeDict.items():
             hardenP = m.MultiplyPoint(planeDef.P)
             hardenN = m.MultiplyPoint(planeDef.n)
             if planeDef.boxState:
                 planeDef.vtkPlane.SetOrigin(hardenP[0], hardenP[1],
                                             hardenP[2])
                 if planeDef.negState:
                     planeDef.vtkPlane.SetNormal(-hardenN[0], -hardenN[1],
                                                 -hardenN[2])
                 if planeDef.posState:
                     planeDef.vtkPlane.SetNormal(hardenN[0], hardenN[1],
                                                 hardenN[2])
                 planeCollection.AddItem(planeDef.vtkPlane)
         dictionnaryModel[model.GetID()] = model.GetPolyData()
         polyData = model.GetPolyData()
         clipper = vtk.vtkClipClosedSurface()
         clipper.SetClippingPlanes(planeCollection)
         clipper.SetInputData(polyData)
         clipper.SetGenerateFaces(1)
         clipper.SetScalarModeToLabels()
         clipper.Update()
         polyDataNew = clipper.GetOutput()
         model.SetAndObservePolyData(polyDataNew)
         # Checking if one ore more fiducial list are connected to this model
         list = slicer.mrmlScene.GetNodesByClass(
             "vtkMRMLMarkupsFiducialNode")
         end = list.GetNumberOfItems()
         for i in range(0, end):
             fidList = list.GetItemAsObject(i)
             if fidList.GetAttribute("connectedModelID"):
                 if fidList.GetAttribute(
                         "connectedModelID") == model.GetID():
                     modelIDdict[fidList.GetID()], hardenModelIDdict[fidList.GetID()], landmarkDescriptionDict[fidList.GetID()] = \
                         self.unprojectLandmarks(fidList)
     return dictionnaryModel, modelIDdict, hardenModelIDdict, landmarkDescriptionDict