Exemple #1
0
  def createSampleLabelmapVolumeNode(self, volumeNode, name, label, colorNode=None):
    self.assertTrue( volumeNode != None )
    self.assertTrue( volumeNode.IsA('vtkMRMLScalarVolumeNode') )
    self.assertTrue( label > 0 )

    sampleLabelmapNode = slicer.vtkMRMLLabelMapVolumeNode()
    sampleLabelmapNode.SetName(name)
    sampleLabelmapNode = slicer.mrmlScene.AddNode(sampleLabelmapNode)
    sampleLabelmapNode.Copy(volumeNode)
    imageData = vtk.vtkImageData()
    imageData.DeepCopy(volumeNode.GetImageData())
    sampleLabelmapNode.SetAndObserveImageData(imageData)

    extent = imageData.GetExtent()
    for x in xrange(extent[0], extent[1]+1):
      for y in xrange(extent[2], extent[3]+1):
        for z in xrange(extent[4], extent[5]+1):
          if (x >= (extent[1]/4) and x <= (extent[1]/4) * 3) and (y >= (extent[3]/4) and y <= (extent[3]/4) * 3) and (z >= (extent[5]/4) and z <= (extent[5]/4) * 3):
            imageData.SetScalarComponentFromDouble(x,y,z,0,label)
          else:
            imageData.SetScalarComponentFromDouble(x,y,z,0,0)

    # Display labelmap
    labelmapVolumeDisplayNode = slicer.vtkMRMLLabelMapVolumeDisplayNode()
    slicer.mrmlScene.AddNode(labelmapVolumeDisplayNode)
    if colorNode == None:
      colorNode = slicer.util.getNode('GenericAnatomyColors')
      self.assertTrue( colorNode != None )
    labelmapVolumeDisplayNode.SetAndObserveColorNodeID(colorNode.GetID())
    labelmapVolumeDisplayNode.VisibilityOn()
    sampleLabelmapNodeName = slicer.mrmlScene.GenerateUniqueName(name)
    sampleLabelmapNode.SetName(sampleLabelmapNodeName)
    sampleLabelmapNode.SetAndObserveDisplayNodeID(labelmapVolumeDisplayNode.GetID())

    return sampleLabelmapNode
 def CreateNewNode(self, colorName, color, dim, origin):
     # we add a pseudo-random number to the name of our empty volume to avoid the risk of having a volume called
     #  exactly the same by the user which could be confusing. We could also have used slicer.app.sessionId()
     if colorName not in self.colorSliceVolumes.keys():
         VolumeName = "EasyClip_EmptyVolume_" + str(slicer.app.applicationPid()) + "_" + colorName
         # Do NOT set the spacing and the origin of imageData (vtkImageData)
         # The spacing and the origin should only be set in the vtkMRMLScalarVolumeNode!!!!!!
         # We only create an image of 1 voxel (as we only use it to color the planes
         imageData = vtk.vtkImageData()
         imageData.SetDimensions(1, 1, 1)
         imageData.AllocateScalars(vtk.VTK_UNSIGNED_CHAR, 1)
         imageData.SetScalarComponentFromDouble(0, 0, 0, 0, color)
         if hasattr(slicer, 'vtkMRMLLabelMapVolumeNode'):
             sampleVolumeNode = slicer.vtkMRMLLabelMapVolumeNode()
         else:
             sampleVolumeNode = slicer.vtkMRMLScalarVolumeNode()
         sampleVolumeNode = slicer.mrmlScene.AddNode(sampleVolumeNode)
         sampleVolumeNode.SetName(VolumeName)
         labelmapVolumeDisplayNode = slicer.vtkMRMLLabelMapVolumeDisplayNode()
         slicer.mrmlScene.AddNode(labelmapVolumeDisplayNode)
         colorNode = slicer.util.getNode('GenericAnatomyColors')
         labelmapVolumeDisplayNode.SetAndObserveColorNodeID(colorNode.GetID())
         sampleVolumeNode.SetAndObserveImageData(imageData)
         sampleVolumeNode.SetAndObserveDisplayNodeID(labelmapVolumeDisplayNode.GetID())
         labelmapVolumeDisplayNode.VisibilityOff()
         self.colorSliceVolumes[colorName] = sampleVolumeNode.GetID()
     sampleVolumeNode = slicer.mrmlScene.GetNodeByID(self.colorSliceVolumes[colorName])
     sampleVolumeNode.HideFromEditorsOn()
     sampleVolumeNode.SetOrigin(origin[0], origin[1], origin[2])
     sampleVolumeNode.SetSpacing(dim[0], dim[1], dim[2])
     if not hasattr(slicer, 'vtkMRMLLabelMapVolumeNode'):
         sampleVolumeNode.SetLabelMap(1)
     sampleVolumeNode.SetHideFromEditors(True)
     sampleVolumeNode.SetSaveWithScene(False)
     return sampleVolumeNode
