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')        
    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
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 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()
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) )
  """