Is there a way to get a list of all child segments of a segmentation programmatically?

How can I get a list of all the segments in a segmentation. For example I have 10 segments in my segmentation. I want a list of these 10 segments so I can use them in my code later on. Is this possible? Is so, how?

If you want a list of segment IDs, you can get them using vtkSegmentation::GetSegmentIDs:

segmentationNode.GetSegmentation().GetSegmentIDs()

@Sunderlandkyl when I enter this in the python interactor in slicer, I get this:
Traceback (most recent call last):
File “”, line 1, in
TypeError: no overloads of GetSegmentIDs() take 0 arguments

Also , is there a way to get the names of these segments instead of IDs?

What version of Slicer are you using? This works in latest version (as of 20 days ago). Othewise, you can pass a vtkStringArray as an argument.

If you are tracking the list of segments for later use, it is better to use segment IDs as the IDs shouldn’t change.

You can get the name of a segment using vtkSegment::GetName():

for segmentID in segmentIDs:
  segmentationNode.GetSegmentation().GetSegment(segmentID).GetName()

or

for i in range(segmentationNode.GetSegmentation().GetNumberOfSegments()):
  segmentationNode.GetSegmentation().GetNthSegment(i).GetName()
2 Likes

I’m using slicer 4.11.20200930

Hi @Sunderlandkyl .
I have same problem. I´ve passed and vtkStringArray as argument but it shouldn´t looks to be iterable

Error msg:
image

Maybe I´m doing something wrong…

Thanks on advance!

You can iterate through a vtkStringArray like this:

for i in range(segmentIDs.GetNumberOfValues()):
  segmentID = segmentIDs.GetValue(i)
2 Likes