Exemple #3
0
    def convertToLabelMap(self, volumeNode, name):
        volumesLogic = slicer.modules.volumes.logic()

        newLabelNode = slicer.vtkMRMLLabelMapVolumeNode()
        newLabelNode.SetName(volumeNode.GetName())
        newLabelNode.SetHideFromEditors(volumeNode.GetHideFromEditors())
        newLabelNode.SetSaveWithScene(volumeNode.GetSaveWithScene())
        newLabelNode.SetSelectable(volumeNode.GetSelectable())
        newLabelNode.SetSingletonTag(volumeNode.GetSingletonTag())
        newLabelNode.SetDescription(volumeNode.GetDescription())
        #TODO: Attributes
        slicer.mrmlScene.AddNode(newLabelNode)

        volumesLogic.CreateLabelVolumeFromVolume(slicer.mrmlScene,
                                                 newLabelNode, volumeNode)
        slicer.mrmlScene.RemoveNode(volumeNode)
  def ConvertStructureSetToLabelmap(self):
    import vtkSlicerDicomRtImportExportModuleLogic
    import vtkSegmentationCore
    import vtkSlicerSegmentationsModuleMRML
    import vtkSlicerSegmentationsModuleLogic

    labelmapsToSave = []
    
    # Get all segmentation nodes from the scene
    segmentationNodes = slicer.util.getNodes('vtkMRMLSegmentationNode*')

    for segmentationNode in segmentationNodes.values():
      logging.info('  Converting structure set ' + segmentationNode.GetName())
      # Set referenced volume as rasterization reference
      referenceVolume = vtkSlicerDicomRtImportExportModuleLogic.vtkSlicerDicomRtImportExportModuleLogic.GetReferencedVolumeByDicomForSegmentation(segmentationNode)
      if referenceVolume == None:
        logging.error('No reference volume found for segmentation ' + segmentationNode.GetName())
        continue
        
      # Perform conversion
      binaryLabelmapRepresentationName = vtkSegmentationCore.vtkSegmentationConverter.GetSegmentationBinaryLabelmapRepresentationName()
      segmentation = segmentationNode.GetSegmentation()
      segmentation.CreateRepresentation(binaryLabelmapRepresentationName)
      
      # Create labelmap volume nodes from binary labelmaps
      segmentIDs = vtk.vtkStringArray()
      segmentation.GetSegmentIDs(segmentIDs)
      for segmentIndex in xrange(0,segmentIDs.GetNumberOfValues()):
        segmentID = segmentIDs.GetValue(segmentIndex)
        segment = segmentation.GetSegment(segmentID)
        binaryLabelmap = segment.GetRepresentation(vtkSegmentationCore.vtkSegmentationConverter.GetSegmentationBinaryLabelmapRepresentationName())
        if not binaryLabelmap:
          logging.error('Failed to retrieve binary labelmap from segment ' + segmentID + ' in segmentation ' + segmentationNode.GetName())
          continue
        labelmapNode = slicer.vtkMRMLLabelMapVolumeNode()
        slicer.mrmlScene.AddNode(labelmapNode)
        labelmapName = segmentationNode.GetName() + "_" + segmentID
        labelmapNode.SetName(labelmapName)
        if not vtkSlicerSegmentationsModuleLogic.vtkSlicerSegmentationsModuleLogic.CreateLabelmapVolumeFromOrientedImageData(binaryLabelmap,labelmapNode):
          logging.error('Failed to create labelmap from segment ' + segmentID + ' in segmentation ' + segmentationNode.GetName())
          continue

        # Append volume to list
        labelmapsToSave.append(labelmapNode)
      
    return labelmapsToSave
  def CreateNewLabelVolume(self,name):
    """ Creates a new labelmap volume with the inputted name
    """

    # Create labelmap node
    labelNode=slicer.vtkMRMLLabelMapVolumeNode()
    labelNode.SetName(name)

    # Add volume to scene
    slicer.mrmlScene.AddNode(labelNode)
    displayNode=slicer.vtkMRMLScalarVolumeDisplayNode()
    slicer.mrmlScene.AddNode(displayNode)
    colorNode = slicer.util.getNode('Grey')
    displayNode.SetAndObserveColorNodeID(colorNode.GetID())
    labelNode.SetAndObserveDisplayNodeID(displayNode.GetID())
    labelNode.CreateDefaultStorageNode() 

    return labelNode
