Exemplo n.º 1
0
def ReadImageSlicer(FileName):
    mrml = slicer.vtkMRMLScene()
    vl = slicer.vtkSlicerVolumesLogic()
    vl.SetAndObserveMRMLScene(mrml)
    n = vl.AddArchetypeVolume(FileName, 'CTC')
    i = n.GetImageData()
    return i
Exemplo n.º 2
0
 def onCentrar(self):
     volumenCentrar = self.imagenSelector.currentNode()
     lm = slicer.app.layoutManager()
     origenVolumen = volumenCentrar.GetOrigin()
     volumeLogic = slicer.vtkSlicerVolumesLogic()
     origenCentro = [0, 0, 0]
     volumeLogic.GetVolumeCenteredOrigin(volumenCentrar, origenCentro)
     traslacion = [0, 0, 0]
     volumenCentrar.SetOrigin(origenCentro)
     lm.resetSliceViews()
     for i in range(3):
         traslacion[i] = origenCentro[i] - origenVolumen[i]
     T = slicer.vtkMRMLTransformNode()
     I = slicer.vtkMRMLTransformNode()
     transmatrix = vtk.vtkMatrix4x4()
     transform = vtk.vtkTransform()
     T.SetAndObserveTransformToParent(transform)
     T.SetName('centrarTransformacionSeeg')
     I.SetName('CentrarTInversaSeeg')
     transmatrix.DeepCopy((1, 0, 0, traslacion[0], 0, 1, 0, traslacion[1],
                           0, 0, 1, traslacion[2], 0, 0, 0, 1))
     transform.SetMatrix(transmatrix)
     inv = transform.GetInverse()
     I.SetAndObserveTransformToParent(inv)
     slicer.mrmlScene.AddNode(T)
     slicer.mrmlScene.AddNode(I)
def SaveLabelMapContours(labelMapContours, outputSegmentationsDir, fileFormat, logFilePath):    
    volumesLogic = slicer.vtkSlicerVolumesLogic()
    for labelMapContour in labelMapContours:
        volumesLogic.CenterVolume(labelMapContour)
        savenamelabel = labelMapContour.GetName()
        savenamelabel = ''.join(x for x in savenamelabel if x not in "',;\/:*?<>|") + fileFormat
        savelabel = slicer.util.saveNode(labelMapContour, os.path.join(outputSegmentationsDir, savenamelabel), properties={"filetype": fileFormat})
        if not savelabel:
            with open(logFilePath,mode='a') as logfile: logfile.write("\tSAVEERROR: Could not save data" + labelMapContour.GetName() + '\n')     
 def saveVolumes(self, listVolumes, outputDir, isLabelMap=False):
     volumesLogic = slicer.vtkSlicerVolumesLogic()
     for volume in listVolumes:
         if self.converterSettings["centerlabels"] and isLabelMap:
             volumesLogic.CenterVolume(volume)
         elif self.converterSettings["centerimages"] and not isLabelMap:
             volumesLogic.CenterVolume(volume)
             
         savename = volume.GetName() 
         savename = ''.join(x for x in savename if x not in "',;\/:*?<>|") + self.converterSettings["fileformat"]       
         savevol = slicer.util.saveNode(volume, os.path.join(outputDir, savename), properties={"filetype": self.converterSettings["fileformat"]})
         if not savevol:
             with open(self.logFilePath,mode='a') as logfile: logfile.write("\tSAVEERROR: Could not save data" + volume.GetName() + '\n')        
Exemplo n.º 5
0
def SaveLabelMapContours(labelMapContours, outputSegmentationsDir, fileFormat,
                         logFilePath):
    volumesLogic = slicer.vtkSlicerVolumesLogic()
    for labelMapContour in labelMapContours:
        volumesLogic.CenterVolume(labelMapContour)
        savenamelabel = labelMapContour.GetName()
        savenamelabel = ''.join(
            x for x in savenamelabel if x not in "',;\/:*?<>|") + fileFormat
        savelabel = slicer.util.saveNode(labelMapContour,
                                         os.path.join(outputSegmentationsDir,
                                                      savenamelabel),
                                         properties={"filetype": fileFormat})
        if not savelabel:
            with open(logFilePath, mode='a') as logfile:
                logfile.write("\tSAVEERROR: Could not save data" +
                              labelMapContour.GetName() + '\n')
    def loadVolumeFromHierarchyNode(self, hierarchyNode):
        #Look for existing associated nodes:
        if hierarchyNode.GetAssociatedNodeID():
            volume = slicer.util.getNode(hierarchyNode.GetAssociatedNodeID())
            if volume:
                return volume

        filePath = hierarchyNode.GetAttribute('FilePath')
        volume = None
        if filePath:
            #Special case for ctx files
            if filePath.find('ctx') > -1:
                import LoadCTX

                loadLogic = LoadCTX.LoadCTXLogic()
                volume = slicer.util.getNode(loadLogic.loadCube(filePath, 0))
                if volume:
                    #Write it in hierarchy node for later use
                    hierarchyNode.SetAssociatedNodeID(volume.GetID())
                    return volume
            elif filePath.find('cbt') > -1:
                import LoadCTX

                loadLogic = LoadCTX.LoadCTXLogic()
                volume = slicer.util.getNode(loadLogic.loadCube(filePath, 3))
                if volume:
                    #Write it in hierarchy node for later use
                    hierarchyNode.SetAssociatedNodeID(volume.GetID())
                    return volume
            else:
                volumesLogic = slicer.vtkSlicerVolumesLogic()
                volumesLogic.SetMRMLScene(slicer.mrmlScene)
                slicerVolumeName = os.path.splitext(os.path.basename(filePath))[0]
                volume = volumesLogic.AddArchetypeVolume(filePath, slicerVolumeName)
                if not volume:
                    print "Can't load volume " + os.path.basename(filePath)
                    return None
                #Write it in hierarchy node for later use
                hierarchyNode.SetAssociatedNodeID(volume.GetID())

        else:
            print "Can't get file Path from: " + hierarchyNode.GetNameWithoutPostfix()
            return None

        return volume
