Exemple #1
0
    def setup(self):
        print(" ")
        print("=======================================================")
        print("                 Remeshing Tools 2019                  ")
        print("=======================================================")

        ScriptedLoadableModuleWidget.setup(self)

        # Declare global labels
        self.imtimeLbl = qt.QLabel("                 Time: 00:00")
        self.imtimeLbl.setFixedWidth(300)
        self.qhtimeLbl = qt.QLabel("                 Time: 00:00")
        self.qhtimeLbl.setFixedWidth(300)

        # Initialize GUI
        self.initMainPanel()

        self.logic = SlicerRemeshingLogic()
        self.logic.setGlobalVariables()
        self.logic.checkBinaries()

        # change the model type from vtk to stl
        msn = slicer.vtkMRMLModelStorageNode()
        msn.SetDefaultWriteFileExtension('stl')
        slicer.mrmlScene.AddDefaultNode(msn)
Exemple #2
0
 def initializeModelNode(node):
   displayNode = slicer.vtkMRMLModelDisplayNode()
   storageNode = slicer.vtkMRMLModelStorageNode()
   displayNode.SetScene(slicer.mrmlScene)
   storageNode.SetScene(slicer.mrmlScene)
   slicer.mrmlScene.AddNode(displayNode)
   slicer.mrmlScene.AddNode(storageNode)
   node.SetAndObserveDisplayNodeID(displayNode.GetID())
   node.SetAndObserveStorageNodeID(storageNode.GetID())
 def initializeModelNode(node):
     displayNode = slicer.vtkMRMLModelDisplayNode()
     storageNode = slicer.vtkMRMLModelStorageNode()
     displayNode.SetScene(slicer.mrmlScene)
     storageNode.SetScene(slicer.mrmlScene)
     slicer.mrmlScene.AddNode(displayNode)
     slicer.mrmlScene.AddNode(storageNode)
     node.SetAndObserveDisplayNodeID(displayNode.GetID())
     node.SetAndObserveStorageNodeID(storageNode.GetID())
