コード例 #1
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.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
コード例 #2
0
 def createIntermediateHardenModel(self, model):
     hardenModel = slicer.mrmlScene.GetNodesByName("SurfaceRegistration_" + model.GetName() + "_hardenCopy_" + str(
         slicer.app.applicationPid())).GetItemAsObject(0)
     if hardenModel is None:
         hardenModel = slicer.vtkMRMLModelNode()
     hardenPolyData = vtk.vtkPolyData()
     hardenPolyData.DeepCopy(model.GetPolyData())
     hardenModel.SetAndObservePolyData(hardenPolyData)
     hardenModel.SetName(
         "SurfaceRegistration_" + model.GetName() + "_hardenCopy_" + str(slicer.app.applicationPid()))
     if model.GetParentTransformNode():
         hardenModel.SetAndObserveTransformNodeID(model.GetParentTransformNode().GetID())
     hardenModel.HideFromEditorsOn()
     slicer.mrmlScene.AddNode(hardenModel)
     logic = slicer.vtkSlicerTransformLogic()
     logic.hardenTransform(hardenModel)
     return hardenModel
コード例 #3
0
 def createIntermediateHardenModel(self, model):
     hardenModel = slicer.mrmlScene.GetNodesByName(
         "SurfaceRegistration_" + model.GetName() + "_hardenCopy_" +
         str(slicer.app.applicationPid())).GetItemAsObject(0)
     if hardenModel is None:
         hardenModel = slicer.vtkMRMLModelNode()
     hardenPolyData = vtk.vtkPolyData()
     hardenPolyData.DeepCopy(model.GetPolyData())
     hardenModel.SetAndObservePolyData(hardenPolyData)
     hardenModel.SetName("SurfaceRegistration_" + model.GetName() +
                         "_hardenCopy_" + str(slicer.app.applicationPid()))
     if model.GetParentTransformNode():
         hardenModel.SetAndObserveTransformNodeID(
             model.GetParentTransformNode().GetID())
     hardenModel.HideFromEditorsOn()
     slicer.mrmlScene.AddNode(hardenModel)
     logic = slicer.vtkSlicerTransformLogic()
     logic.hardenTransform(hardenModel)
     return hardenModel
