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 initializeNewLabel(newLabel, sourceVolume):    
    displayNode = slicer.mrmlScene.AddNode(slicer.vtkMRMLLabelMapVolumeDisplayNode())

    threshold = vtk.vtkImageThreshold()
    threshold.ReplaceInOn()
    threshold.ReplaceOutOn()
    threshold.SetInValue(0)
    threshold.SetOutValue(0)
    threshold.SetOutputScalarTypeToUnsignedShort()
    threshold.SetInput(sourceVolume.GetImageData())
    threshold.Update()

    labelImage = vtk.vtkImageData()
    labelImage.DeepCopy(threshold.GetOutput())
    
    newLabel.SetAndObserveStorageNodeID(None)
    newLabel.SetLabelMap(1)
    newLabel.CopyOrientation(sourceVolume)
    ras2ijk = vtk.vtkMatrix4x4()
    sourceVolume.GetRASToIJKMatrix(ras2ijk)
    newLabel.SetRASToIJKMatrix(ras2ijk)

    newLabel.SetAttribute('ReportingReportNodeID', sourceVolume.GetAttribute('ReportingReportNodeID'))
    newLabel.SetAttribute('AssociatedNodeID', sourceVolume.GetID())
    
    newLabel.SetAndObserveDisplayNodeID(displayNode.GetID())
    newLabel.SetAndObserveImageData(labelImage)
Exemplo n.º 3
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 initializeNewLabel(newLabel, sourceVolume):
        displayNode = slicer.mrmlScene.AddNode(
            slicer.vtkMRMLLabelMapVolumeDisplayNode())

        threshold = vtk.vtkImageThreshold()
        threshold.ReplaceInOn()
        threshold.ReplaceOutOn()
        threshold.SetInValue(0)
        threshold.SetOutValue(0)
        threshold.SetOutputScalarTypeToUnsignedShort()
        threshold.SetInput(sourceVolume.GetImageData())
        threshold.Update()

        labelImage = vtk.vtkImageData()
        labelImage.DeepCopy(threshold.GetOutput())

        newLabel.SetAndObserveStorageNodeID(None)
        newLabel.SetLabelMap(1)
        newLabel.CopyOrientation(sourceVolume)
        ras2ijk = vtk.vtkMatrix4x4()
        sourceVolume.GetRASToIJKMatrix(ras2ijk)
        newLabel.SetRASToIJKMatrix(ras2ijk)

        newLabel.SetAttribute('AssociatedNodeID', sourceVolume.GetID())

        newLabel.SetAndObserveDisplayNodeID(displayNode.GetID())
        newLabel.SetAndObserveImageData(labelImage)
Exemplo n.º 5
0
 def renderLabelMap(self):
   # Initializes a vtkMRMLScalarVolumeNode for the SegmentCAD Output and copies ijkToRAS matrix and Image data from nodeLabel
   ijkToRASMatrix = vtk.vtkMatrix4x4()
   self.volumePre.GetIJKToRASMatrix(ijkToRASMatrix)
   self.SegmentCADLabelMap.SetIJKToRASMatrix(ijkToRASMatrix)
   SegmentCADLabelMapImageData = vtk.vtkImageData()
   SegmentCADLabelMapImageData.DeepCopy(self.volumePre.GetImageData())
   SegmentCADLabelMapPointData = SegmentCADLabelMapImageData.GetPointData()
   # Numpy array is converted from signed int16 to signed vtkShortArray
   scalarArray = vtk.vtkShortArray()
   dims1D = SegmentCADLabelMapPointData.GetScalars().GetSize()
   self.nodeArraySegmentCADLabel = self.nodeArraySegmentCADLabel.reshape(dims1D, order='C')
   scalarArray = vtk.util.numpy_support.numpy_to_vtk(self.nodeArraySegmentCADLabel)
   # PointData() of SegmentCAD label output pointed to new vtkShortArray for scalar values
   SegmentCADLabelMapImageData.SetScalarTypeToShort()
   SegmentCADLabelMapPointData.SetScalars(scalarArray)
   SegmentCADLabelMapPointData.Update()
   SegmentCADLabelMapImageData.Update()
   self.SegmentCADLabelMap.SetAndObserveImageData(SegmentCADLabelMapImageData)
   # Corresponding display node and color table nodes created for SegmentCAD label Output
   self.SegmentCADLabelMapDisplay = slicer.vtkMRMLLabelMapVolumeDisplayNode()
   self.SegmentCADLabelMapDisplay.SetScene(slicer.mrmlScene)
   self.SegmentCADLabelMapDisplay.SetAndObserveColorNodeID('vtkMRMLColorTableNodeFileGenericColors.txt')
   self.SegmentCADLabelMapDisplay.SetInputImageData(SegmentCADLabelMapImageData)
   self.SegmentCADLabelMapDisplay.UpdateImageDataPipeline()
   
   slicer.mrmlScene.AddNode(self.SegmentCADLabelMapDisplay)
   self.SegmentCADLabelMap.SetAndObserveDisplayNodeID(self.SegmentCADLabelMapDisplay.GetID())
   self.SegmentCADLabelMapDisplay.UpdateScene(slicer.mrmlScene)
