Iterating through segments in a segmentation Node

I know this has got to be something obvious that I’m not getting but I’ve spent a really long time longer for the answer and I can’t seem to find it. If I have a segmentation node loaded in and saved as a variable, how can I iterate through its segments in python? Thank you

You can get a segment object if you know the segment index in the segmentation node that you want. This example includes a way to get a segment id by segment name.

You could also use methods available in the vtkSegmentation object such as GetNumberOfSegments as a way to get the number of indices to then use with getNthSegment. See Slicer: vtkSegmentation Class Reference.

Great! Thank you, the GetNumberOfSegments method is exactly the type of thing I was looking for!

I’m sorry but for the life of me I cannot figure out how to use the vtkSegmentation class in my python code. Do you have any advice for how to implement it? Thank you


Just a short example: This fragment of python code will iterate through all currently loaded segment nodes and delete each one containing the string “MaskSegmentation”

allSegmentNodes = slicer.util.getNodes('vtkMRMLSegmentationNode*').values()
for ctn in allSegmentNodes:
  teststr = ctn.GetName()
  if 'MaskSegmentation' in teststr:

please handle with care :slight_smile:

A segmentation node (vtkMRMLSegmentationNode) object contains a Segmentation (vtkSegmentation) that contains Segments (vtkSegment).

>>> segmentation_node = slicer.util.getNode("Segmentation")
>>> segmentation_node
>>> segmentation = segmentation_node.GetSegmentation()
>>> segmentation.GetNumberOfSegments()
>>> segmentation.GetNthSegment(0)

Thank you! I appreciate the examples! I got it now