コード例 #4
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.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
コード例 #5
0
  def run(self, inputVolumeNode, inputFiducialNode, vtIDT, vtMethodID):
      logging.info('Processing started')
      self.vsc   = VisSimCommon.VisSimCommonLogic()
      self.vsc.setGlobalVariables(1)
      print("setup local paths variables.........................")  
      vtID =int(vtIDT) 
      # set the correct models paths:
      modelPath       =   self.vsc.vtVars['modelPath']+  ',Default'+",Mdl" + self.vsc.vtVars['Styp']+ str(vtID)        +self.vsc.vtVars['imgType'] 
      modelPath       =   os.path.join(*modelPath.split(","))
      modelSegPath    =   self.vsc.vtVars['modelPath'] + self.vsc.vtVars['segT']+",Mdl"+self.vsc.vtVars['Styp']+ str(vtID)+ self.vsc.vtVars['sgT'] +self.vsc.vtVars['imgType'] 
      modelSegPath    =   os.path.join(*modelSegPath.split(","))
      modelLigPtsPath = self.vsc.vtVars['modelLigPtsPath'] +str(vtID)+self.vsc.vtVars['vtPtsLigSuff']+".fcsv"

      # set the results paths:       
      resTransPathOld  = os.path.join(self.vsc.vtVars['outputPath'] ,"TransformParameters.0.txt")
      resTransPath=resTransPathOld[0:-6]+'Pars.txt'        
      resOldDefPath = os.path.join(self.vsc.vtVars['outputPath'] , "deformationField"+self.vsc.vtVars['imgType'])
      resDefPath    = os.path.join(self.vsc.vtVars['outputPath'] , inputVolumeNode.GetName()+"_C"+str(vtID)+"_dFld"+self.vsc.vtVars['imgType'])
      inputImgName  = inputVolumeNode.GetStorageNode().GetFileName()
      inputImgName  = basename(os.path.splitext(inputImgName)[0])    
        
      segNodeName       = inputVolumeNode.GetName() + "_C"   +str(vtID)+".Seg"                 
      ligPtsNodeName    = inputVolumeNode.GetName() + "_C"   +str(vtID)+"_LigPts"
      transNodeName     = inputVolumeNode.GetName() + "_C"   +str(vtID)+ "_Transform"

      print("removeOtputsFolderContents ........................ ")  
      #only for this vertebra
      self.vsc.removeOtputsFolderContents()
      # check if the model is found
      if not isfile(modelPath): 
            print >> sys.stderr, "ERROR: model is not found"            
            print("modelPath: " + modelPath)
            return -1
      # endif

      print("ptRAS2IJK ........................ ")          
      # for multiple vertebra, it is enough to have one markup node
      # Get IJK point from the fiducial to use in cropping
      newFid= True
      for j in range (inputFiducialNode.GetNumberOfFiducials() ):
             if inputFiducialNode.GetNthFiducialLabel(j)==("C"+str(vtID)) :
                break
              #endif
      #endfor

      # Get IJK point from the fiducial to use in cropping          
      inputPoint = self.vsc.ptRAS2IJK(inputFiducialNode,inputVolumeNode,j)
      # TODO: add better condition
      if  np.sum(inputPoint)== 0 :
            print("Error: select vertebra point")
            return -1
      #endif  
      fnm = os.path.join(self.vsc.vtVars['outputPath'] , inputVolumeNode.GetName()+"_C"+str(vtID)+"_vtLocations.fcsv")                           
      sR = slicer.util.saveNode(inputFiducialNode, fnm )  

      #Remove old resulted nodes
      for node in slicer.util.getNodes():
          if ( ligPtsNodeName    == node): slicer.mrmlScene.RemoveNode(node) #endif
          if ( segNodeName       == node): slicer.mrmlScene.RemoveNode(node) #endif
          if ( transNodeName == node): slicer.mrmlScene.RemoveNode(node) #endif
      #endfor    

      inputPointT = self.vsc.v2t(inputPoint) 
      print ("************  Cropping  **********************")
      self.vsc.vtVars['intputCropPath'] = self.vsc.runCropping(inputVolumeNode, inputPointT,self.vsc.vtVars['croppingLength'],  self.vsc.vtVars['RSxyz'],  self.vsc.vtVars['hrChk'], str(vtID) )                    
      [success, croppedNode] = slicer.util.loadVolume(self.vsc.vtVars['intputCropPath'], returnNode=True)
      croppedNode.SetName(inputVolumeNode.GetName()+"_C"+str(vtID)+"Crop")        

      print ("************  Register model to cropped input image **********************")
      cTI = self.vsc.runElastix(self.vsc.vtVars['elastixBinPath'],self.vsc.vtVars['intputCropPath'],  modelPath, self.vsc.vtVars['outputPath'], self.vsc.vtVars['parsPath'], self.vsc.vtVars['noOutput'], "554")
      copyfile(resTransPathOld, resTransPath)
      #genrates deformation field 
      cTR = self.vsc.runTransformix(self.vsc.vtVars['transformixBinPath'],modelPath, self.vsc.vtVars['outputPath'], resTransPath, self.vsc.vtVars['noOutput'], "556")
      # rename fthe file:
      os.rename(resOldDefPath,resDefPath)       
      print ("************  Load deformation field Transform  **********************")
      [success, vtTransformNode] = slicer.util.loadTransform(resDefPath, returnNode = True)
      vtTransformNode.SetName(transNodeName)
      print ("************  Transform segmentation  **********************")
      [success, vtSegNode] = slicer.util.loadSegmentation(modelSegPath, returnNode = True)
      vtSegNode.SetName(segNodeName)
      vtSegNode.SetAndObserveTransformNodeID(vtTransformNode.GetID()) # movingAllMarkupNode should be loaded, the file contains all points
      slicer.vtkSlicerTransformLogic().hardenTransform(vtSegNode) # apply the transform
      vtSegNode.CreateClosedSurfaceRepresentation() 
      fnm = os.path.join(self.vsc.vtVars['outputPath'] , vtSegNode.GetName()+".nrrd")                             
      sR = slicer.util.saveNode(vtSegNode, fnm )  
                     
      if self.vsc.s2b(self.vsc.vtVars['ligChk']):            
           print ("************  Transform Ligaments Points **********************")
           [success, vtLigPtsNode] = slicer.util.loadMarkupsFiducialList  (modelLigPtsPath, returnNode = True)
           vtLigPtsNode.GetDisplayNode().SetSelectedColor(1,0,0)           
           vtLigPtsNode.GetDisplayNode().SetTextScale(0.5)                      
           vtLigPtsNode.SetName(ligPtsNodeName)
           vtLigPtsNode.SetAndObserveTransformNodeID(vtTransformNode.GetID()) 
           slicer.vtkSlicerTransformLogic().hardenTransform(vtLigPtsNode) # apply the transform
           # needed in extract scaled model
           self.vtLigPtsNode = vtLigPtsNode    
           fnm = os.path.join(self.vsc.vtVars['outputPath'] , vtLigPtsNode.GetName()+".fcsv")                             
           sR = slicer.util.saveNode(vtLigPtsNode, fnm ) 
   
      #endif 
      # Display the result if no error
      # Clear vertebra location labels
      if  (cTI==0) and (cTR==0):
          # change the model type from vtk to stl 
          msn=slicer.vtkMRMLModelStorageNode()
          msn.SetDefaultWriteFileExtension('stl')
          slicer.mrmlScene.AddDefaultNode(msn)        
          print("get vertebra information")
          tableName =  inputVolumeNode.GetName()+"_tbl"
          # create only if it does not exist
          try:
              # if table exists, don't create a new one.
              spTblNode =  slicer.util.getNode(tableName)
              print("table is found .........................................")
          except:
              #create a new table                
              spTblNode= None
          #endtry
          spTblNode = self.vsc.getItemInfo( vtSegNode, croppedNode, spTblNode, vtID)
      else:
          print("error happened during segmentation ")
      #endif
        
      #Remove temporary files and nodes:
      self.vsc.removeTmpsFiles()     
      print("================= vertebra analysis is complete  =====================")
      logging.info('Processing completed')
      return vtSegNode