Exemplo n.º 7
0
    def saveVolumes(self, listVolumes, outputDir, isLabelMap=False):
        volumesLogic = slicer.vtkSlicerVolumesLogic()
        for volume in listVolumes:
            if self.converterSettings["centerlabels"] and isLabelMap:
                volumesLogic.CenterVolume(volume)
            elif self.converterSettings["centerimages"] and not isLabelMap:
                volumesLogic.CenterVolume(volume)

            savename = volume.GetName()
            savename = ''.join(x for x in savename if x not in "',;\/:*?<>|"
                               ) + self.converterSettings["fileformat"]
            savevol = slicer.util.saveNode(
                volume,
                os.path.join(outputDir, savename),
                properties={"filetype": self.converterSettings["fileformat"]})
            if not savevol:
                with open(self.logFilePath, mode='a') as logfile:
                    logfile.write("\tSAVEERROR: Could not save data" +
                                  volume.GetName() + '\n')
def modelHandler(imageNode, labelNode, Zind): 
    sliceZImageNode = extractMaxZSlice(imageNode, Zind)
    sliceZLabelNode = extractMaxZSlice(labelNode, Zind) 

    volumesLogic = slicer.vtkSlicerVolumesLogic()
    volumesLogic.SetVolumeAsLabelMap(sliceZLabelNode, True)
    volumesLogic.SetVolumeAsLabelMap(labelNode, True)
    
    sliceZLabelNodeDisplay = sliceZLabelNode.GetDisplayNode()
    sliceZLabelNodeDisplay.SetAndObserveColorNodeID('vtkMRMLColorTableNodeFileGenericColors.txt')
    sliceZLabelNode.SetAndObserveDisplayNodeID(sliceZLabelNodeDisplay.GetID())
    labelNodeDisplay = labelNode.GetDisplayNode()
    labelNodeDisplay.SetAndObserveColorNodeID('vtkMRMLColorTableNodeFileGenericColors.txt')
    labelNode.SetAndObserveDisplayNodeID(labelNodeDisplay.GetID())
    
    ##
    appLogic = slicer.app.applicationLogic()
    selectionNode = appLogic.GetSelectionNode()
    selectionNode.SetReferenceActiveVolumeID(sliceZImageNode.GetID())
    selectionNode.SetReferenceActiveLabelVolumeID(sliceZLabelNode.GetID())  
    appLogic.PropagateVolumeSelection()
    
    ##
    lm = slicer.app.layoutManager()
    lm.setLayout(slicer.vtkMRMLLayoutNode.SlicerLayoutFourUpView)
    redWidget = lm.sliceWidget('Red')
    redLogic = redWidget.sliceLogic()
    redView = redWidget.sliceView()
    #redLogic.SetBackgroundWindowLevel(*windowLevel)
     
    sln = slicer.util.getNode('vtkMRMLSliceNodeRed')
    dims = list(sliceZImageNode.GetImageData().GetDimensions())
    # dims[0] is x, dims[1] is y, dims [2] is Z 
    redWidget.setFixedSize(720,660)
    slncw = redWidget.sliceController()
    slncw.showLabelOutline(1)
    slncw.fitSliceToBackground()
    #sln.SetFieldOfView(dims[0],dims[1],1)
    #sln.SetDimensions(dims[0],dims[1],1)
    
    sliceannotations = slicer.modules.DataProbeInstance.infoWidget.sliceAnnoations
    if sliceannotations.sliceViewAnnotationsCheckBox.checkState() == 2:
      sliceannotations.sliceViewAnnotationsCheckBox.click()
    
    slicer.app.processEvents()
    wti=vtk.vtkWindowToImageFilter()  
    wti.SetInput(redView.renderWindow())
    wti.Update()
    imgDataRedSlice = wti.GetOutput()
   
    modelMakerCLI(labelNode) 
    imgData3D = GetModelSnapshot()
    
    append = vtk.vtkImageAppend() 
    append.SetAppendAxis(0)
    append.AddInputData(imgDataRedSlice)
    append.AddInputData(imgData3D)
    append.Update()
    finalImage = append.GetOutput()
    
    return finalImage
    def GeoDistorsionShow3D(self, inputSelectorGeoDistorsionResult,
                            OutputDirectory):
        ### Output : image 3D avec code couleur en fonction du fait que les sphères ont des déformations géométrique en dessus ou en dessous des valeurs de tolérance ####
        print(u"Début de la fonction Show3D")
        time1 = time.time()

        if not inputSelectorGeoDistorsionResult:
            nom_image_IRMrecal = "Resultat_DisGeo_CT_MRI" + str(
                date.day) + str(date.month) + str(date.year)
        else:
            nom_image_IRMrecal = inputSelectorGeoDistorsionResult

        #############   Récupération du chemin de sauvegarde de l'image résultat (3D) #############
        ThreeDImagesavepath = OutputDirectory.directory + "/3DImageResult" + str(
            date.day) + str(date.month) + str(date.year) + ".png"

        #############  Récupération de l'image résultat des test précédent et création de 3 volumes pour les 3 conditions de tolérance  #############
        volumeNode1 = slicer.util.getNode(nom_image_IRMrecal)
        labelVolumeNode1 = slicer.mrmlScene.AddNewNodeByClass(
            "vtkMRMLLabelMapVolumeNode")
        slicer.vtkSlicerVolumesLogic().CreateLabelVolumeFromVolume(
            slicer.mrmlScene, labelVolumeNode1, volumeNode1)

        volumeNode2 = slicer.util.getNode(nom_image_IRMrecal)
        labelVolumeNode2 = slicer.mrmlScene.AddNewNodeByClass(
            "vtkMRMLLabelMapVolumeNode")
        slicer.vtkSlicerVolumesLogic().CreateLabelVolumeFromVolume(
            slicer.mrmlScene, labelVolumeNode2, volumeNode2)

        volumeNode3 = slicer.util.getNode(nom_image_IRMrecal)
        labelVolumeNode3 = slicer.mrmlScene.AddNewNodeByClass(
            "vtkMRMLLabelMapVolumeNode")
        slicer.vtkSlicerVolumesLogic().CreateLabelVolumeFromVolume(
            slicer.mrmlScene, labelVolumeNode3, volumeNode3)

        ############# Création de 3 segmentations basée sur les valeurs de tolérance 6; 13 et 14 du test précédent  #############
        thresholdValue1 = 6
        voxelArray = slicer.util.arrayFromVolume(volumeNode1)
        labelVoxelArray = slicer.util.arrayFromVolume(labelVolumeNode1)
        labelVoxelArray[voxelArray == thresholdValue1] = 100
        labelVoxelArray[voxelArray != thresholdValue1] = 0
        slicer.util.arrayFromVolumeModified(labelVolumeNode1)

        thresholdValue2 = 13
        voxelArray = slicer.util.arrayFromVolume(volumeNode2)
        labelVoxelArray = slicer.util.arrayFromVolume(labelVolumeNode2)
        labelVoxelArray[voxelArray == thresholdValue2] = 100
        labelVoxelArray[voxelArray != thresholdValue2] = 0
        slicer.util.arrayFromVolumeModified(labelVolumeNode2)

        thresholdValue3 = 14
        voxelArray = slicer.util.arrayFromVolume(volumeNode3)
        labelVoxelArray = slicer.util.arrayFromVolume(labelVolumeNode3)
        labelVoxelArray[voxelArray == thresholdValue3] = 100
        labelVoxelArray[voxelArray != thresholdValue3] = 0
        slicer.util.arrayFromVolumeModified(labelVolumeNode3)

        ############# Création de 3 segments issus des 3 segmentations précédentes, coloriage en fonction de la tolérance ou non au test #############
        segmentationNode1 = slicer.mrmlScene.AddNewNodeByClass(
            'vtkMRMLSegmentationNode')
        segmentID = slicer.modules.segmentations.logic(
        ).ImportLabelmapToSegmentationNode(labelVolumeNode1, segmentationNode1)
        segmentation = segmentationNode1.GetSegmentation()
        segment = segmentation.GetSegment(segmentation.GetNthSegmentID(0))
        segment.SetColor(0, 1, 0)

        segmentationNode2 = slicer.mrmlScene.AddNewNodeByClass(
            'vtkMRMLSegmentationNode')
        slicer.modules.segmentations.logic().ImportLabelmapToSegmentationNode(
            labelVolumeNode2, segmentationNode2)
        segmentation = segmentationNode2.GetSegmentation()
        segment = segmentation.GetSegment(segmentation.GetNthSegmentID(0))
        try:  # condition pour éviter plantage dans le cas où il n'y ait pas de sphères avec des distortions < 2mm
            segment.SetColor(1, 0.70, 0)  # couleur R, V, B
        except:
            print("Il n'y a pas de sphère avec une distortion inférieur à 2mm")
            sphere2exist = False
        else:
            sphere2exist = True

        segmentationNode3 = slicer.mrmlScene.AddNewNodeByClass(
            'vtkMRMLSegmentationNode')
        slicer.modules.segmentations.logic().ImportLabelmapToSegmentationNode(
            labelVolumeNode3, segmentationNode3)
        segmentation = segmentationNode3.GetSegmentation()
        segment = segmentation.GetSegment(segmentation.GetNthSegmentID(0))
        try:  # condition pour éviter plantage dans le cas où il n'y ait pas de sphères avec des distortions > 2mm
            segment.SetColor(1, 0, 0)  # couleur R, V, B
        except:
            print("Il n'y a pas de sphère avec une distortion supérieur à 2mm")
            sphere3exist = False
        else:
            sphere3exist = True

        ############# Représentation 3d des volumes segmentés et coloriés   #############
        segmentationNode1.CreateClosedSurfaceRepresentation()
        if sphere2exist == True:
            segmentationNode2.CreateClosedSurfaceRepresentation()
        if sphere3exist == True:
            segmentationNode3.CreateClosedSurfaceRepresentation()

        ############# Copie d'écran du résultat et sauvegarde de l'image dans le dossier de résultat global  #############
        ThreeDImage = qt.QPixmap.grabWidget(slicer.util.mainWindow()).toImage()
        ThreeDImage.save(ThreeDImagesavepath)

        time2 = time.time()
        TimeForrunFunction = time2 - time1

        print("\n")
        print(
            u"La fonction de représentation 3D des sphères s'est bien executée (temps = "
            + str(TimeForrunFunction) + " secondes)")
        print("\n")
        print(
            u"Si dans la représentation 3D des sphères sont de couleurs rouges, merci de prévenir Cyril Jaudet au 5690 ou Aurélien Corroyer-Dulmont au 5768"
        )
        print("\n")
        print(
            u"Si besoin d’aide ou d’informations sur comment fonctionne le programme : Cyril Jaudet (5690) ou Aurélien Corroyer-Dulmont (5768)"
        )
