Get labelmap from each segment separately?

label

I try to convert segmentation to labelmap separately from cli (eg labelmap of body, lung_L and lung_R separately). I found that this code below can export visable segment to labelmap.

seg = getNode(‘Segmentation’)
reference = getNode (‘InputVolume’) # this will be the volume the segmentation was drawn on
labelmapVolumeNode = slicer.mrmlScene.AddNewNodeByClass(‘vtkMRMLLabelMapVolumeNode’)

ids = vtk.vtkStringArray()
seg.GetDisplayNode().GetVisibleSegmentIDs(ids)
slicer.modules.segmentations.logic().ExportSegmentsToLabelmapNode(seg, ids, labelmapVolumeNode, reference)

But how can I turn visible on or off from cli, or there other method to export labelmap separately from cli?.

You can change visibility of a segment by using SetSegmentVisibility method of the segmentation display node.

However, it is probably easier and faster to get all segments at once, as a numpy array, and then use standard numpy operations to extract/recolor a chosen all voxel that have a particular value (see for this example to mask a scalar volume - you can mask a labelmap volume the same way).

1 Like

There is another simple way to accomplish this with an in-built function from vtkSlicerSegmentationsModuleLogic, which I’ve been using recently, and which circumvents segment visibilites entirely. Example code is below - if you need to convert regions one-by-one and separately, use lists of length 1 (e.g. [“background”], [“prostate”], [“tumor”]) instead of a list with multiple regions ([“background”, “prostate”, “tumor”]):

# nseg ... segmentation node
# nvol ... volume reference node of the segmentation 
# nlab ... node of the target labelmap (will adopt the geometry of nvol)
# listSegmentNames ... a list of strings with segment names to be included
#                      in the labelmap (for single-region: a string list of len 1)

# Convert list of segment names to a vtkStringArray of segment IDs
strarr = vtk.vtkStringArray()
for sname in listSegmentNames:
    sid = nseg.GetSegmentation().GetSegmentIdBySegmentName(sname)
    strarr.InsertNextValue(sid)
# Export the list of segments to a labelmap
slicer.vtkSlicerSegmentationsModuleLogic.ExportSegmentsToLabelmapNode(nseg, strarr, nlab, nvol)
2 Likes