コード例 #6
0
 def transformNodewithBspline(self, movingSimilarityLabel, BSPLINETransform):
   # tranform input node using bspline transform from registration
   movingSimilarityLabel.SetAndObserveTransformNodeID(BSPLINETransform.GetID())
   slicer.vtkSlicerTransformLogic().hardenTransform(movingSimilarityLabel) # hardens transform
コード例 #7
0
    def run(self, fixedVolumeNode, fixedFiducialNode, movingVolumeNode,
            movingFiducialNode):
        logging.info('Processing started')
        print(fixedVolumeNode.GetName())
        print(movingVolumeNode.GetName())
        self.vsc = VisSimCommon.VisSimCommonLogic()
        self.vsc.setGlobalVariables(0)

        self.vsc.removeOtputsFolderContents()

        # results paths
        resTransPath = os.path.join(self.vsc.vtVars['outputPath'],
                                    "TransformParameters.0.txt")
        resOldDefPath = os.path.join(
            self.vsc.vtVars['outputPath'],
            "deformationField" + self.vsc.vtVars['imgType'])
        resDefPath = os.path.join(
            self.vsc.vtVars['outputPath'],
            movingVolumeNode.GetName() + "_dFld" + self.vsc.vtVars['imgType'])
        transNodeName = movingVolumeNode.GetName() + "_Transform"

        # Save original fixed and moving images
        if fixedVolumeNode.GetStorageNode() is None:
            fixedImgPath = os.path.join(self.vsc.vtVars['vissimPath'],
                                        fixedVolumeNode.GetName() + ".nrrd")
            slicer.util.saveNode(fixedVolumeNode, fixedImgPath)
        fixedPath = fixedVolumeNode.GetStorageNode().GetFileName()

        if movingVolumeNode.GetStorageNode() is None:
            movingImgPath = os.path.join(self.vsc.vtVars['vissimPath'],
                                         movingVolumeNode.GetName() + ".nrrd")
            slicer.util.saveNode(movingVolumeNode, movingImgPath)
        movingPath = movingVolumeNode.GetStorageNode().GetFileName()

        # Get IJK point from the fiducial to use in cropping
        fixedPoint = self.vsc.ptRAS2IJK(fixedFiducialNode, fixedVolumeNode, 0)
        print("run fixed point: ============================")
        print(fixedVolumeNode.GetName())
        print(fixedPoint)
        # TODO: add better condition
        if np.sum(fixedPoint) == 0:
            print("Error: select cochlea fixed point")
            return -1
        #endif
        fnm = os.path.join(self.vsc.vtVars['outputPath'],
                           fixedVolumeNode.GetName() + "_F_Cochlea_Pos.fcsv")
        sR = slicer.util.saveNode(fixedFiducialNode, fnm)

        movingPoint = self.vsc.ptRAS2IJK(movingFiducialNode, movingVolumeNode,
                                         0)
        print("run moving point: ============================")
        print(movingVolumeNode.GetName())
        print(movingPoint)

        # TODO: add better condition
        if np.sum(fixedPoint) == 0:
            print("Error: select cochlea moving point")
            return -1
        #endif
        fnm = os.path.join(self.vsc.vtVars['outputPath'],
                           movingVolumeNode.GetName() + "_M_Cochlea_Pos.fcsv")
        sR = slicer.util.saveNode(movingFiducialNode, fnm)

        #Remove old resulted nodes
        #for node in slicer.util.getNodes():
        #    if ( "result"   in [node].GetName() ): slicer.mrmlScene.RemoveNode(node) #endif
        #endfor

        # TODO: add better condition
        if (np.sum(fixedPoint) == 0) and (np.sum(movingPoint) == 0):
            #qt.QMessageBox.critical(slicer.util.mainWindow(),'SlicerCochleaRegistration', 'Cochlea locations are missing')
            print("Error: select cochlea points in fixed and moving images")
            return False
        #endif

        fixedPointT = self.vsc.v2t(fixedPoint)
        movingPointT = self.vsc.v2t(movingPoint)

        print("=================== Cropping =====================")
        self.vsc.vtVars['fixedCropPath'] = self.vsc.runCropping(
            fixedVolumeNode, fixedPointT, self.vsc.vtVars['croppingLength'],
            self.vsc.vtVars['RSxyz'], self.vsc.vtVars['hrChk'], 0)
        [success, croppedFixedNode
         ] = slicer.util.loadVolume(self.vsc.vtVars['fixedCropPath'],
                                    returnNode=True)
        croppedFixedNode.SetName(fixedVolumeNode.GetName() + "_F_Crop")

        self.vsc.vtVars['movingCropPath'] = self.vsc.runCropping(
            movingVolumeNode, movingPointT, self.vsc.vtVars['croppingLength'],
            self.vsc.vtVars['RSxyz'], self.vsc.vtVars['hrChk'], 0)
        [success, croppedMovingNode
         ] = slicer.util.loadVolume(self.vsc.vtVars['movingCropPath'],
                                    returnNode=True)
        croppedMovingNode.SetName(movingVolumeNode.GetName() + "_M_Crop")
        print(
            "************  Register cropped moving image to cropped fixed image **********************"
        )
        cTI = self.vsc.runElastix(self.vsc.vtVars['elastixBinPath'],
                                  self.vsc.vtVars['fixedCropPath'],
                                  self.vsc.vtVars['movingCropPath'],
                                  self.vsc.vtVars['outputPath'],
                                  self.vsc.vtVars['parsPath'],
                                  self.vsc.vtVars['noOutput'], "336")
        #copyfile(resTransPathOld, resTransPath)
        #genrates deformation field
        cTR = self.vsc.runTransformix(self.vsc.vtVars['transformixBinPath'],
                                      self.vsc.vtVars['movingCropPath'],
                                      self.vsc.vtVars['outputPath'],
                                      resTransPath,
                                      self.vsc.vtVars['noOutput'], "339")
        # rename fthe file:
        os.rename(resOldDefPath, resDefPath)

        print(
            "************  Load deformation field Transform  **********************"
        )
        [success, vtTransformNode] = slicer.util.loadTransform(resDefPath,
                                                               returnNode=True)
        vtTransformNode.SetName(transNodeName)
        print(
            "************  Transform The Original Moving image **********************"
        )
        movingVolumeNode.SetAndObserveTransformNodeID(vtTransformNode.GetID())
        #export seg to lbl then export back with input image as reference
        slicer.vtkSlicerTransformLogic().hardenTransform(
            movingVolumeNode)  # apply the transform
        fnm = os.path.join(self.vsc.vtVars['outputPath'],
                           movingVolumeNode.GetName() + "_Registered.nrrd")
        sR = slicer.util.saveNode(movingVolumeNode, fnm)
        [success,
         registeredMovingVolumeNode] = slicer.util.loadVolume(fnm,
                                                              returnNode=True)
        registeredMovingVolumeNode.SetName(movingVolumeNode.GetName() +
                                           "_Registered")
        #remove the tempnode and load the original
        slicer.mrmlScene.RemoveNode(movingVolumeNode)
        [success, movingVolumeNode] = slicer.util.loadVolume(movingPath,
                                                             returnNode=True)
        movingVolumeNode.SetName(
            os.path.splitext(
                os.path.basename(
                    movingVolumeNode.GetStorageNode().GetFileName()))[0])
        if (cTI == 0) and (cTR == 0):
            print("No error is reported during registeration ...")
        else:
            print("error happened during registration ")
        #endif

        #Remove temporary files and nodes:
        self.vsc.removeTmpsFiles()
        print(
            "================= Cochlea registration is complete  ====================="
        )
        logging.info('Processing completed')

        return registeredMovingVolumeNode