Exemplo n.º 6
0
 def renderLabelMap(self):
   # Initializes a vtkMRMLScalarVolumeNode for the SegmentCAD Output and copies ijkToRAS matrix and Image data from nodeLabel
   ras2ijk = vtk.vtkMatrix4x4()
   ijk2ras = vtk.vtkMatrix4x4()
   self.nodePre.GetRASToIJKMatrix(ras2ijk)
   self.nodePre.GetIJKToRASMatrix(ijk2ras)
   self.SegmentCADLabelMap.SetRASToIJKMatrix(ras2ijk)
   self.SegmentCADLabelMap.SetIJKToRASMatrix(ijk2ras)
   SegmentCADLabelMapImageData = vtk.vtkImageData()
   SegmentCADLabelMapImageData.DeepCopy(self.nodePre.GetImageData())
   SegmentCADLabelMapPointData = SegmentCADLabelMapImageData.GetPointData()
   # Numpy array is converted from signed int16 to signed vtkShortArray
   scalarArray = vtk.vtkShortArray()
   dims1D = SegmentCADLabelMapPointData.GetScalars().GetSize()
   self.nodeArraySegmentCADLabel = self.nodeArraySegmentCADLabel.reshape(dims1D, order='C') #use a flattening function
   scalarArray = vtk.util.numpy_support.numpy_to_vtk(self.nodeArraySegmentCADLabel)
   # PointData() of SegmentCAD label output pointed to new vtkShortArray for scalar values
   
   if vtk.VTK_MAJOR_VERSION <= 5:
     #SegmentCADLabelMapImageData.SetScalarTypeToShort()
     SegmentCADLabelMapPointData.SetScalars(scalarArray)
     SegmentCADLabelMapPointData.Update()
   else:
     #SegmentCADLabelMapImageData.SetScalarType(4)
     SegmentCADLabelMapPointData.SetScalars(scalarArray)
     SegmentCADLabelMapImageData.Modified()
   
   self.SegmentCADLabelMap.SetAndObserveImageData(SegmentCADLabelMapImageData)
   # Corresponding display node and color table nodes created for SegmentCAD label Output
   self.SegmentCADLabelMapDisplay = slicer.vtkMRMLLabelMapVolumeDisplayNode()
   self.SegmentCADLabelMapDisplay.SetScene(slicer.mrmlScene)
   self.SegmentCADLabelMapDisplay.SetAndObserveColorNodeID('vtkMRMLColorTableNodeFileGenericColors.txt')
   
   if vtk.VTK_MAJOR_VERSION <= 5:
     self.SegmentCADLabelMapDisplay.SetInputImageData(self.SegmentCADLabelMap.GetImageData())
   else:
     self.SegmentCADLabelMapDisplay.SetInputImageDataConnection(self.SegmentCADLabelMap.GetImageDataConnection())
   self.SegmentCADLabelMapDisplay.UpdateImageDataPipeline()
   
   slicer.mrmlScene.AddNode(self.SegmentCADLabelMapDisplay)
   self.SegmentCADLabelMap.SetAndObserveDisplayNodeID(self.SegmentCADLabelMapDisplay.GetID())
   self.SegmentCADLabelMapDisplay.UpdateScene(slicer.mrmlScene)
   
   #red_logic = slicer.app.layoutManager().sliceWidget("Red").sliceLogic()
   #red_logic.GetSliceCompositeNode().SetLabelVolumeID(self.SegmentCADLabelMap.GetID())  
   #yellow_logic = slicer.app.layoutManager().sliceWidget("Yellow").sliceLogic()
   #yellow_logic.GetSliceCompositeNode().SetLabelVolumeID(self.SegmentCADLabelMap.GetID())
   #green_logic = slicer.app.layoutManager().sliceWidget("Green").sliceLogic()
   #green_logic.GetSliceCompositeNode().SetLabelVolumeID(self.SegmentCADLabelMap.GetID())
   
   appLogic = slicer.app.applicationLogic()
   selectionNode = appLogic.GetSelectionNode()
   #selectionNode.SetReferenceActiveVolumeID(self.nodePre.GetID())
   selectionNode.SetReferenceActiveLabelVolumeID(self.SegmentCADLabelMap.GetID())  
   #selectionNode.SetReferenceSecondaryVolumeID(self.node1.GetID())
   appLogic.PropagateVolumeSelection()