Exemple #4
0
    def runBtnClick(self):
        self.runBtn.setText("...please wait")
        self.runBtn.setStyleSheet("QPushButton{ background-color: red  }")
        slicer.app.processEvents()

        # Get the cochlea location point
        sr = self.inputPointEdt.text.strip()
        sr = sr[1:-1]
        self.inputPoint = map(int, sr.split(','))

        #remove old files
        shutil.rmtree(self.outputPath)
        os.mkdir(self.outputPath)

        Styp = "Dv"
        side = "L"

        if self.sideActivated:  # right side
            side = "R"

        self.modelCropPath = self.modelPath + "/Mdl" + Styp + side + "c.nrrd"
        self.modelCropSegPath = self.modelPath + "/Mdl" + Styp + side + "cS.nrrd"
        self.modelCropImgStPath = self.modelPath + "/Mdl" + Styp + side + "cSt.nrrd"

        resTransPath = self.outputPath + "/TransformParameters.0.txt"
        res0ImgPath = self.outputPath + "/result.0.nrrd"
        resImgPath = self.outputPath + "/result.nrrd"

        # check if the model is found
        if not isfile(self.modelCropPath):
            print >> sys.stderr, "ERROR: model is not found"
            return False
        # endif

        try:  # is there a node loaded
            self.inputNode = self.inputSelectorCoBx.currentNode()
        except AttributeError:
            print >> sys.stderr, "ERROR: No input volume, Bad Path or DICOM."
            self.suppDICOM()
        #end try
        self.inputPath = self.inputNode.GetStorageNode().GetFileName()
        self.inputFnm = basename(os.path.splitext(self.inputPath)[0])
        # Remove old result
        rNodes = slicer.util.getNodesByClass("vtkMRMLScalarVolumeNode")
        for f in rNodes:
            if f.GetName()[0:3] == 'res':
                slicer.mrmlScene.RemoveNode(f)

        self.stm = time.time()
        print("time:" + str(self.stm))
        self.timeLbl.setText("                 Time: 00:00")

        if self.inputPointEdt.text == "[0, 0, 0]":
            print("Error: select cochlea point")
            return False
        #endif
        self.intputCropPath = self.doCropping(self.inputNode, self.inputPoint)

        print("=================== Segmentation =====================")
        print
        print("************  Compute the Transform **********************")
        # register the cropped image  of the model
        cmd = self.elastixBinPath + " -f " + self.intputCropPath + " -m " + self.modelCropPath + " -out " + self.outputPath + " -p " + self.parsPath + self.noOutput
        print("Executing: " + cmd)
        cTI = os.system(cmd)
        errStr = "elastix error at line 601, check the log files"
        self.chkElxER(
            cTI, errStr)  # Check if errors happen during elastix execution

        print(
            "************  Transform The Segmentation **********************")
        # Apply the transformation to the segmentation image:
        Cmd = self.transformixBinPath + " -in " + self.modelCropSegPath + " -out " + self.outputPath + " -tp " + resTransPath + self.noOutput
        print("Executing... " + str(Cmd))
        cTS = os.system(Cmd)
        errStr = "Transformix error at line 611, check the log file"
        self.chkElxER(
            cTS, errStr)  # Check if errors happen during elastix execution

        #rename the result file
        self.resImgLabelPath = self.outputPath + "/" + self.inputNode.GetName(
        ) + "-label.nrrd"
        self.resultFnm = basename(os.path.splitext(self.resImgLabelPath)[0])
        os.rename(resImgPath, self.resImgLabelPath)

        print("************  Transform The Points **********************")
        # transform the Scala Tympani Points for length Computation
        Cmd = self.transformixBinPath + " -in " + self.modelCropImgStPath + " -out " + self.outputPath + " -tp " + resTransPath + self.noOutput
        print("Executing... " + str(Cmd))
        cTP = os.system(Cmd)
        errStr = "Transformix error, transform points at line 623, check the log file"
        self.chkElxER(
            cTP, errStr)  # Check if errors happen during elastix execution

        #rename the result image file
        self.resImgPtsPath = self.outputPath + "/" + self.inputNode.GetName(
        ) + "-IPtsSt.nrrd"
        os.rename(resImgPath, self.resImgPtsPath)

        # Load the image poins, calculat the length and crete the points
        [success,
         self.resImgPtsNode] = slicer.util.loadVolume(self.resImgPtsPath,
                                                      returnNode=True)

        # Convert to points
        self.image2points(self.resImgPtsNode)

        # Display the result if no error
        # Clear cochlea location labels
        if (cTS == 0) and (cTP == 0):
            #remove the temprary cropped file and node
            os.remove(self.inputCropPath)
            slicer.mrmlScene.RemoveNode(self.croppedNode)

            # Remove old Fiducial nodes
            nodes = slicer.util.getNodesByClass('vtkMRMLMarkupsFiducialNode')
            for f in nodes:
                if ((f.GetName() == "CochleaLocation")):
                    slicer.mrmlScene.RemoveNode(f)

            # The result image file is loaded into the slicer scene.
            [success, self.resultNode
             ] = slicer.util.loadLabelVolume(self.resImgLabelPath,
                                             returnNode=True)
            nodes = slicer.util.getNodesByClass("vtkMRMLScalarVolumeNode")
            for f in nodes:
                match = re.search(r"result_[0-9]*", f.GetName())
                if match:
                    self.resultFnm = f.GetName()
            self.resultNode = slicer.util.getNode(self.resultFnm)
            self.resultNode.SetName('result')

            # Generate a .seg node
            self.segNode = slicer.mrmlScene.AddNewNodeByClass(
                'vtkMRMLSegmentationNode')
            self.segNode.SetName(self.inputFnm + "S")
            slicer.modules.segmentations.logic(
            ).ImportLabelmapToSegmentationNode(self.resultNode, self.segNode)
            #self.segNode.SetName(self.inputFnm+"S")  #TODO check if this shoud be removed
            sg = self.segNode.GetSegmentation()
            st = sg.GetSegment("7")
            st.SetName(self.inputFnm + "_St")
            sv = sg.GetSegment("300")
            sv.SetName(self.inputFnm + "_Sv")

            #remove the temprary labelmap
            slicer.mrmlScene.RemoveNode(self.resultNode)

            # change the model type from vtk to stl
            msn = slicer.vtkMRMLModelStorageNode()
            msn.SetDefaultWriteFileExtension('stl')
            slicer.mrmlScene.AddDefaultNode(msn)

            # get Cochlea measuerments
            self.getCochleaSize()
        else:
            print("error happened during segmentation ")

        # TODO: find a reduced code to replace this block
        lm = slicer.app.layoutManager()
        r_logic = lm.sliceWidget("Red").sliceLogic()
        r_cn = r_logic.GetSliceCompositeNode()
        r_cn.SetBackgroundVolumeID(self.inputNode.GetID())
        y_logic = lm.sliceWidget("Yellow").sliceLogic()
        y_cn = y_logic.GetSliceCompositeNode()
        y_cn.SetBackgroundVolumeID(self.inputNode.GetID())
        g_logic = lm.sliceWidget("Green").sliceLogic()
        g_cn = g_logic.GetSliceCompositeNode()
        g_cn.SetBackgroundVolumeID(self.inputNode.GetID())

        print(
            "================= Cochlea analysis is complete  ====================="
        )

        # Update time label
        self.etm = time.time()
        tm = self.etm - self.stm
        self.timeLbl.setText("Time: " + str(tm) + "  seconds")

        self.runBtn.setText("Run")
        self.runBtn.setStyleSheet(
            "QPushButton{ background-color: DarkSeaGreen  }")
        slicer.app.processEvents()
