def createVectorVolumeFromRoi(self,
                                  exportRoi,
                                  spacingMm,
                                  numberOfComponents=3):
        roiCenter = [0, 0, 0]
        exportRoi.GetXYZ(roiCenter)
        roiRadius = [0, 0, 0]
        exportRoi.GetRadiusXYZ(roiRadius)
        roiOrigin_Roi = [
            roiCenter[0] - roiRadius[0], roiCenter[1] - roiRadius[1],
            roiCenter[2] - roiRadius[2], 1
        ]

        roiToRas = vtk.vtkMatrix4x4()
        if exportRoi.GetTransformNodeID() != None:
            roiBoxTransformNode = slicer.mrmlScene.GetNodeByID(
                exportRoi.GetTransformNodeID())
            roiBoxTransformNode.GetMatrixTransformToWorld(roiToRas)

        exportVolumeSize = [
            roiRadius[0] * 2 / spacingMm, roiRadius[1] * 2 / spacingMm,
            roiRadius[2] * 2 / spacingMm
        ]
        exportVolumeSize = [int(math.ceil(x)) for x in exportVolumeSize]

        exportImageData = vtk.vtkImageData()
        exportImageData.SetExtent(0, exportVolumeSize[0] - 1, 0,
                                  exportVolumeSize[1] - 1, 0,
                                  exportVolumeSize[2] - 1)
        if vtk.VTK_MAJOR_VERSION <= 5:
            exportImageData.SetScalarType(vtk.VTK_DOUBLE)
            exportImageData.SetNumberOfScalarComponents(numberOfComponents)
            exportImageData.AllocateScalars()
        else:
            exportImageData.AllocateScalars(vtk.VTK_DOUBLE, numberOfComponents)

        exportVolume = None
        if numberOfComponents == 1:
            exportVolume = slicer.vtkMRMLScalarVolumeNode()
        else:
            exportVolume = slicer.vtkMRMLVectorVolumeNode()
        exportVolume.SetAndObserveImageData(exportImageData)
        exportVolume.SetIJKToRASDirections(roiToRas.GetElement(0, 0),
                                           roiToRas.GetElement(0, 1),
                                           roiToRas.GetElement(0, 2),
                                           roiToRas.GetElement(1, 0),
                                           roiToRas.GetElement(1, 1),
                                           roiToRas.GetElement(1, 2),
                                           roiToRas.GetElement(2, 0),
                                           roiToRas.GetElement(2, 1),
                                           roiToRas.GetElement(2, 2))
        exportVolume.SetSpacing(spacingMm, spacingMm, spacingMm)
        roiOrigin_Ras = roiToRas.MultiplyPoint(roiOrigin_Roi)
        exportVolume.SetOrigin(roiOrigin_Ras[0:3])

        return exportVolume