Exemplo n.º 7
0
 def loadData(self):
     """ Load some default data for development and set up a viewing scenario for it.
     """
     self.logging.debug("call")
     dataDialog = qt.QPushButton();
     dataDialog.setText('Loading files for session %s...' % self.currentSession);
     dataDialog.show()
     volumeLogic = slicer.modules.volumes.logic()
     t1NodeName = '%s_t1_average' % self.currentSession
     t1VolumeNode = slicer.util.getNode(t1NodeName)
     if t1VolumeNode is None:
         self.logging.debug("%s = %s", 't1_average', self.sessionFiles['t1_average'])
         try:
             volumeLogic.AddArchetypeScalarVolume(self.sessionFiles['t1_average'], t1NodeName, 0, None)
         except TypeError:
             volumeLogic.AddArchetypeScalarVolume(self.sessionFiles['t1_average'], t1NodeName, 0)
         if slicer.util.getNode(t1NodeName) is None:
             self.logging.error("Could not load session file for T1: %s", self.sessionFiles['t1_average'])
         t1VolumeNode = slicer.util.getNode(t1NodeName)
         t1VolumeNode.CreateDefaultDisplayNodes()
         t1VolumeNode.GetDisplayNode().AutoWindowLevelOn()
     t2NodeName = '%s_t2_average' % self.currentSession
     t2VolumeNode = slicer.util.getNode(t2NodeName)
     if t2VolumeNode is None:
         self.logging.debug("%s = %s", 't2_average', self.sessionFiles['t2_average'])
         try:
             volumeLogic.AddArchetypeScalarVolume(self.sessionFiles['t2_average'], t2NodeName, 0, None)
         except TypeError:
             volumeLogic.AddArchetypeScalarVolume(self.sessionFiles['t2_average'], t2NodeName, 0)
         if slicer.util.getNode(t2NodeName) is None:
             self.logging.error("Could not load session file for T2: %s", self.sessionFiles['t2_average'])
         t2VolumeNode = slicer.util.getNode(t2NodeName)
         t2VolumeNode.CreateDefaultDisplayNodes()
         t2VolumeNode.GetDisplayNode().AutoWindowLevelOn()
     for region in self.regions:
         regionNodeName = '%s_%s' % (self.currentSession, region)
         regionNode = slicer.util.getNode(regionNodeName)
         if regionNode is None:
             self.logging.debug("%s = %s", region, self.sessionFiles[region])
             try:
                 volumeLogic.AddArchetypeScalarVolume(self.sessionFiles[region], regionNodeName, 1, None)
             except TypeError:
                 volumeLogic.AddArchetypeScalarVolume(self.sessionFiles[region], regionNodeName, 1)
             if slicer.util.getNode(regionNodeName) is None:
                 self.logging.error("Could not load session file for region %s! File: %s", region, self.sessionFiles[region])
             regionNode = slicer.util.getNode(regionNodeName)
             displayNode = slicer.vtkMRMLLabelMapVolumeDisplayNode()
             slicer.mrmlScene.AddNode(displayNode)
             regionNode.SetAndObserveNthDisplayNodeID(0, displayNode.GetID())
     dataDialog.close()