コード例 #8
0
    def run(self, inputVolumeNode, inputFiducialNode, cochleaSide):
        logging.info('Processing started')

        self.vsc = VisSimCommon.VisSimCommonLogic()
        self.vsc.setGlobalVariables(0)

        self.inputVolumeNode = inputVolumeNode
        self.inputFiducialNode = inputFiducialNode
        # modality type CBCT, CT or MRI
        # it seems using CBCT atlas is enough
        Styp = "Dv"

        # segmentation atlas model paths
        modelPath = os.path.join(
            self.vsc.vtVars['modelPath'],
            "Mdl" + Styp + cochleaSide + "c" + self.vsc.vtVars['imgType'])
        modelSegPath = os.path.join(
            self.vsc.vtVars['modelPath'],
            "Mdl" + Styp + cochleaSide + "cS.seg" + self.vsc.vtVars['imgType'])
        modelImgStPath = os.path.join(self.vsc.vtVars['modelPath'],
                                      "Mdl" + Styp + cochleaSide + "cSt.fcsv")
        # set the results paths:
        resTransPathOld = os.path.join(self.vsc.vtVars['outputPath'],
                                       "TransformParameters.0.txt")
        resTransPath = resTransPathOld[0:-6] + 'Pars.txt'
        resOldDefPath = os.path.join(
            self.vsc.vtVars['outputPath'],
            "deformationField" + self.vsc.vtVars['imgType'])
        resDefPath = os.path.join(
            self.vsc.vtVars['outputPath'],
            inputVolumeNode.GetName() + "_dFld" + self.vsc.vtVars['imgType'])
        inputImgName = os.path.basename(
            os.path.splitext(
                inputVolumeNode.GetStorageNode().GetFileName())[0])
        segNodeName = inputVolumeNode.GetName() + "_S.Seg"
        stpNodeName = inputVolumeNode.GetName() + "_StPts"
        transNodeName = inputVolumeNode.GetName() + "_Transform"

        self.vsc.removeOtputsFolderContents()
        # check if the model is found
        if not os.path.isfile(modelPath):
            print("ERROR: model is not found", file=sys.stderr)
            print("modelPath: " + modelPath)
            return -1
        # endif

        # Get IJK point from the fiducial to use in cropping
        inputPoint = self.vsc.ptRAS2IJK(inputFiducialNode, inputVolumeNode, 0)
        # TODO: add better condition
        if np.sum(inputPoint) == 0:
            print("Error: select cochlea point")
            return -1
        #endif
        fnm = os.path.join(self.vsc.vtVars['outputPath'],
                           inputVolumeNode.GetName() + "_Cochlea_Pos.fcsv")
        sR = slicer.util.saveNode(inputFiducialNode, fnm)

        #Remove old resulted nodes
        for node in slicer.util.getNodes():
            if (segNodeName == node): slicer.mrmlScene.RemoveNode(node)  #endif
            if (transNodeName == node):
                slicer.mrmlScene.RemoveNode(node)  #endif
        #endfor

        inputPointT = self.vsc.v2t(inputPoint)

        print("=================== Cropping =====================")
        self.vsc.vtVars['intputCropPath'] = self.vsc.runCropping(
            inputVolumeNode, inputPointT, self.vsc.vtVars['croppingLength'],
            self.vsc.vtVars['RSxyz'], self.vsc.vtVars['hrChk'], 0)
        [success, croppedNode
         ] = slicer.util.loadVolume(self.vsc.vtVars['intputCropPath'],
                                    returnNode=True)
        croppedNode.SetName(inputVolumeNode.GetName() + "_Crop")
        print(
            "************  Register model to cropped input image **********************"
        )
        cTI = self.vsc.runElastix(self.vsc.vtVars['elastixBinPath'],
                                  self.vsc.vtVars['intputCropPath'], modelPath,
                                  self.vsc.vtVars['outputPath'],
                                  self.vsc.vtVars['parsPath'],
                                  self.vsc.vtVars['noOutput'], "292")
        copyfile(resTransPathOld, resTransPath)
        #genrates deformation field
        cTR = self.vsc.runTransformix(self.vsc.vtVars['transformixBinPath'],
                                      modelPath, self.vsc.vtVars['outputPath'],
                                      resTransPath,
                                      self.vsc.vtVars['noOutput'], "295")
        # rename fthe file:
        os.rename(resOldDefPath, resDefPath)
        print(
            "************  Load deformation field Transform  **********************"
        )
        [success, vtTransformNode] = slicer.util.loadTransform(resDefPath,
                                                               returnNode=True)
        vtTransformNode.SetName(transNodeName)
        print(
            "************  Transform The Segmentation **********************")
        [success, vtSegNode] = slicer.util.loadSegmentation(modelSegPath,
                                                            returnNode=True)
        vtSegNode.SetName(segNodeName)
        vtSegNode.SetAndObserveTransformNodeID(vtTransformNode.GetID())
        #export seg to lbl then export back with input image as reference
        slicer.vtkSlicerTransformLogic().hardenTransform(
            vtSegNode)  # apply the transform
        vtSegNode.CreateClosedSurfaceRepresentation()
        fnm = os.path.join(self.vsc.vtVars['outputPath'],
                           vtSegNode.GetName() + ".nrrd")
        sR = slicer.util.saveNode(vtSegNode, fnm)

        print(
            "************  Transform The Scala Points **********************")
        #TODO:check the right side model
        #TODO:add scala vestibuli model
        # transform the Scala Tympani Points for length Computation
        [success,
         vtImgStNode] = slicer.util.loadMarkupsFiducialList(modelImgStPath,
                                                            returnNode=True)
        vtImgStNode.GetDisplayNode().SetSelectedColor(1, 0, 0)
        vtImgStNode.GetDisplayNode().SetTextScale(0.5)
        vtImgStNode.SetName(stpNodeName)
        vtImgStNode.SetAndObserveTransformNodeID(vtTransformNode.GetID())
        slicer.vtkSlicerTransformLogic().hardenTransform(
            vtImgStNode)  # apply the transform
        fnm = os.path.join(self.vsc.vtVars['outputPath'],
                           vtImgStNode.GetName() + ".fcsv")
        sR = slicer.util.saveNode(vtImgStNode, fnm)

        # Display the result if no error
        # Clear cochlea location labels
        if (cTI == 0) and (cTR == 0):
            # change the model type from vtk to stl
            msn = slicer.vtkMRMLModelStorageNode()
            msn.SetDefaultWriteFileExtension('stl')
            slicer.mrmlScene.AddDefaultNode(msn)
            print("get Cochlea information")
            tableName = inputVolumeNode.GetName() + "_tbl"
            # create only if it does not exist
            try:
                spTblNode = slicer.util.getNode(tableName)
            except Exception as e:
                print(e)
                spTblNode = slicer.mrmlScene.AddNewNodeByClass(
                    "vtkMRMLTableNode")
                spTblNode.SetName(tableName)
            #endtry
            spTblNode = self.vsc.getItemInfo(vtSegNode, croppedNode, spTblNode,
                                             0)
            for i in range(0, 8):
                spTblNode.RemoveColumn(3)
            #endfor
            spTblNode.GetTable().GetColumn(1).SetName("Size (mm^3)")
            spTblNode.GetTable().GetColumn(2).SetName("Length (mm)")
            spTblNode.SetCellText(0, 0, "Scala Tympani")
            spTblNode.SetCellText(1, 0, "Scala Vestibuli")
            #spTblNode.resultsTableNode.SetCellText(0,2,"ST value")
            #spTblNode.resultsTableNode.SetCellText(1,2,"0")

            self.vsc.getFiducilsDistance(vtImgStNode, spTblNode)
            spTblNode.RemoveRow(spTblNode.GetNumberOfRows())
            self.spTblNode = spTblNode
        else:
            print("error happened during segmentation ")
        #endif

        #Remove temporary files and nodes:
        self.vsc.removeTmpsFiles()
        print(
            "================= Cochlea analysis is complete  ====================="
        )
        logging.info('Processing completed')
        return vtSegNode