Exemple #6
0
 def CreateNewNode(self, colorName, color, dim, origin):
     # we add a pseudo-random number to the name of our empty volume to avoid the risk of having a volume called
     #  exactly the same by the user which could be confusing. We could also have used slicer.app.sessionId()
     if colorName not in self.colorSliceVolumes.keys():
         VolumeName = "EasyClip_EmptyVolume_" + str(
             slicer.app.applicationPid()) + "_" + colorName
         # Do NOT set the spacing and the origin of imageData (vtkImageData)
         # The spacing and the origin should only be set in the vtkMRMLScalarVolumeNode!!!!!!
         # We only create an image of 1 voxel (as we only use it to color the planes
         imageData = vtk.vtkImageData()
         imageData.SetDimensions(1, 1, 1)
         imageData.AllocateScalars(vtk.VTK_UNSIGNED_CHAR, 1)
         imageData.SetScalarComponentFromDouble(0, 0, 0, 0, color)
         if hasattr(slicer, 'vtkMRMLLabelMapVolumeNode'):
             sampleVolumeNode = slicer.vtkMRMLLabelMapVolumeNode()
         else:
             sampleVolumeNode = slicer.vtkMRMLScalarVolumeNode()
         sampleVolumeNode = slicer.mrmlScene.AddNode(sampleVolumeNode)
         sampleVolumeNode.SetName(VolumeName)
         labelmapVolumeDisplayNode = slicer.vtkMRMLLabelMapVolumeDisplayNode(
         )
         slicer.mrmlScene.AddNode(labelmapVolumeDisplayNode)
         colorNode = slicer.util.getNode('GenericAnatomyColors')
         labelmapVolumeDisplayNode.SetAndObserveColorNodeID(
             colorNode.GetID())
         sampleVolumeNode.SetAndObserveImageData(imageData)
         sampleVolumeNode.SetAndObserveDisplayNodeID(
             labelmapVolumeDisplayNode.GetID())
         labelmapVolumeDisplayNode.VisibilityOff()
         self.colorSliceVolumes[colorName] = sampleVolumeNode.GetID()
     sampleVolumeNode = slicer.mrmlScene.GetNodeByID(
         self.colorSliceVolumes[colorName])
     sampleVolumeNode.HideFromEditorsOn()
     sampleVolumeNode.SetOrigin(origin[0], origin[1], origin[2])
     sampleVolumeNode.SetSpacing(dim[0], dim[1], dim[2])
     if not hasattr(slicer, 'vtkMRMLLabelMapVolumeNode'):
         sampleVolumeNode.SetLabelMap(1)
     sampleVolumeNode.SetHideFromEditors(True)
     sampleVolumeNode.SetSaveWithScene(False)
     return sampleVolumeNode