Пример #2
0
  def resampleVectorVolume(self,vectorVolume,resample):
      if not vectorVolume or not vectorVolume.IsA('vtkMRMLVectorVolumeNode'):
        print "No vector volume for resampling."
        return
      
      if resample == []:
	print "No resample values."
	return
	
      if not len(resample) == 3:
        print "Too many values for resampling."
        return
      
      oldVectorVolume = vectorVolume
      
      #Create new vector volume
      newVectorVolume = slicer.vtkMRMLVectorVolumeNode()
      newVectorVolume.SetName(oldVectorVolume.GetName())
      slicer.mrmlScene.AddNode(newVectorVolume)
      
      newStorageNode = newVectorVolume.CreateDefaultStorageNode()
      newVectorVolume.SetAndObserveStorageNodeID(newStorageNode.GetID())
      
      #Create strings for resampling
      spacing = ''
      size = ''
      for i in range(0,len(resample)):
        spacing += str(oldVectorVolume.GetSpacing()[i]*resample[i])
        #extent = oldVectorVolume.GetImageData().GetExtent[2*i+1]
        extent = oldVectorVolume.GetImageData().GetExtent()[2*i+1]+1
        size += str(extent/resample[i])
        if i < 2:
	  spacing += ','
	  size += ','

      print "Resampling " + oldVectorVolume.GetName() + " to new pixel size " + size 
      
      #Set parameters
      parameters = {} 
      parameters["inputVolume"] = oldVectorVolume.GetID()
      parameters["outputVolume"] = newVectorVolume.GetID()
      parameters["referenceVolume"] = ''
      parameters["outputImageSpacing"] = spacing
      parameters["outputImageSize"] = size
      
      #Do resampling
      resampleScalarVolume = slicer.modules.resamplescalarvectordwivolume
      clNode = slicer.cli.run(resampleScalarVolume, None, parameters, wait_for_completion=True)
      
      #Remove old vector node and set new:
      return newVectorVolume
    def resampleVectorVolume(self):
        if not self.vectorVolume or not self.vectorVolume.IsA('vtkMRMLVectorVolumeNode'):
            print "No vector volume for resampling."
            return

        if self.resample == []:
            print "No resample values."
            return

        if not len(self.resample) == 3:
            print "Too many values for resampling."
            return

        oldVectorVolume = self.vectorVolume

        #Create new vector volume
        newVectorVolume = slicer.vtkMRMLVectorVolumeNode()
        newVectorVolume.SetName(oldVectorVolume.GetName())
        slicer.mrmlScene.AddNode(newVectorVolume)

        #Create strings for resampling
        spacing = ''
        size = ''
        for i in range(0, len(self.resample)):
            spacing += str(oldVectorVolume.GetSpacing()[i] * self.resample[i])
            #extent = oldVectorVolume.GetImageData().GetExtent[2*i+1]
            extent = oldVectorVolume.GetImageData().GetExtent()[2 * i + 1] + 1
            size += str(extent / self.resample[i])
            if i < 2:
                spacing += ','
                size += ','

        print "Resampling " + oldVectorVolume.GetName() + " to new pixel size " + size

        #Set parameters
        parameters = {}
        parameters["inputVolume"] = oldVectorVolume.GetID()
        parameters["outputVolume"] = newVectorVolume.GetID()
        parameters["referenceVolume"] = ''
        parameters["outputImageSpacing"] = spacing
        parameters["outputImageSize"] = size

        #Do resampling
        resampleScalarVolume = slicer.modules.resamplescalarvectordwivolume
        clNode = slicer.cli.run(resampleScalarVolume, None, parameters, wait_for_completion=True)

        #Remove old vector node and set new:
        self.vectorVolume = newVectorVolume
        slicer.mrmlScene.RemoveNode(oldVectorVolume)
  def resampleVolume(self, inputVolume, referenceVolume):
    parameters = {}
    parameters["inputVolume"] = inputVolume.GetID()
    parameters["referenceVolume"] = referenceVolume.GetID()
    outputVolume = slicer.vtkMRMLVectorVolumeNode()
    outputVolume.SetName('ResampledVolume')
    slicer.mrmlScene.AddNode( outputVolume )
    parameters["outputVolume"] = outputVolume.GetID()