Exemplo n.º 10
0
def modelHandler(ImageFilePath, imageNode, labelNode, imgOutputDir,
                 IDcurrPatient, Zind):
    """
  imageBuffer = vtk.vtkImageData()
  label = growCut(imageNode.GetImageData(),labelNode.GetImageData(),imageBuffer)
  q = labelNode.GetImageData()
  q.DeepCopy(label)
  if labelNode.GetImageDataConnection():
    labelNode.GetImageDataConnection().GetProducer().Update()
  if labelNode.GetImageData().GetPointData().GetScalars() != None:
    labelNode.GetImageData().GetPointData().GetScalars().Modified()
  labelNode.GetImageData().Modified()
  labelNode.Modified()
  pdb.set_trace()
  """
    imageSeriesDescription = os.path.basename(ImageFilePath).replace(
        '.nrrd', '')
    imagePatientID = os.path.basename(
        os.path.dirname(os.path.dirname(os.path.dirname((ImageFilePath)))))
    imageStudyDate = os.path.basename(
        os.path.dirname(os.path.dirname((ImageFilePath))))
    imagePatientID_StudyDate = imagePatientID + '_' + imageStudyDate

    inputImage = su.PullFromSlicer(imageNode.GetName())
    inputLabel = su.PullFromSlicer(labelNode.GetName())
    pixelID = inputImage.GetPixelIDValue()
    FlipYAxis = sitk.FlipImageFilter()
    FlipYAxis.SetFlipAxes([False, True, False])
    sizeZ = list(inputImage.GetSize())
    sizeZ[2] = 0
    indexZ = [0, 0, Zind]
    ExtractorZ = sitk.ExtractImageFilter()
    ExtractorZ.SetSize(sizeZ)
    ExtractorZ.SetIndex(indexZ)
    sliceZImage = ExtractorZ.Execute(inputImage)
    sliceZLabel = ExtractorZ.Execute(inputLabel)
    imageName = 'Axial_Slice_Image' + IDcurrPatient
    labelName = 'Axial_Slice_Label' + IDcurrPatient
    su.PushToSlicer(sliceZImage, imageName)
    su.PushToSlicer(sliceZLabel, labelName)

    sliceZImageNode = slicer.util.getNode(imageName)
    sliceZLabelNode = slicer.util.getNode(labelName)
    volumesLogic = slicer.vtkSlicerVolumesLogic()
    volumesLogic.SetVolumeAsLabelMap(sliceZLabelNode, True)
    volumesLogic.SetVolumeAsLabelMap(labelNode, True)

    #sliceZLabelNode = binarizeLabelMapToValue(sliceZLabelNode, labelValue=296)
    #labelNode = binarizeLabelMapToValue(labelNode, labelValue=296)

    sliceZLabelNodeDisplay = sliceZLabelNode.GetDisplayNode()
    sliceZLabelNodeDisplay.SetAndObserveColorNodeID(
        'vtkMRMLColorTableNodeFileGenericColors.txt')
    sliceZLabelNode.SetAndObserveDisplayNodeID(sliceZLabelNodeDisplay.GetID())
    labelNodeDisplay = labelNode.GetDisplayNode()
    labelNodeDisplay.SetAndObserveColorNodeID(
        'vtkMRMLColorTableNodeFileGenericColors.txt')
    labelNode.SetAndObserveDisplayNodeID(labelNodeDisplay.GetID())

    ##
    appLogic = slicer.app.applicationLogic()
    selectionNode = appLogic.GetSelectionNode()
    selectionNode.SetReferenceActiveVolumeID(sliceZImageNode.GetID())
    selectionNode.SetReferenceActiveLabelVolumeID(sliceZLabelNode.GetID())
    appLogic.PropagateVolumeSelection()

    ##
    lm = slicer.app.layoutManager()
    lm.setLayout(slicer.vtkMRMLLayoutNode.SlicerLayoutFourUpView)
    redWidget = lm.sliceWidget('Red')
    redLogic = redWidget.sliceLogic()
    redView = redWidget.sliceView()
    #redLogic.SetBackgroundWindowLevel(*windowLevel)

    sln = slicer.util.getNode('vtkMRMLSliceNodeRed')
    dims = list(sliceZImageNode.GetImageData().GetDimensions())
    # dims[0] is x, dims[1] is y, dims [2] is Z
    redWidget.setFixedSize(720, 660)
    slncw = redWidget.sliceController()
    slncw.showLabelOutline(1)
    slncw.fitSliceToBackground()
    #sln.SetFieldOfView(dims[0],dims[1],1)
    #sln.SetDimensions(dims[0],dims[1],1)

    sliceannotations = slicer.modules.DataProbeInstance.infoWidget.sliceAnnoations
    if sliceannotations.sliceViewAnnotationsCheckBox.checkState() == 2:
        sliceannotations.sliceViewAnnotationsCheckBox.click()

    slicer.app.processEvents()
    wti = vtk.vtkWindowToImageFilter()
    wti.SetInput(redView.renderWindow())
    wti.Update()
    imgDataRedSlice = wti.GetOutput()

    modelMakerCLI(labelNode)
    imgData3D = GetModelSnapshot()

    append = vtk.vtkImageAppend()
    append.SetAppendAxis(0)
    append.AddInputData(imgDataRedSlice)
    append.AddInputData(imgData3D)
    append.Update()
    finalImage = append.GetOutput()

    #finalImagePath = str(os.path.join(imgOutputDir, IDcurrPatient + '_axial_sliceZ.png'))
    finalImagePath = str(
        os.path.join(
            imgOutputDir,
            imagePatientID_StudyDate + '_' + imageSeriesDescription + '.png'))
    writer = vtk.vtkPNGWriter()
    writer.SetFileName(finalImagePath)
    writer.SetInputData(finalImage)
    writer.Write()