コード例 #9
0
    def run(self, inputVolumeNode, inputFiducialNode, methodID):

        self.vsc = VisSimCommon.VisSimCommonLogic()
        self.vsc.setGlobalVariables(1)

        self.inputVolumeNode = inputVolumeNode
        self.inputFiducialNode = inputFiducialNode

        self.outputPaths = []
        self.intputCropPaths = []
        self.inputPoints = []
        self.modelPaths = []
        vtIDsLst = []
        missingVt = list(range(1, 8))
        rng = 7  # number of vertebra
        for j in range(7):
            vtIDsLst.append([0, 0, 0])
            self.intputCropPaths.append("")
            self.inputPoints.append([0, 0, 0])
        #endfor
        for j in range(inputFiducialNode.GetNumberOfFiducials()):
            l = inputFiducialNode.GetNthFiducialLabel(j)
            k = int(l[1])
            missingVt[k - 1] = 0
            inputFiducialNode.GetNthFiducialPosition(j, vtIDsLst[k - 1])
        #endfor

        if sum(missingVt) > 0:
            vtIDsLst = self.getAllVertebraePoints(vtIDsLst, inputFiducialNode)
        #endif

        #create a table for vertebra information
        tableName = inputVolumeNode.GetName() + "_tbl"
        spTblNode = slicer.mrmlScene.AddNewNodeByClass("vtkMRMLTableNode")
        spTblNode.SetName(tableName)
        spTblNode.AddEmptyRow()
        spTblNode.GetTable().GetColumn(0).SetName("Vertebra")
        spTblNode.AddColumn()
        spTblNode.GetTable().GetColumn(1).SetName("Volume mm3")
        spTblNode.AddColumn()
        spTblNode.GetTable().GetColumn(2).SetName("CoM X")
        spTblNode.AddColumn()
        spTblNode.GetTable().GetColumn(3).SetName("CoM Y")
        spTblNode.AddColumn()
        spTblNode.GetTable().GetColumn(4).SetName("CoM Z")
        self.spTblNode = spTblNode

        # create output paths
        for i in range(rng):
            #get other points
            #create a list from the points
            vtID = i + 1
            outputPath = self.vsc.vtVars[
                'outputPath'] + "," + inputVolumeNode.GetName() + "_C" + str(
                    vtID)
            outputPath = os.path.join(*outputPath.split(","))
            self.outputPaths.append(outputPath)
            modelCropPath = self.vsc.vtVars[
                'modelPath'] + ',Default' + ",Mdl" + self.vsc.vtVars[
                    'Styp'] + str(vtID) + self.vsc.vtVars['imgType']
            modelCropPath = os.path.join(*modelCropPath.split(","))
            self.modelPaths.append(modelCropPath)
            if not os.path.exists(self.outputPaths[i]):
                os.makedirs(self.outputPaths[i])
            #endif
        #endfor

        # try parallel but slicer crash
        # try if we collect information then run popen
        """
       i=range(rng)
       pool = ThreadPool(9)
       b=pool.map(self.runCroppingAll,i)
       pool.close()
       pool.join()
       """
        #---------------------  process ------------------------------------
        for i in range(rng):
            vtID = i + 1
            segNodeName = self.inputVolumeNode.GetName() + "_C" + str(
                vtID) + ".Seg"
            ligPtsNodeName = self.inputVolumeNode.GetName() + "_C" + str(
                vtID) + "_LigPts"
            transNodeName = self.inputVolumeNode.GetName() + "_C" + str(
                vtID) + "_Transform"

            self.runCroppingAll(i)
            self.runElastixAll(i)

            self.resTransPath = os.path.join(self.outputPaths[i],
                                             "TransformParameters.0.txt")
            resOldDefPath = os.path.join(
                self.outputPaths[i],
                "deformationField" + self.vsc.vtVars['imgType'])
            resDefPath = os.path.join(
                self.outputPaths[i],
                self.inputVolumeNode.GetName() + "_C" + str(vtID) + "_dFld" +
                self.vsc.vtVars['imgType'])
            #remove old result files:
            if os.path.isfile(resOldDefPath):
                os.remove(resOldDefPath)
            if os.path.isfile(resDefPath):
                os.remove(resDefPath)

            self.runTransformixAll(i)

            os.rename(resOldDefPath, resDefPath)

            [success,
             vtTransformNode] = slicer.util.loadTransform(resDefPath,
                                                          returnNode=True)
            vtTransformNode.SetName(transNodeName)

            modelSegPath = self.vsc.vtVars['modelPath'] + self.vsc.vtVars[
                'segT'] + ",Mdl" + self.vsc.vtVars['Styp'] + str(
                    vtID) + self.vsc.vtVars['sgT'] + self.vsc.vtVars['imgType']
            modelSegPath = os.path.join(*modelSegPath.split(","))

            [success,
             vtResultSegNode] = slicer.util.loadSegmentation(modelSegPath,
                                                             returnNode=True)
            vtResultSegNode.SetName(segNodeName)
            vtResultSegNode.SetAndObserveTransformNodeID(
                vtTransformNode.GetID()
            )  # movingAllMarkupNode should be loaded, the file contains all points
            slicer.vtkSlicerTransformLogic().hardenTransform(vtResultSegNode)
            vtResultSegNode.CreateClosedSurfaceRepresentation()
            fnm = os.path.join(self.outputPaths[i],
                               vtResultSegNode.GetName() + ".nrrd")
            sR = slicer.util.saveNode(vtResultSegNode, fnm)

            if self.vsc.s2b(self.vsc.vtVars['ligChk']):
                modelCropImgLigPtsPath = self.vsc.vtVars[
                    'modelPath'] + self.vsc.vtVars[
                        'vtPtsLigDir'] + "," + self.vsc.vtVars['Styp'] + str(
                            vtID) + self.vsc.vtVars['vtPtsLigSuff'] + ".fcsv"
                modelCropImgLigPtsPath = os.path.join(
                    *modelCropImgLigPtsPath.split(","))
                [success, vtLigPtsNode] = slicer.util.loadMarkupsFiducialList(
                    modelCropImgLigPtsPath, returnNode=True)
                vtLigPtsNode.GetDisplayNode().SetSelectedColor(1, 0, 0)
                vtLigPtsNode.GetDisplayNode().SetTextScale(0.5)
                vtLigPtsNode.SetName(ligPtsNodeName)
                vtLigPtsNode.SetAndObserveTransformNodeID(
                    vtTransformNode.GetID()
                )  # movingAllMarkupNode should be loaded, the file contains all points
                slicer.vtkSlicerTransformLogic().hardenTransform(
                    vtLigPtsNode)  # apply the transform
                # needed in extract scaled model
                self.vtLigPtsNode = vtLigPtsNode
                fnm = os.path.join(self.outputPaths[i],
                                   vtLigPtsNode.GetName() + ".fcsv")
                sR = slicer.util.saveNode(vtLigPtsNode, fnm)
            #endif
            self.getVertebraInfoAll(i)
        #endfor

        self.spTblNode.RemoveRow(0)

        self.vsc.vtVars['segNodeCoM'] = self.vsc.vtVars['segNodeCoM']
        self.vtResultSegNode = vtResultSegNode

        #Remove temporary files and nodes:
        self.vsc.removeTmpsFiles()
        return vtResultSegNode