#   Instead of
#    slicer.cli.run(slicer.modules.resamplescalarvectordwivolume, None, parameters, wait_for_completion=True)
#   apply using custom code to allow disabling DisplayData in ApplyAndWait
    module = slicer.modules.resamplescalarvectordwivolume
    node = slicer.cli.createNode(module, parameters)
    logic = module.logic()
    logic.ApplyAndWait(node, False)

    return outputVolume
    def resampleVolume(self, inputVolume, referenceVolume):
        parameters = {}
        parameters["inputVolume"] = inputVolume.GetID()
        parameters["referenceVolume"] = referenceVolume.GetID()
        outputVolume = slicer.vtkMRMLVectorVolumeNode()
        outputVolume.SetName('ResampledVolume')
        slicer.mrmlScene.AddNode(outputVolume)
        parameters["outputVolume"] = outputVolume.GetID()
        #   Instead of
        #    slicer.cli.run(slicer.modules.resamplescalarvectordwivolume, None, parameters, wait_for_completion=True)
        #   apply using custom code to allow disabling DisplayData in ApplyAndWait
        module = slicer.modules.resamplescalarvectordwivolume
        node = slicer.cli.createNode(module, parameters)
        logic = module.logic()
        logic.ApplyAndWait(node, False)

        return outputVolume
  def createVectorVolumeFromRoi(self, exportRoi, spacingMm, numberOfComponents=3):
    roiCenter = [0, 0, 0]
    exportRoi.GetXYZ( roiCenter )
    roiRadius = [0, 0, 0]
    exportRoi.GetRadiusXYZ( roiRadius )
    roiOrigin_Roi = [roiCenter[0] - roiRadius[0], roiCenter[1] - roiRadius[1], roiCenter[2] - roiRadius[2], 1 ]

    roiToRas = vtk.vtkMatrix4x4()
    if exportRoi.GetTransformNodeID() != None:
      roiBoxTransformNode = slicer.mrmlScene.GetNodeByID(exportRoi.GetTransformNodeID())
      roiBoxTransformNode.GetMatrixTransformToWorld(roiToRas)

    exportVolumeSize = [roiRadius[0]*2/spacingMm, roiRadius[1]*2/spacingMm, roiRadius[2]*2/spacingMm]
    exportVolumeSize = [int(math.ceil(x)) for x in exportVolumeSize]

    exportImageData = vtk.vtkImageData()
    exportImageData.SetExtent(0, exportVolumeSize[0]-1, 0, exportVolumeSize[1]-1, 0, exportVolumeSize[2]-1)
    if vtk.VTK_MAJOR_VERSION <= 5:
      exportImageData.SetScalarType(vtk.VTK_DOUBLE)
      exportImageData.SetNumberOfScalarComponents(numberOfComponents)
      exportImageData.AllocateScalars()
    else:
      exportImageData.AllocateScalars(vtk.VTK_DOUBLE, numberOfComponents)

    exportVolume = None
    if numberOfComponents==1:
      exportVolume = slicer.vtkMRMLScalarVolumeNode()
    else:
      exportVolume = slicer.vtkMRMLVectorVolumeNode()
    exportVolume.SetAndObserveImageData(exportImageData)
    exportVolume.SetIJKToRASDirections( roiToRas.GetElement(0,0), roiToRas.GetElement(0,1), roiToRas.GetElement(0,2), roiToRas.GetElement(1,0), roiToRas.GetElement(1,1), roiToRas.GetElement(1,2), roiToRas.GetElement(2,0), roiToRas.GetElement(2,1), roiToRas.GetElement(2,2))
    exportVolume.SetSpacing(spacingMm, spacingMm, spacingMm)
    roiOrigin_Ras = roiToRas.MultiplyPoint(roiOrigin_Roi)
    exportVolume.SetOrigin(roiOrigin_Ras[0:3])

    return exportVolume
  def exportTransformToVectorVolume(self, positionErrorVectorTransform, exportRoi, magnitudeOnly):
    if not positionErrorVectorTransform:
      return

    roiBounds_Ras = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
    exportRoi.GetRASBounds(roiBounds_Ras)
    exportVolumeSize = [(roiBounds_Ras[1]-roiBounds_Ras[0]+1)/self.exportVolumeSpacingMm, (roiBounds_Ras[3]-roiBounds_Ras[2]+1)/self.exportVolumeSpacingMm, (roiBounds_Ras[5]-roiBounds_Ras[4]+1)/self.exportVolumeSpacingMm]
    exportVolumeSize = [int(math.ceil(x)) for x in exportVolumeSize]

    exportImageData = vtk.vtkImageData()
    exportImageData.SetExtent(0, exportVolumeSize[0]-1, 0, exportVolumeSize[1]-1, 0, exportVolumeSize[2]-1)
    if vtk.VTK_MAJOR_VERSION <= 5:
      exportImageData.SetScalarType(vtk.VTK_DOUBLE)
      exportImageData.SetNumberOfScalarComponents(1)
      exportImageData.AllocateScalars()
    else:
      exportImageData.AllocateScalars(vtk.VTK_DOUBLE, 1)

    exportVolume = slicer.vtkMRMLVectorVolumeNode()
    exportVolume.SetAndObserveImageData(exportImageData)
    exportVolume.SetSpacing(self.exportVolumeSpacingMm, self.exportVolumeSpacingMm, self.exportVolumeSpacingMm)
    exportVolume.SetOrigin(roiBounds_Ras[0], roiBounds_Ras[2], roiBounds_Ras[4])

    slicer.modules.transforms.logic().CreateDisplacementVolumeFromTransform(positionErrorVectorTransform, exportVolume, magnitudeOnly)
  def exportTransformToVectorVolume(self, positionErrorVectorTransform, exportRoi, magnitudeOnly):
    if not positionErrorVectorTransform:
      return

    roiBounds_Ras = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
    exportRoi.GetRASBounds(roiBounds_Ras)
    exportVolumeSize = [(roiBounds_Ras[1]-roiBounds_Ras[0]+1)/self.exportVolumeSpacingMm, (roiBounds_Ras[3]-roiBounds_Ras[2]+1)/self.exportVolumeSpacingMm, (roiBounds_Ras[5]-roiBounds_Ras[4]+1)/self.exportVolumeSpacingMm]
    exportVolumeSize = [int(math.ceil(x)) for x in exportVolumeSize]

    exportImageData = vtk.vtkImageData()
    exportImageData.SetExtent(0, exportVolumeSize[0]-1, 0, exportVolumeSize[1]-1, 0, exportVolumeSize[2]-1)
    if vtk.VTK_MAJOR_VERSION <= 5:
      exportImageData.SetScalarType(vtk.VTK_DOUBLE)
      exportImageData.SetNumberOfScalarComponents(1)
      exportImageData.AllocateScalars()
    else:
      exportImageData.AllocateScalars(vtk.VTK_DOUBLE, 1)

    exportVolume = slicer.vtkMRMLVectorVolumeNode()
    exportVolume.SetAndObserveImageData(exportImageData)
    exportVolume.SetSpacing(self.exportVolumeSpacingMm, self.exportVolumeSpacingMm, self.exportVolumeSpacingMm)
    exportVolume.SetOrigin(roiBounds_Ras[0], roiBounds_Ras[2], roiBounds_Ras[4])

    slicer.modules.transforms.logic().CreateDisplacementVolumeFromTransform(positionErrorVectorTransform, exportVolume, magnitudeOnly)
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)
Пример #11
0
  def writeTRiPdata(self, filePath, pytripCube=None, extension='.ctx', nodeID = None, binfoName='',aix = False, resample = []):
    
    if nodeID is not None:
      node = slicer.util.getNode( nodeID )
      print "Node to write:" + node.GetID()
    else:
      node = None
      
    if pytripCube is None and node is not None:
      
      print "Converting slicer node into pytrip cube " + str(node.GetID())
      #Getting vector field from transform node
      if node.IsA('vtkMRMLGridTransformNode') or node.IsA('vtkMRMLBSplineTransformNode'):
	print "Converting Transform Node to Vector Field"
	trans = node.GetTransformFromParent()#.GetConcatenatedTransform(0)
	#trans.Inverse()
	#trans.Update()
	im = trans.GetDisplacementGrid()
	if im is None:
	  print "Can't get image data. " + str(im)
	  return
	  
	vectorVolume = slicer.vtkMRMLVectorVolumeNode()
	slicer.mrmlScene.AddNode( vectorVolume )
	vectorVolume.SetAndObserveImageData( im )
	vectorVolume.SetName( node.GetName() )
	vectorVolume.SetSpacing( im.GetSpacing() )
	
	#vectorVolume.SetOrigin( im.GetOrigin() )
	
	#Get Right Direction For Vector Volume
	#matrix = vtk.vtkMatrix4x4()
	matrix = trans.GetGridDirectionMatrix()
        #matrix.DeepCopy((-1,0,0,0,0,-1,0,0,0,0,1,0,0,0,0,1))
        vectorVolume.SetIJKToRASDirectionMatrix(matrix)
        

        
        if not resample == []:
	  newVectorVolume = self.resampleVectorVolume(vectorVolume,resample)
	  slicer.mrmlScene.RemoveNode(vectorVolume)
	  vectorVolume = newVectorVolume
        
	node = vectorVolume

      pytripCube = self.getPyTRiPCubeFromNode(node)

      if aix:
	pytripCube.byte_order = 'aix'
	pytripCube.cube.byteswap()
      else:
	pytripCube.byte_order = 'vms'

    if pytripCube is None:
      if node is None:
        print "Input slicer node or pytrip Cube!"
        return
      else:
	print "Cannot create/find pytripCube"
	return

    if not filePath[-1] == '/':
      filePath += '/'
    fName = str(filePath)+binfoName+ pytripCube.patient_name
    if node is not None:
      if node.IsA('vtkMRMLVectorVolumeNode'):
        if not extension == '.cbt':
	  print "Error, vector volume can be exported only as .cbt (no: "+extension+" )"
	  return
        array = slicer.util.array(node.GetID())
        
        #Change precision from double to float
        if array.dtype == np.float64:
	  array = array.astype(np.float32)

        if pytripCube.byte_order == 'aix':
	  print "Changing array to aix byte order."
	  array.byteswap()
	pName = pytripCube.patient_name
        for i in range(0,3):
	  # Vector field components in cbt are divided with voxel spacing due to historical reasons.
	  if i == 2:
	      pytripCube.cube = np.array(array[:,:,:,i])/pytripCube.slice_distance
	  else:
	    if nodeID.find('GridTransform') > -1:
	      print "Changing sign"
	      pytripCube.cube = -np.array(array[:,:,:,i])/pytripCube.pixel_size
	    else:
	      pytripCube.cube = np.array(array[:,:,:,i])/pytripCube.pixel_size
	    
	  #if i == 2:
	    #print "Converting vector components."
	    #pytripCube.cube = np.array(array[:,:,:,i]/pytripCube.slice_distance
	  #elif i < 2:
	    #pytripCube.cube = np.array(array[:,:,:,i]/pytripCube.pixel_size
	  #pytripCube.cube = array
	  if i==0:
	    fNameNew = fName + "_x"
	    pytripCube.patient_name = pName + "_x"
	  elif i==1:
	    fNameNew = fName + "_y"
	    pytripCube.patient_name = pName + "_y"
	  elif i==2:
	    fNameNew = fName + "_z"
	    pytripCube.patient_name = pName + "_z"
	  print("Saving: "+fNameNew)
	  pytripCube.write_trip_data(fNameNew+extension)
          pytripCube.write_trip_header(fNameNew+".hed")
        if nodeID.find('GridTransform') > -1:
          slicer.mrmlScene.RemoveNode(vectorVolume)
      elif node.IsA('vtkMRMLScalarVolumeNode'):
	pytripCube.write_trip_data(fName+extension)
        pytripCube.write_trip_header(fName+".hed")
    else:
      if extension == '.cbt':
	print "Error, input is not vector volume for exporting cbt."
	return
      pytripCube.write_trip_data(fName+extension)
      pytripCube.write_trip_header(fName+".hed")
      
    print("Saved: "+fName+extension)