Exemplo n.º 11
0
def modelHandler(imageNode, labelNode, Zind):
    sliceZImageNode = extractMaxZSlice(imageNode, Zind)
    sliceZLabelNode = extractMaxZSlice(labelNode, Zind)

    volumesLogic = slicer.vtkSlicerVolumesLogic()
    volumesLogic.SetVolumeAsLabelMap(sliceZLabelNode, True)
    volumesLogic.SetVolumeAsLabelMap(labelNode, True)

    sliceZLabelNodeDisplay = sliceZLabelNode.GetDisplayNode()
    sliceZLabelNodeDisplay.SetAndObserveColorNodeID(
        'vtkMRMLColorTableNodeFileGenericColors.txt')
    sliceZLabelNode.SetAndObserveDisplayNodeID(sliceZLabelNodeDisplay.GetID())
    labelNodeDisplay = labelNode.GetDisplayNode()
    labelNodeDisplay.SetAndObserveColorNodeID(
        'vtkMRMLColorTableNodeFileGenericColors.txt')
    labelNode.SetAndObserveDisplayNodeID(labelNodeDisplay.GetID())

    ##
    appLogic = slicer.app.applicationLogic()
    selectionNode = appLogic.GetSelectionNode()
    selectionNode.SetReferenceActiveVolumeID(sliceZImageNode.GetID())
    selectionNode.SetReferenceActiveLabelVolumeID(sliceZLabelNode.GetID())
    appLogic.PropagateVolumeSelection()

    ##
    lm = slicer.app.layoutManager()
    lm.setLayout(slicer.vtkMRMLLayoutNode.SlicerLayoutFourUpView)
    redWidget = lm.sliceWidget('Red')
    redLogic = redWidget.sliceLogic()
    redView = redWidget.sliceView()
    #redLogic.SetBackgroundWindowLevel(*windowLevel)

    sln = slicer.util.getNode('vtkMRMLSliceNodeRed')
    dims = list(sliceZImageNode.GetImageData().GetDimensions())
    # dims[0] is x, dims[1] is y, dims [2] is Z
    redWidget.setFixedSize(720, 660)
    slncw = redWidget.sliceController()
    slncw.showLabelOutline(1)
    slncw.fitSliceToBackground()
    #sln.SetFieldOfView(dims[0],dims[1],1)
    #sln.SetDimensions(dims[0],dims[1],1)

    sliceannotations = slicer.modules.DataProbeInstance.infoWidget.sliceAnnoations
    if sliceannotations.sliceViewAnnotationsCheckBox.checkState() == 2:
        sliceannotations.sliceViewAnnotationsCheckBox.click()

    slicer.app.processEvents()
    wti = vtk.vtkWindowToImageFilter()
    wti.SetInput(redView.renderWindow())
    wti.Update()
    imgDataRedSlice = wti.GetOutput()

    modelMakerCLI(labelNode)
    imgData3D = GetModelSnapshot()

    append = vtk.vtkImageAppend()
    append.SetAppendAxis(0)
    append.AddInputData(imgDataRedSlice)
    append.AddInputData(imgData3D)
    append.Update()
    finalImage = append.GetOutput()

    return finalImage