Exemplo n.º 8
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()
Exemplo n.º 10
0
    def renderLabelMap(self):
        # Initializes a vtkMRMLScalarVolumeNode for the SegmentCAD Output and copies ijkToRAS matrix and Image data from nodeLabel
        ras2ijk = vtk.vtkMatrix4x4()
        ijk2ras = vtk.vtkMatrix4x4()
        self.nodePre.GetRASToIJKMatrix(ras2ijk)
        self.nodePre.GetIJKToRASMatrix(ijk2ras)
        self.SegmentCADLabelMap.SetRASToIJKMatrix(ras2ijk)
        self.SegmentCADLabelMap.SetIJKToRASMatrix(ijk2ras)
        SegmentCADLabelMapImageData = vtk.vtkImageData()
        SegmentCADLabelMapImageData.DeepCopy(self.nodePre.GetImageData())
        SegmentCADLabelMapPointData = SegmentCADLabelMapImageData.GetPointData(
        )
        # Numpy array is converted from signed int16 to signed vtkShortArray
        scalarArray = vtk.vtkShortArray()
        dims1D = SegmentCADLabelMapPointData.GetScalars().GetSize()
        self.nodeArraySegmentCADLabel = self.nodeArraySegmentCADLabel.reshape(
            dims1D, order='C')  #use a flattening function
        scalarArray = vtk.util.numpy_support.numpy_to_vtk(
            self.nodeArraySegmentCADLabel)
        # PointData() of SegmentCAD label output pointed to new vtkShortArray for scalar values

        if vtk.VTK_MAJOR_VERSION <= 5:
            #SegmentCADLabelMapImageData.SetScalarTypeToShort()
            SegmentCADLabelMapPointData.SetScalars(scalarArray)
            SegmentCADLabelMapPointData.Update()
        else:
            #SegmentCADLabelMapImageData.SetScalarType(4)
            SegmentCADLabelMapPointData.SetScalars(scalarArray)
            SegmentCADLabelMapImageData.Modified()

        self.SegmentCADLabelMap.SetAndObserveImageData(
            SegmentCADLabelMapImageData)
        # Corresponding display node and color table nodes created for SegmentCAD label Output
        self.SegmentCADLabelMapDisplay = slicer.vtkMRMLLabelMapVolumeDisplayNode(
        )
        self.SegmentCADLabelMapDisplay.SetScene(slicer.mrmlScene)
        self.SegmentCADLabelMapDisplay.SetAndObserveColorNodeID(
            'vtkMRMLColorTableNodeFileGenericColors.txt')

        if vtk.VTK_MAJOR_VERSION <= 5:
            self.SegmentCADLabelMapDisplay.SetInputImageData(
                self.SegmentCADLabelMap.GetImageData())
        else:
            self.SegmentCADLabelMapDisplay.SetInputImageDataConnection(
                self.SegmentCADLabelMap.GetImageDataConnection())
        self.SegmentCADLabelMapDisplay.UpdateImageDataPipeline()

        slicer.mrmlScene.AddNode(self.SegmentCADLabelMapDisplay)
        self.SegmentCADLabelMap.SetAndObserveDisplayNodeID(
            self.SegmentCADLabelMapDisplay.GetID())
        self.SegmentCADLabelMapDisplay.UpdateScene(slicer.mrmlScene)

        #red_logic = slicer.app.layoutManager().sliceWidget("Red").sliceLogic()
        #red_logic.GetSliceCompositeNode().SetLabelVolumeID(self.SegmentCADLabelMap.GetID())
        #yellow_logic = slicer.app.layoutManager().sliceWidget("Yellow").sliceLogic()
        #yellow_logic.GetSliceCompositeNode().SetLabelVolumeID(self.SegmentCADLabelMap.GetID())
        #green_logic = slicer.app.layoutManager().sliceWidget("Green").sliceLogic()
        #green_logic.GetSliceCompositeNode().SetLabelVolumeID(self.SegmentCADLabelMap.GetID())

        appLogic = slicer.app.applicationLogic()
        selectionNode = appLogic.GetSelectionNode()
        #selectionNode.SetReferenceActiveVolumeID(self.nodePre.GetID())
        selectionNode.SetReferenceActiveLabelVolumeID(
            self.SegmentCADLabelMap.GetID())
        #selectionNode.SetReferenceSecondaryVolumeID(self.node1.GetID())
        appLogic.PropagateVolumeSelection()
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)
    def onComputeBox(self):
        numNodes = slicer.mrmlScene.GetNumberOfNodesByClass("vtkMRMLModelNode")
        bound = [MAXINT, -MAXINT, MAXINT, -MAXINT, MAXINT, -MAXINT]
        for i in range (3,numNodes):
            self.elements = slicer.mrmlScene.GetNthNodeByClass(i,"vtkMRMLModelNode" )
            node = slicer.util.getNode(self.elements.GetName())
            polydata = node.GetPolyData()
            tempbound = polydata.GetBounds()
            bound[0] = min(bound[0], tempbound[0])
            bound[2] = min(bound[2], tempbound[2])
            bound[4] = min(bound[4], tempbound[4])

            bound[1] = max(bound[1], tempbound[1])
            bound[3] = max(bound[3], tempbound[3])
            bound[5] = max(bound[5], tempbound[5])

        #--------------------------- Box around the model --------------------------#
        
        # print "bound", bound
        
        dimX = bound[1]-bound[0]
        dimY = bound[3]-bound[2]
        dimZ = bound[5]-bound[4]
        
        # print "dimension X :", dimX
        # print "dimension Y :", dimY
        # print "dimension Z :", dimZ
        
        dimX = dimX + 10
        dimY = dimY + 10
        dimZ = dimZ + 10

        sampleVolumeNode = slicer.vtkMRMLScalarVolumeNode()
        sampleVolumeNode = slicer.mrmlScene.AddNode(sampleVolumeNode)
        imageData = vtk.vtkImageData()

        # Do NOT set the spacing and the origin of imageData (vtkImageData)
        # The spacing and the origin should only be set in the vtkMRMLScalarVolumeNode!!!!!!
        imageData.SetDimensions(int(dimX), int(dimY), int(dimZ))
        imageData.AllocateScalars(vtk.VTK_UNSIGNED_CHAR, 1)
        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):
                        imageData.SetScalarComponentFromDouble(x,y,z,0,0)

        sampleVolumeNode.SetSpacing(1, 1, 1)
        sampleVolumeNode.SetOrigin(bound[0], bound[2], bound[4])

        sampleVolumeNode.SetName("Empty_volume")
        sampleVolumeNode.SetAndObserveImageData(imageData)

        sampleVolumeNode.SetLabelMap(1)
        labelmapVolumeDisplayNode = slicer.vtkMRMLLabelMapVolumeDisplayNode()
        slicer.mrmlScene.AddNode(labelmapVolumeDisplayNode)
        colorNode = slicer.util.getNode('GenericAnatomyColors')
        labelmapVolumeDisplayNode.SetAndObserveColorNodeID(colorNode.GetID())
        labelmapVolumeDisplayNode.VisibilityOn()
        sampleVolumeNode.SetAndObserveDisplayNodeID(labelmapVolumeDisplayNode.GetID())

        count = slicer.mrmlScene.GetNumberOfNodesByClass('vtkMRMLSliceCompositeNode')
        for n in xrange(count):
          compNode = slicer.mrmlScene.GetNthNodeByClass(n, 'vtkMRMLSliceCompositeNode')
          compNode.SetBackgroundVolumeID(sampleVolumeNode.GetID())