def DoIt(inputDir, labelFile, outputDir, forceLabel, forceResample):

  dbDir1 = slicer.app.temporaryPath+'/LabelConverter'

  if not hasattr(slicer.modules, 'reporting'):
    print 'The Reporting module has not been loaded into Slicer, script cannot run!\n\tTry setting the --additional-module-path parameter.'
    sys.exit(1)

  reportingLogic = slicer.modules.reporting.logic()

  print('Temporary directory location: '+dbDir1)
  qt.QDir().mkpath(dbDir1)

  dbDir0 = None
  if slicer.dicomDatabase:
    dbDir0 = os.path.split(slicer.dicomDatabase.databaseFilename)[0]

  dicomWidget = slicer.modules.dicom.widgetRepresentation().self()
  dicomWidget.onDatabaseDirectoryChanged(dbDir1)

  # import DICOM study
  indexer = ctk.ctkDICOMIndexer()
  indexer.addDirectory(slicer.dicomDatabase, inputDir, None)
  indexer.waitForImportFinished()

  print('DICOM import finished!')

  #
  # Read the input DICOM series as a volume
  #
  dcmList = []
  for dcm in os.listdir(inputDir):
    if len(dcm)-dcm.rfind('.dcm') == 4:
      dcmList.append(inputDir+'/'+dcm)

  scalarVolumePlugin = slicer.modules.dicomPlugins['DICOMScalarVolumePlugin']()

  loadables = scalarVolumePlugin.examine([dcmList])

  if len(loadables) == 0:
    print 'Could not parse the DICOM Study!'
    sys.exit(1)

  inputVolume = scalarVolumePlugin.load(loadables[0])
  print 'Input volume loaded! ID = ', inputVolume.GetID()

  # read the label volume
  labelVolume = slicer.vtkMRMLLabelMapVolumeNode()
  sNode = slicer.vtkMRMLVolumeArchetypeStorageNode()
  sNode.SetFileName(labelFile)
  sNode.ReadData(labelVolume)

  if forceLabel>0:
    # print('Forcing label to '+str(forceLabel))
    labelImage = labelVolume.GetImageData()
    thresh = vtk.vtkImageThreshold()
    if vtk.vtkVersion().GetVTKMajorVersion() < 6:
      thresh.SetInput(labelImage)
    else:
      thresh.SetInputData(labelImage)
      thresh.ThresholdBetween(1, labelImage.GetScalarRange()[1])
      thresh.SetInValue(int(forceLabel))
      thresh.SetOutValue(0)
      thresh.ReplaceInOn()
      thresh.ReplaceOutOn()
      thresh.Update()
      labelImage = thresh.GetOutput()
      labelVolume.SetAndObserveImageData(labelImage)

  slicer.mrmlScene.AddNode(labelVolume)
  print 'Label volume added, id = ', labelVolume.GetID()

  # ensure that the label volume scalar type is unsigned short
  if labelVolume.GetImageData() != None:
    scalarType = labelVolume.GetImageData().GetScalarType()
    if scalarType != vtk.VTK_UNSIGNED_SHORT:
      print 'Label volume has pixel type of ',vtk.vtkImageScalarTypeNameMacro(scalarType),', casting to unsigned short'
      cast = vtk.vtkImageCast()
      cast.SetOutputScalarTypeToUnsignedShort()
      if vtk.vtkVersion().GetVTKMajorVersion() < 6:
        cast.SetInput(labelVolume.GetImageData())
        cast.Update()
        labelVolume.SetAndObserveImageData(cast.GetOutput())
      else:
        cast.SetInputConnection(labelVolume.GetImageDataConnection())
        cast.Update()
        labelVolume.SetImageDataConnection(cast.GetOutputPort())
      if labelVolume.GetImageData().GetScalarType() != vtk.VTK_UNSIGNED_SHORT:
        print 'Failed to cast label volume to unsigned short, type is ',  vtk.vtkImageScalarTypeNameMacro(labelVolume.GetImageData().GetScalarType())
        sys.exit(1)

  volumesLogic = slicer.modules.volumes.logic()
  geometryCheckString = volumesLogic.CheckForLabelVolumeValidity(inputVolume, labelVolume)
  if geometryCheckString != "":
    # has the user specified that forced resampling is okay?
    if forceResample == False:
      print 'Label volume mismatch with input volume:\n',geometryCheckString,'\nForced resample not specified, aborting. Re-run with --force option to ignore geometric inconsistencies'
      sys.exit(1)
    # resample label to the input volume raster
    resampledLabel = slicer.vtkMRMLLabelMapVolumeNode()
    slicer.mrmlScene.AddNode(resampledLabel)
    print 'Resampled label added, id = ', resampledLabel.GetID()
    resampledLabel = volumesLogic.ResampleVolumeToReferenceVolume(labelVolume, inputVolume)
    labelVolume = resampledLabel

  displayNode = slicer.vtkMRMLLabelMapVolumeDisplayNode()
  displayNode.SetAndObserveColorNodeID(reportingLogic.GetDefaultColorNode().GetID())
  slicer.mrmlScene.AddNode(displayNode)

  labelVolume.SetAttribute('AssociatedNodeID',inputVolume.GetID())
  labelVolume.SetAndObserveDisplayNodeID(displayNode.GetID())

  # initialize the DICOM DB for Reporting logic, save as DICOM SEG
  labelCollection = vtk.vtkCollection()
  labelCollection.AddItem(labelVolume)

  print('About to write DICOM SEG!')
  dbFileName = slicer.dicomDatabase.databaseFilename
  reportingLogic.InitializeDICOMDatabase(dbFileName)
  reportingLogic.DicomSegWrite(labelCollection, outputDir)

  dicomWidget.onDatabaseDirectoryChanged(dbDir0)

  exit()