Exemplo n.º 12
0
def modelHandler(ImageFilePath, imageNode, labelNode, imgOutputDir, IDcurrPatient, Zind):
  """
  imageBuffer = vtk.vtkImageData()
  label = growCut(imageNode.GetImageData(),labelNode.GetImageData(),imageBuffer)
  q = labelNode.GetImageData()
  q.DeepCopy(label)
  if labelNode.GetImageDataConnection():
    labelNode.GetImageDataConnection().GetProducer().Update()
  if labelNode.GetImageData().GetPointData().GetScalars() != None:
    labelNode.GetImageData().GetPointData().GetScalars().Modified()
  labelNode.GetImageData().Modified()
  labelNode.Modified()
  pdb.set_trace()
  """
  imageSeriesDescription = os.path.basename(ImageFilePath).replace('.nrrd','')
  imagePatientID = os.path.basename(os.path.dirname(os.path.dirname(os.path.dirname((ImageFilePath)))))
  imageStudyDate = os.path.basename(os.path.dirname(os.path.dirname((ImageFilePath))))
  imagePatientID_StudyDate = imagePatientID + '_' + imageStudyDate
  
  inputImage = su.PullFromSlicer(imageNode.GetName())
  inputLabel = su.PullFromSlicer(labelNode.GetName())
  pixelID = inputImage.GetPixelIDValue()
  FlipYAxis = sitk.FlipImageFilter()
  FlipYAxis.SetFlipAxes([False, True, False])  
  sizeZ = list(inputImage.GetSize())
  sizeZ[2] = 0
  indexZ = [0, 0, Zind]
  ExtractorZ = sitk.ExtractImageFilter()
  ExtractorZ.SetSize(sizeZ)
  ExtractorZ.SetIndex(indexZ)
  sliceZImage = ExtractorZ.Execute(inputImage)
  sliceZLabel = ExtractorZ.Execute(inputLabel)
  imageName = 'Axial_Slice_Image' + IDcurrPatient
  labelName = 'Axial_Slice_Label' + IDcurrPatient
  su.PushToSlicer(sliceZImage, imageName)
  su.PushToSlicer(sliceZLabel, labelName)
  
  sliceZImageNode = slicer.util.getNode(imageName)
  sliceZLabelNode = slicer.util.getNode(labelName)
  volumesLogic = slicer.vtkSlicerVolumesLogic()
  volumesLogic.SetVolumeAsLabelMap(sliceZLabelNode, True)
  volumesLogic.SetVolumeAsLabelMap(labelNode, True)
   
  #sliceZLabelNode = binarizeLabelMapToValue(sliceZLabelNode, labelValue=296)
  #labelNode = binarizeLabelMapToValue(labelNode, labelValue=296)
  
  sliceZLabelNodeDisplay = sliceZLabelNode.GetDisplayNode()
  sliceZLabelNodeDisplay.SetAndObserveColorNodeID('vtkMRMLColorTableNodeFileGenericColors.txt')
  sliceZLabelNode.SetAndObserveDisplayNodeID(sliceZLabelNodeDisplay.GetID())
  labelNodeDisplay = labelNode.GetDisplayNode()
  labelNodeDisplay.SetAndObserveColorNodeID('vtkMRMLColorTableNodeFileGenericColors.txt')
  labelNode.SetAndObserveDisplayNodeID(labelNodeDisplay.GetID())
  
  ##
  appLogic = slicer.app.applicationLogic()
  selectionNode = appLogic.GetSelectionNode()
  selectionNode.SetReferenceActiveVolumeID(sliceZImageNode.GetID())
  selectionNode.SetReferenceActiveLabelVolumeID(sliceZLabelNode.GetID())  
  appLogic.PropagateVolumeSelection()
  
  ##
  lm = slicer.app.layoutManager()
  lm.setLayout(slicer.vtkMRMLLayoutNode.SlicerLayoutFourUpView)
  redWidget = lm.sliceWidget('Red')
  redLogic = redWidget.sliceLogic()
  redView = redWidget.sliceView()
  #redLogic.SetBackgroundWindowLevel(*windowLevel)
   
  sln = slicer.util.getNode('vtkMRMLSliceNodeRed')
  dims = list(sliceZImageNode.GetImageData().GetDimensions())
  # dims[0] is x, dims[1] is y, dims [2] is Z 
  redWidget.setFixedSize(720,660)
  slncw = redWidget.sliceController()
  slncw.showLabelOutline(1)
  slncw.fitSliceToBackground()
  #sln.SetFieldOfView(dims[0],dims[1],1)
  #sln.SetDimensions(dims[0],dims[1],1)
  
  sliceannotations = slicer.modules.DataProbeInstance.infoWidget.sliceAnnoations
  if sliceannotations.sliceViewAnnotationsCheckBox.checkState() == 2:
    sliceannotations.sliceViewAnnotationsCheckBox.click()
  
  slicer.app.processEvents()
  wti=vtk.vtkWindowToImageFilter()  
  wti.SetInput(redView.renderWindow())
  wti.Update()
  imgDataRedSlice = wti.GetOutput()
 
  modelMakerCLI(labelNode) 
  imgData3D = GetModelSnapshot()
  
  append = vtk.vtkImageAppend() 
  append.SetAppendAxis(0)
  append.AddInputData(imgDataRedSlice)
  append.AddInputData(imgData3D)
  append.Update()
  finalImage = append.GetOutput()
  
  #finalImagePath = str(os.path.join(imgOutputDir, IDcurrPatient + '_axial_sliceZ.png'))
  finalImagePath = str(os.path.join(imgOutputDir, imagePatientID_StudyDate + '_' + imageSeriesDescription +'.png'))
  writer=vtk.vtkPNGWriter()
  writer.SetFileName(finalImagePath)
  writer.SetInputData(finalImage)
  writer.Write()