def DoIt(inputDir, labelFile, outputDir, forceLabel):

  dbDir1 = slicer.app.temporaryPath+'/LabelConverter'
  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]

  try:
    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!'
      exit()
  
    inputVolume = scalarVolumePlugin.load(loadables[0])
    slicer.mrmlScene.AddNode(inputVolume)
    print('Input volume loaded!')

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

    if forceLabel>0:
      print('Forcing label to '+str(forceLabel))
      labelImage = labelVolume.GetImageData()
      thresh = vtk.vtkImageThreshold()
      thresh.SetInput(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)
    
    # resample label to the input volume raster
    resampledLabel = slicer.vtkMRMLScalarVolumeNode()
    slicer.mrmlScene.AddNode(resampledLabel)
    eye = slicer.vtkMRMLLinearTransformNode()
    slicer.mrmlScene.AddNode(eye)
    parameters = {}
    parameters['inputVolume'] = labelVolume.GetID()
    parameters['referenceVolume'] = inputVolume.GetID()
    parameters['outputVolume'] = resampledLabel.GetID()
    parameters['warpTransform'] = eye.GetID()
    parameters['interpolationMode'] = 'NearestNeighbor'
    parameters['pixelType'] = 'ushort'
    cliNode = None
    cliNode = slicer.cli.run(slicer.modules.brainsresample, None, parameters, 1)
    labelVolume = resampledLabel

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

    labelVolume.SetAttribute('AssociatedNodeID',inputVolume.GetID())
    labelVolume.LabelMapOn()
    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)
  except:
    print('Error occurred!')

  dicomWidget.onDatabaseDirectoryChanged(dbDir0)

  exit()