def DoIt(inputDir, rgbDir, outputDir):


  #
  # Read the input DICOM series as a volume
  #
  dcmList = []
  for dcm in os.listdir(inputDir):
    if len(dcm)-dcm.rfind('.dcm') == 4:
      dcmList.append(inputDir+'/'+dcm)

  scalarVolumePlugin = slicer.modules.dicomPlugins['DICOMScalarVolumePlugin']()

  print 'Will examine: ',dcmList


  indexer = ctk.ctkDICOMIndexer()
  indexer.addDirectory(slicer.dicomDatabase, inputDir)
  indexer.waitForImportFinished()

  loadables = scalarVolumePlugin.examine([dcmList])

  if len(loadables) == 0:
    print 'Could not parse the DICOM Study!'
    exit()

  inputVolume = scalarVolumePlugin.load(loadables[0])

  sNode = slicer.vtkMRMLVolumeArchetypeStorageNode()
  '''
  sNode.ResetFileNameList()
  for f in loadables[0].files:
    sNode.AddFileName(f)
  sNode.SetFileName(loadables[0].files[0])
  sNode.SetSingleFile(0)
  inputVolume = slicer.vtkMRMLScalarVolumeNode()
  sNode.ReadData(inputVolume)
  '''

  sNode.SetWriteFileFormat('nrrd')
  sNode.SetFileName(os.path.join(outputDir,'input_volume.nrrd'))
  sNode.WriteData(inputVolume)

  #
  # Order the input RGBs and rename in a temp directory
  #
  rgbList = []
  for rgb in os.listdir(rgbDir):
    if len(rgb)-rgb.rfind('.bmp') == 4:
      rgbList.append(rgb)

  tmpDir = slicer.app.settings().value('Modules/TemporaryDirectory')
  tmpDir = tmpDir+'/PNGStackLabelConverter'
  if not os.path.exists(tmpDir):
    os.mkdir(tmpDir)

  oldFiles = os.listdir(tmpDir)
  # just in case there is anything in that directory
  for f in oldFiles:
    os.unlink(tmpDir+'/'+f)

  rgbOrdered = [None] * len(loadables[0].files)
  rgbCnt = 0
  rgbExt = rgbList[0][rgbList[0].rfind('.')+1:len(rgbList[0])]
  print 'Extension for RGBs: ',rgbExt

  dcmFileList = loadables[0].files
  rgbRenamedList = []

  print 'Number of dcm files: ',len(dcmFileList), ' and rgb files: ',len(rgbOrdered)

  dcmIdx = 0
  for dcm in dcmFileList:
    rgbIdx = 0

    for rgb in rgbList:

      dcmPrefix = dcm[dcm.rfind('/')+1:dcm.rfind('.')]

      if rgb.find(dcmPrefix) != -1:
        name = string.zfill(str(dcmIdx),5)
        rgbCnt = rgbCnt+1
        src = rgbDir+'/'+rgb
        dest = tmpDir+'/'+name+'.'+rgbExt
        rgbRenamedList.append(dest)
        shutil.copy(src,dest)

        break
      rgbIdx = rgbIdx+1

    # remove the matched DICOM file from the list
    if rgbIdx == len(rgbList):
      print('ERROR: failed to find matching label file for DICOM file '+dcm)
      return

    del rgbList[rgbIdx]
    dcmIdx = dcmIdx+1

  if len(rgbRenamedList) == 0:
    print 'Could not parse the DICOM Study!'
    return

  sNode = slicer.vtkMRMLVolumeArchetypeStorageNode()
  sNode.ResetFileNameList()
  for f in rgbRenamedList:
    sNode.AddFileName(f)
  sNode.SetFileName(rgbRenamedList[0])
  sNode.SetSingleFile(0)
  inputRGBVolume = slicer.vtkMRMLVectorVolumeNode()
  sNode.ReadData(inputRGBVolume)


  # run the filter
  # - extract the RGB portions
  extract = vtk.vtkImageExtractComponents()
  extract.SetComponents(0,1,2)
  if vtk.vtkVersion().GetVTKMajorVersion() < 6:
    extract.SetInput(inputRGBVolume.GetImageData())
  else:
    extract.SetInputData(inputRGBVolume.GetImageData())

  luminance = vtk.vtkImageLuminance()
  if vtk.vtkVersion().GetVTKMajorVersion() < 6:
    luminance.SetInput(extract.GetOutput())
  else:
    luminance.SetInputData(extract.GetOutput())

  cast = vtk.vtkImageCast()
  if vtk.vtkVersion().GetVTKMajorVersion() < 6:
    cast.SetInput(luminance.GetOutput())
  else:
    cast.SetInputData(luminance.GetOutput())
  cast.SetOutputScalarTypeToShort()
  cast.GetOutput().Update()

  ijkToRAS = vtk.vtkMatrix4x4()
  inputVolume.GetIJKToRASMatrix(ijkToRAS)

  outputLabel = slicer.vtkMRMLLabelMapVolumeNode()
  outputLabel.SetIJKToRASMatrix(ijkToRAS)
  outputLabel.SetAndObserveImageData(cast.GetOutput())

  reportingLogic = slicer.modules.reporting.logic()

  displayNode = slicer.vtkMRMLLabelMapVolumeDisplayNode()
  displayNode.SetAndObserveColorNodeID(reportingLogic.GetDefaultColorNode().GetID())
  slicer.mrmlScene.AddNode(displayNode)
  outputLabel.SetAndObserveDisplayNodeID(displayNode.GetID())

  sNode.SetWriteFileFormat('nrrd')
  sNode.SetFileName(os.path.join(outputDir,'label_output.nrrd'))
  sNode.WriteData(outputLabel)

  # save as DICOM SEG
  labelCollection = vtk.vtkCollection()
  labelCollection.AddItem(outputLabel)

  slicer.mrmlScene.AddNode(inputVolume)
  outputLabel.SetAttribute('AssociatedNodeID',inputVolume.GetID())
  slicer.mrmlScene.AddNode(outputLabel)

  # initialize the DICOM DB for Reporting logic
  settings = qt.QSettings()
  dbFileName = settings.value('DatabaseDirectory','')
  if dbFileName =='':
    print('ERROR: database must be initialized')
  else:
    dbFileName = dbFileName +'/ctkDICOM.sql'
    reportingLogic.InitializeDICOMDatabase(dbFileName)

    reportingLogic.DicomSegWrite(labelCollection, outputDir)