Exemple #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
  def run(self, inputVolumeNode, inputFiducialNode, side):
      #to be used fromoutside we need to do:
      # import CochleaSeg
      # logic= CochleaSeg.CochleaSegLogic()
      # logic.run(with the parameters above)
      
        """
        Run the actual algorithm
        """
        # we need to run this again in case of external call
        self.setGlobalVariables()
        
        self.hasImageData(inputVolumeNode)
        self.inputVolumeNode = inputVolumeNode
        self.inputFiducialNode = inputFiducialNode
        
        # Create a temporary node as workaround for bad path or filename 
        #TODO: create a temp folder and remove temp node before display
        tmpName= self.vissimPath+"/inputImage.nrrd"
        slicer.util.saveNode( inputVolumeNode, tmpName)
        [success, self.inputVolumeNode] = slicer.util.loadVolume(tmpName, returnNode=True)    
        self.inputVolumeNode.SetName("inputImage")

        logging.info('Processing started')

        # Get IJK point from the fiducial to use in cropping  
        self.inputPoint = self.ptRAS2IJK(self.inputFiducialNode,inputVolumeNode)

        #remove old files if exist
        if os.path.isdir(self.outputPath.strip()): 
           print("removing old output folder!")
           shutil.rmtree(self.outputPath) 
        #endif   
        os.mkdir(self.outputPath)      

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

        # segmentation atlas model paths
        self.modelCropPath       = self.modelPath + "/Mdl"+Styp+side+"c.nrrd" 
        self.modelCropSegPath    = self.modelPath + "/Mdl"+Styp+side+"cS.nrrd" 
        self.modelCropImgStPath  = self.modelPath + "/Mdl"+Styp+side+"cSt.nrrd" 
                
        # results paths        
        resTransPath = self.outputPath  + "/TransformParameters.0.txt"
        res0ImgPath  = self.outputPath  + "/result.0.nrrd"
        resImgPath   = self.outputPath  + "/result.nrrd"
             
        # check if the model is found
        if not isfile(self.modelCropPath): 
            print >> sys.stderr, "ERROR: model is not found"
            return False
        # endif

        self.inputPath = self.inputVolumeNode.GetStorageNode().GetFileName()
        self.inputFnm  = basename(os.path.splitext(self.inputPath)[0])    
        
        # Remove old nodes
        rNodes = slicer.util.getNodesByClass("vtkMRMLScalarVolumeNode")
        for f in rNodes:
            if f.GetName()[0:3]=='res':
                 slicer.mrmlScene.RemoveNode(f)
            #endif
        #endfor    
        
        # TODO: add better condition
        if  np.sum(self.inputPoint)== 0 :
            print("Error: select cochlea point")
            return False
        #endif  

        print("=================== Cropping =====================")                           
        self.intputCropPath = self.doCropping(self.inputVolumeNode, self.inputPoint, self.croppingLength)                     

        print ("************  Register model to cropped input image **********************")
        cTI = self.runElastix(self.intputCropPath,  self.modelCropPath, self.outputPath, self.parsPath, self.noOutput, "554")
        print ("************  Transform The Segmentation **********************")
        cTS = self.runTransformix(self.modelCropSegPath, self.outputPath, resTransPath , self.noOutput, "556")
        #rename the result file        
        self.resImgLabelPath = self.outputPath  +"/"+ self.inputVolumeNode.GetName()  +"-label.nrrd"
        self.resultFnm = basename(os.path.splitext(self.resImgLabelPath)[0])                 
        os.rename(resImgPath, self.resImgLabelPath)                        
        print ("************  Transform The Points **********************")
        # transform the Scala Tympani Points for length Computation 
        cTP = self.runTransformix(self.modelCropImgStPath, self.outputPath, resTransPath , self.noOutput, "556")
        #rename the result image file        
        self.resImgPtsPath = self.outputPath  +"/"+ self.inputVolumeNode.GetName()  + "-IPtsSt.nrrd"
        os.rename(resImgPath, self.resImgPtsPath )           
        # Load the image poins, calculat the length and crete the points          
        [success, self.resImgPtsNode] = slicer.util.loadVolume(self.resImgPtsPath, returnNode=True)           
        # Convert the image points to fiducials
        print ("************  create fiducial from the scala transformed image **********************")
        self.image2points(self.resImgPtsNode) 

        # Display the result if no error
        # Clear cochlea location labels
        if  (cTS==0) and (cTP==0):
             #remove the temprary cropped file and node  
             os.remove(self.inputCropPath)     
             slicer.mrmlScene.RemoveNode(self.croppedNode )

             # Remove old Fiducial nodes
             nodes = slicer.util.getNodesByClass('vtkMRMLMarkupsFiducialNode')
             for f in nodes:
                if ((f.GetName() == "CochleaLocation") ):
                    slicer.mrmlScene.RemoveNode(f)   
             
             # The result image file is loaded into the slicer scene.
             [success , self.resultNode]=slicer.util.loadLabelVolume(self.resImgLabelPath,returnNode=True) 
             nodes = slicer.util.getNodesByClass("vtkMRMLScalarVolumeNode")
             for f in nodes:
                match = re.search(r"result_[0-9]*", f.GetName())
                if match:
                   self.resultFnm = f.GetName()
                   self.resultNode = f
                   self.resultNode.SetName('result') 
                #endif
             #endfor      

             # Generate a .seg node
             self.segNode = slicer.mrmlScene.AddNewNodeByClass('vtkMRMLSegmentationNode')
             self.segNode.SetName(self.inputFnm+"S")
             slicer.modules.segmentations.logic().ImportLabelmapToSegmentationNode(self.resultNode, self.segNode) 
             sg=self.segNode.GetSegmentation()
             st=sg.GetSegment("7")
             st.SetName(self.inputFnm+"_St")
             sv=sg.GetSegment("300")
             sv.SetName(self.inputFnm+"_Sv")

             #remove the temprary loaded labelmap  
             slicer.mrmlScene.RemoveNode(self.resultNode )
        
             # change the model type from vtk to stl 
             msn=slicer.vtkMRMLModelStorageNode()
             msn.SetDefaultWriteFileExtension('stl')
             slicer.mrmlScene.AddDefaultNode(msn)

             # get Cochlea measuerments
             self.getCochleaSize()
        else:
            print("error happened during segmentation ")
        #endif
        
        # TODO: find a reduced code to replace this block  
        lm = slicer.app.layoutManager()
        r_logic = lm.sliceWidget("Red").sliceLogic()
        r_cn = r_logic.GetSliceCompositeNode()
        r_cn.SetBackgroundVolumeID(self.inputVolumeNode.GetID())
        y_logic = lm.sliceWidget("Yellow").sliceLogic()
        y_cn = y_logic.GetSliceCompositeNode()
        y_cn.SetBackgroundVolumeID(self.inputVolumeNode.GetID())
        g_logic = lm.sliceWidget("Green").sliceLogic()
        g_cn = g_logic.GetSliceCompositeNode()
        g_cn.SetBackgroundVolumeID(self.inputVolumeNode.GetID())
        
        print("================= Cochlea analysis is complete  =====================")
        logging.info('Processing completed')
        return True
    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