Cloning a SegmentationNode segment in Python

I am working on a module where I make a make a binary labelmap on a 2d view with the scissors rectangle tool. The next step is to cut the rectangle into 3 regions for further processing.

My first approach was to add 3 segments with AddEmptySegment and then use SetExtent to resize the rectangles. This is not being reflected in the segmentation node so I am obviously missing something.

I worked out that I can do this manually by right-clicking on the mask in Subject Hierarchy in the Data module and selecting Clone. I can then rename the segment and modify Extent.

Is it possible to perform the clone from Python? I looked at the SubjectHierarchy code but could not work it out.

I worked it out, if the original mask is (62, 71, 69, 102, 0, 11) the upper region is

slicer.mrmlScene.GetNodeByID("vtkMRMLSegmentationNode1").GetSegmentation().AddEmptySegment("upper")
s0 = slicer.mrmlScene.GetNodeByID("vtkMRMLSegmentationNode1").GetSegmentation().GetNthSegment(0)
s1 = slicer.mrmlScene.GetNodeByID("vtkMRMLSegmentationNode1").GetSegmentation().GetNthSegment(1)
s1.DeepCopy(s0)
slicer.mrmlScene.GetNodeByID("vtkMRMLSegmentationNode1").GetSegmentation().GetNthSegment(1).SetName("upper")
slicer.mrmlScene.GetNodeByID("vtkMRMLSegmentationNode1").GetSegmentation().GetNthSegment(1).GetRepresentation("Binary labelmap").SetExtent([62, 71, 69, 80, 0, 11])

You can clone an item via code like this

clonedItemID = slicer.modules.subjecthierarchy.logic().CloneSubjectHierarchyItem(shNode, itemID)

1 Like

Thanks, that is a much easier way to do it.

I found a problem using the suggested method on a segmentation. If you load sample data and create a segmentation with Segment Editor the clone is not valid

import SampleData
node = SampleData.SampleDataLogic().downloadMRHead()

Switch to Segment Editor and create a segmentation

segmentationNode = slicer.mrmlScene.GetNodeByID("vtkMRMLSegmentationNode1")
shNode = slicer.vtkMRMLSubjectHierarchyNode.GetSubjectHierarchyNode(slicer.mrmlScene)
segmentationID = shNode.GetItemByDataNode(segmentationNode)
segmentID = shNode.GetItemChildWithName(segmentationID, "Segment_1")
clonedItemID = slicer.modules.subjecthierarchy.logic().CloneSubjectHierarchyItem(shNode, segmentID)

The result is Segment_1 Copy but it is not a valid segment

If I right-click on Segment_1 and choose Clone then the clone is a valid copy. Should the 2 methods be equivalent?