def DoIt(inputDir, rgbDir, outputDir):

    #
    # Read the input DICOM series as a volume
    #
    dcmList = []
    for dcm in os.listdir(inputDir):
        if len(dcm) - dcm.rfind('.dcm') == 4:
            dcmList.append(inputDir + '/' + dcm)

    scalarVolumePlugin = slicer.modules.dicomPlugins[
        'DICOMScalarVolumePlugin']()

    print 'Will examine: ', dcmList

    indexer = ctk.ctkDICOMIndexer()
    indexer.addDirectory(slicer.dicomDatabase, inputDir)
    indexer.waitForImportFinished()

    loadables = scalarVolumePlugin.examine([dcmList])

    if len(loadables) == 0:
        print 'Could not parse the DICOM Study!'
        exit()

    inputVolume = scalarVolumePlugin.load(loadables[0])

    sNode = slicer.vtkMRMLVolumeArchetypeStorageNode()
    '''
  sNode.ResetFileNameList()
  for f in loadables[0].files:
    sNode.AddFileName(f)
  sNode.SetFileName(loadables[0].files[0])
  sNode.SetSingleFile(0)
  inputVolume = slicer.vtkMRMLScalarVolumeNode()
  sNode.ReadData(inputVolume)
  '''

    sNode.SetWriteFileFormat('nrrd')
    sNode.SetFileName(os.path.join(outputDir, 'input_volume.nrrd'))
    sNode.WriteData(inputVolume)

    #
    # Order the input RGBs and rename in a temp directory
    #
    rgbList = []
    for rgb in os.listdir(rgbDir):
        if len(rgb) - rgb.rfind('.bmp') == 4:
            rgbList.append(rgb)

    tmpDir = slicer.app.settings().value('Modules/TemporaryDirectory')
    tmpDir = tmpDir + '/PNGStackLabelConverter'
    if not os.path.exists(tmpDir):
        os.mkdir(tmpDir)

    oldFiles = os.listdir(tmpDir)
    # just in case there is anything in that directory
    for f in oldFiles:
        os.unlink(tmpDir + '/' + f)

    rgbOrdered = [None] * len(loadables[0].files)
    rgbCnt = 0
    rgbExt = rgbList[0][rgbList[0].rfind('.') + 1:len(rgbList[0])]
    print 'Extension for RGBs: ', rgbExt

    dcmFileList = loadables[0].files
    rgbRenamedList = []

    print 'Number of dcm files: ', len(dcmFileList), ' and rgb files: ', len(
        rgbOrdered)

    dcmIdx = 0
    for dcm in dcmFileList:
        rgbIdx = 0

        for rgb in rgbList:

            dcmPrefix = dcm[dcm.rfind('/') + 1:dcm.rfind('.')]

            if rgb.find(dcmPrefix) != -1:
                name = string.zfill(str(dcmIdx), 5)
                rgbCnt = rgbCnt + 1
                src = rgbDir + '/' + rgb
                dest = tmpDir + '/' + name + '.' + rgbExt
                rgbRenamedList.append(dest)
                shutil.copy(src, dest)

                break
            rgbIdx = rgbIdx + 1

        # remove the matched DICOM file from the list
        if rgbIdx == len(rgbList):
            print('ERROR: failed to find matching label file for DICOM file ' +
                  dcm)
            return

        del rgbList[rgbIdx]
        dcmIdx = dcmIdx + 1

    if len(rgbRenamedList) == 0:
        print 'Could not parse the DICOM Study!'
        return

    sNode = slicer.vtkMRMLVolumeArchetypeStorageNode()
    sNode.ResetFileNameList()
    for f in rgbRenamedList:
        sNode.AddFileName(f)
    sNode.SetFileName(rgbRenamedList[0])
    sNode.SetSingleFile(0)
    inputRGBVolume = slicer.vtkMRMLVectorVolumeNode()
    sNode.ReadData(inputRGBVolume)

    # run the filter
    # - extract the RGB portions
    extract = vtk.vtkImageExtractComponents()
    extract.SetComponents(0, 1, 2)
    if vtk.vtkVersion().GetVTKMajorVersion() < 6:
        extract.SetInput(inputRGBVolume.GetImageData())
    else:
        extract.SetInputData(inputRGBVolume.GetImageData())

    luminance = vtk.vtkImageLuminance()
    if vtk.vtkVersion().GetVTKMajorVersion() < 6:
        luminance.SetInput(extract.GetOutput())
    else:
        luminance.SetInputData(extract.GetOutput())

    cast = vtk.vtkImageCast()
    if vtk.vtkVersion().GetVTKMajorVersion() < 6:
        cast.SetInput(luminance.GetOutput())
    else:
        cast.SetInputData(luminance.GetOutput())
    cast.SetOutputScalarTypeToShort()
    cast.GetOutput().Update()

    ijkToRAS = vtk.vtkMatrix4x4()
    inputVolume.GetIJKToRASMatrix(ijkToRAS)

    outputLabel = slicer.vtkMRMLLabelMapVolumeNode()
    outputLabel.SetIJKToRASMatrix(ijkToRAS)
    outputLabel.SetAndObserveImageData(cast.GetOutput())

    reportingLogic = slicer.modules.reporting.logic()

    displayNode = slicer.vtkMRMLLabelMapVolumeDisplayNode()
    displayNode.SetAndObserveColorNodeID(
        reportingLogic.GetDefaultColorNode().GetID())
    slicer.mrmlScene.AddNode(displayNode)
    outputLabel.SetAndObserveDisplayNodeID(displayNode.GetID())

    sNode.SetWriteFileFormat('nrrd')
    sNode.SetFileName(os.path.join(outputDir, 'label_output.nrrd'))
    sNode.WriteData(outputLabel)

    # save as DICOM SEG
    labelCollection = vtk.vtkCollection()
    labelCollection.AddItem(outputLabel)

    slicer.mrmlScene.AddNode(inputVolume)
    outputLabel.SetAttribute('AssociatedNodeID', inputVolume.GetID())
    slicer.mrmlScene.AddNode(outputLabel)

    # initialize the DICOM DB for Reporting logic
    settings = qt.QSettings()
    dbFileName = settings.value('DatabaseDirectory', '')
    if dbFileName == '':
        print('ERROR: database must be initialized')
    else:
        dbFileName = dbFileName + '/ctkDICOM.sql'
        reportingLogic.InitializeDICOMDatabase(dbFileName)

        reportingLogic.DicomSegWrite(labelCollection, outputDir)