OK, I can create and apply a color table from the existing values, and then get the correct values from segNode.GenerateMergedLabelmapForAllSegments()
.
— Create Color table
def ColorTableFromSegmentation(segNode, tableName="SegmentationColorTable"):
segmentation = segNode.GetSegmentation()
colorNode = slicer.mrmlScene.AddNewNodeByClass("vtkMRMLColorTableNode", tableName)
colorNode.SetTypeToUser()
colorNode.HideFromEditorsOff()
maxLabel = 0
for segId in segmentation.GetSegmentIDs():
seg = segmentation.GetSegment(segId)
lv = int(seg.GetLabelValue())
if lv > maxLabel:
maxLabel = lv
colorNode.SetNumberOfColors(maxLabel + 1)
for segId in segmentation.GetSegmentIDs():
seg = segmentation.GetSegment(segId)
name = seg.GetName()
labelValue = int(seg.GetLabelValue())
(r, g, b) = seg.GetColor()
Ri = int(round(r * 255))
Gi = int(round(g * 255))
Bi = int(round(b * 255))
Ai = 255
colorNode.SetColor(labelValue, Ri, Gi, Bi, Ai)
colorNode.SetColorName(labelValue, name)
return colorNode
— Apply Color table
ct = ColorTableFromSegmentation(segNode)
segNode.SetLabelmapConversionColorTableNodeID( ct.GetID() )
— Create labelmap with ConversionColorTable applied
import slicer
import vtk
import os
import tempfile
import numpy as np
from vtk.util import numpy_support
def SegNode_to_Labelmap(segNode, volNode):
segmentation = segNode.GetSegmentation()
mergedImageData = slicer.vtkOrientedImageData()
extent = slicer.vtkSegmentation.EXTENT_REFERENCE_GEOMETRY
segIDs = vtk.vtkStringArray()
segVals = vtk.vtkIntArray()
for segTemp in AtlasTemplate.brainTemplate_99:
segIDs.InsertNextValue(segTemp['name'])
segVals.InsertNextValue(int(segTemp['value']))
success = segNode.GenerateMergedLabelmapForAllSegments(mergedImageData, extent, None, segIDs, segVals)
print("GenerateMergedLabelmap success:", success)
if success:
labelmapNode = slicer.mrmlScene.AddNewNodeByClass( "vtkMRMLLabelMapVolumeNode", "Merged_Labelmap" )
labelmapNode.SetAndObserveImageData(mergedImageData)
#print unique values in mergedImageData
scalars = mergedImageData.GetPointData().GetScalars()
npArray = numpy_support.vtk_to_numpy(scalars)
uniqueValues = np.unique(npArray)
print("values:", uniqueValues)
return labelmapNode
else:
return None
This prints a list of the correct values, however when I hover over the labelmap, I stream of errors:
[VTK] GetScalarIndex: Pixel (26, 0, 22) not in memory. [VTK] Current extent= (12, 190, 15, 223, 17, 187)
Also, the labelmap doesn’t use the colors from the color table, yet the correct colors are applied if I do NOT apply the color table.