How to clone a segmentation using Python

I have the segmentation of an anatomical structure.
I want to clone that segmentation to apply a transform on a copy in order to analyze the impact of the transform.

segmentation_cancer_contracted.SetName("Cancer contracted")

This create a second segmentation but it seems to be linked to the original one. For example when I hide one, both hide.

I want something similar to the “clone” option when right clicking the segmentation. I understand that I have to use vtkSlicerSubjectHierarchyModuleLogic::CloneSubjectHierarchyItem but I don’t understand the input

Any help would be greatly appreciated

The script repository is an incredible source of knowledge.

Here’s the relevant script:

The cloning function does not provide this, on purpose, because it can cause problems if the content of the two segmentations start to differ. But it you insist on this, you can se the display node of the original to be the display node of the clone as well. Or you can add an observer on the display node and synchronize visibility or whatever property you’d like.

1 Like

Thanks you, I was able to find the solution :grinning:

Here is the working code

shNode = slicer.vtkMRMLSubjectHierarchyNode.GetSubjectHierarchyNode(slicer.mrmlScene) itemIDToClone = shNode.GetItemByDataNode(segmentation_cancer) clonedItemID = slicer.modules.subjecthierarchy.logic().CloneSubjectHierarchyItem(shNode, itemIDToClone) segmentation_cancer_contracted = shNode.GetItemDataNode(clonedItemID) segmentation_cancer_contracted.SetName("Cancer contracted") segmentation_cancer_contracted.GetSegmentation().GetNthSegment(0).SetName("cancer contracted") segmentation_cancer_contracted.SetAndObserveTransformNodeID(inverse_transform.GetID()) segmentation_cancer_contracted.HardenTransform()