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
Hi,
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:
slicer.mrmlScene.RemoveNode(ctn)
please handle with care
A segmentation node (vtkMRMLSegmentationNode) object contains a Segmentation (vtkSegmentation) that contains Segments (vtkSegment).
>>> segmentation_node = slicer.util.getNode("Segmentation")
>>> segmentation_node
(MRMLCore.vtkMRMLSegmentationNode)00000162D42FA1C8
>>> segmentation = segmentation_node.GetSegmentation()
(vtkSegmentationCore.vtkSegmentation)00000162D42FA648
>>> segmentation.GetNumberOfSegments()
1
>>> segmentation.GetNthSegment(0)
(vtkSegmentationCore.vtkSegment)00000162D42FAE88
Thank you! I appreciate the examples! I got it now