Exemplo n.º 15
0
    def onComputeBox(self):
        numNodes = slicer.mrmlScene.GetNumberOfNodesByClass("vtkMRMLModelNode")
        bound = [MAXINT, -MAXINT, MAXINT, -MAXINT, MAXINT, -MAXINT]
        for i in range(3, numNodes):
            self.elements = slicer.mrmlScene.GetNthNodeByClass(
                i, "vtkMRMLModelNode")
            node = slicer.util.getNode(self.elements.GetName())
            polydata = node.GetPolyData()
            tempbound = polydata.GetBounds()
            bound[0] = min(bound[0], tempbound[0])
            bound[2] = min(bound[2], tempbound[2])
            bound[4] = min(bound[4], tempbound[4])

            bound[1] = max(bound[1], tempbound[1])
            bound[3] = max(bound[3], tempbound[3])
            bound[5] = max(bound[5], tempbound[5])

        #--------------------------- Box around the model --------------------------#

        # print "bound", bound

        dimX = bound[1] - bound[0]
        dimY = bound[3] - bound[2]
        dimZ = bound[5] - bound[4]

        # print "dimension X :", dimX
        # print "dimension Y :", dimY
        # print "dimension Z :", dimZ

        dimX = dimX + 10
        dimY = dimY + 10
        dimZ = dimZ + 10

        sampleVolumeNode = slicer.vtkMRMLScalarVolumeNode()
        sampleVolumeNode = slicer.mrmlScene.AddNode(sampleVolumeNode)
        imageData = vtk.vtkImageData()

        # Do NOT set the spacing and the origin of imageData (vtkImageData)
        # The spacing and the origin should only be set in the vtkMRMLScalarVolumeNode!!!!!!
        imageData.SetDimensions(int(dimX), int(dimY), int(dimZ))
        imageData.AllocateScalars(vtk.VTK_UNSIGNED_CHAR, 1)
        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):
                    imageData.SetScalarComponentFromDouble(x, y, z, 0, 0)

        sampleVolumeNode.SetSpacing(1, 1, 1)
        sampleVolumeNode.SetOrigin(bound[0], bound[2], bound[4])

        sampleVolumeNode.SetName("Empty_volume")
        sampleVolumeNode.SetAndObserveImageData(imageData)

        sampleVolumeNode.SetLabelMap(1)
        labelmapVolumeDisplayNode = slicer.vtkMRMLLabelMapVolumeDisplayNode()
        slicer.mrmlScene.AddNode(labelmapVolumeDisplayNode)
        colorNode = slicer.util.getNode('GenericAnatomyColors')
        labelmapVolumeDisplayNode.SetAndObserveColorNodeID(colorNode.GetID())
        labelmapVolumeDisplayNode.VisibilityOn()
        sampleVolumeNode.SetAndObserveDisplayNodeID(
            labelmapVolumeDisplayNode.GetID())

        count = slicer.mrmlScene.GetNumberOfNodesByClass(
            'vtkMRMLSliceCompositeNode')
        for n in xrange(count):
            compNode = slicer.mrmlScene.GetNthNodeByClass(
                n, 'vtkMRMLSliceCompositeNode')
            compNode.SetBackgroundVolumeID(sampleVolumeNode.GetID())