Exemplo n.º 13
0
def createLabelMap(self, dataNode, labelNode, outputDir, IDcurrPatient):
  """
  self.sliceXarray = numpy.rollaxis(self.sliceXarray,1)[:,:,None] #512,36,1
  #self.sliceXarray = self.sliceXarray[:,:,None]
  
  self.sliceYarray = numpy.rollaxis(self.sliceYarray,1)[:,:,None] #512,36,1
  #self.sliceYarray = self.sliceYarray[:,:,None]
  
  #self.slizeZarray = numpy.rot90(self.sliceZarray)
  self.sliceZarray = self.sliceZarray[:,:,None] #512,512,1
  
  self.sliceXnode = slicer.vtkMRMLScalarVolumeNode()
  self.sliceYnode = slicer.vtkMRMLScalarVolumeNode()
  self.sliceZnode = slicer.vtkMRMLScalarVolumeNode()
  self.sliceXnode.SetName('SliceX')
  self.sliceYnode.SetName('SliceY')
  self.sliceZnode.SetName('SliceZ')
   
  self.sliceXNodeDisplayNode = slicer.vtkMRMLVectorVolumeDisplayNode()
  slicer.mrmlScene.AddNode(self.sliceXNodeDisplayNode)
  self.sliceXnode.SetAndObserveDisplayNodeID(self.sliceXNodeDisplayNode.GetID())
  
  self.sliceYNodeDisplayNode = slicer.vtkMRMLVectorVolumeDisplayNode()
  slicer.mrmlScene.AddNode(self.sliceYNodeDisplayNode)
  self.sliceYnode.SetAndObserveDisplayNodeID(self.sliceYNodeDisplayNode.GetID())

  self.sliceZNodeDisplayNode = slicer.vtkMRMLVectorVolumeDisplayNode()
  slicer.mrmlScene.AddNode(self.sliceZNodeDisplayNode)
  self.sliceZnode.SetAndObserveDisplayNodeID(self.sliceZNodeDisplayNode.GetID())
  """
  imageFilePath = dataNode.GetStorageNode().GetFileName()
  imageName = os.path.basename(imageFilePath).replace('.nrrd','')
  
  reconDir = os.path.dirname(imageFilePath)
  studyDir = os.path.dirname(reconDir)
  segDir  = [dirpath for dirpath in glob.glob(os.path.join(studyDir,'*')) if 'Segmentations' in dirpath][0]
  resourcesDir = [dirpath for dirpath in glob.glob(os.path.join(studyDir,'*')) if 'Resources' in dirpath][0]
  spacing = dataNode.GetSpacing()
  origin = dataNode.GetOrigin()
  #pdb.set_trace()
  
  arrays = []
  for r,d,f in os.walk(studyDir):
    [arrays.append(os.path.join(r,file)) for file in fnmatch.filter(f, '*.npy')]

  try:
    name = os.path.basename(arrays[0]).replace('.npy', '')
  except IndexError:
    print(IDcurrPatient, ': FAILED TO PROCESS NPY FILE')
    return
  arr = numpy.load(arrays[0])
  #arr = numpy.ascontiguousarray(arr)
  
  #nump_arr = reversedim(arr,0)
  nump_arr = numpy.swapaxes(arr, 0, 2)
  
  #nump_arr = nump_arr[...,::-1]
  #nump_arr = numpy.rollaxis(numpy.rollaxis(nump_arr,2),2,1)

  self.labelMapnode = slicer.vtkMRMLScalarVolumeNode()
  self.labelMapnode.SetName('labelMap')
  self.labelMapnode.LabelMapOn()
  
  self.labelMapnodeDisplayNode = slicer.vtkMRMLScalarVolumeDisplayNode()
  slicer.mrmlScene.AddNode(self.labelMapnodeDisplayNode)
  self.labelMapnode.SetAndObserveDisplayNodeID(self.labelMapnodeDisplayNode.GetID())
  self.labelMapnodeDisplayNode.SetAndObserveColorNodeID('vtkMRMLColorTableNodeFileGenericColors.txt')
  
  try:
    self.labelMapnode = renderArray(self, nump_arr, self.labelMapnode, dataNode, shape=nump_arr.shape, spacing=spacing, origin=origin)
  except ValueError:
    print(IDcurrPatient, ': FAILED TO CONVERT TO LABEL MAP')
    return
  #self.sliceXnode = self.renderSlice(self.sliceXarray, self.sliceXnode, self.dataNode, shape=self.sliceXarray.shape, spacing=(x,z,1))
  #self.sliceYnode = self.renderSlice(self.sliceYarray, self.sliceYnode, self.dataNode, shape=self.sliceYarray.shape, spacing=(y,z,1))
  #self.sliceZnode = self.renderSlice(self.sliceZarray, self.sliceZnode, self.dataNode, shape=self.sliceZarray.shape, spacing=(x,y,1))
  
  self.labelMapnode = binarizeLabelMapToValue(self.labelMapnode)  
  self.labelMapnodeDisplayNode.SetInputImageDataConnection(self.labelMapnode.GetImageDataConnection())
  self.labelMapnodeDisplayNode.UpdateImageDataPipeline()
  
  volumesLogic = slicer.vtkSlicerVolumesLogic()
  volumesLogic.CenterVolume(dataNode)
  volumesLogic.CenterVolume(self.labelMapnode)
  
  labelMapNodeFileName = os.path.join(segDir, imageName + '_labelMap.nrrd')
  saveLabelMap = slicer.util.saveNode(self.labelMapnode, labelMapNodeFileName, properties={"filetype": ".nrrd"})
  #saveNode = slicer.util.saveNode(dataNode, imageFilePath, properties={"filetype": ".nrrd"})
  arraysName = os.path.basename(arrays[0])
  shutil.move(arrays[0],os.path.join(resourcesDir,arraysName))
  
  labelMapNodeSITK = sitk.ReadImage(str(labelMapNodeFileName))
  FlipZAxis = sitk.FlipImageFilter()
  FlipZAxis.SetDebug(False)
  FlipZAxis.SetFlipAxes([False, False, True])
  FlipZAxis.SetFlipAboutOrigin(True)
  FlipZAxis.SetNumberOfThreads(4)
  labelMapNodeSITK = FlipZAxis.Execute(labelMapNodeSITK)
  FlipZAxis.Execute(labelMapNodeSITK)
  sitk.WriteImage(labelMapNodeSITK, str(labelMapNodeFileName) )
  """