Margin effect altering multiple segments at once

parmidajafarian
Fri, 19 Dec 2025 12:48:32 +0000
Support

Hi everyone,

I’m running into a problem while trying to use the margin effect in the segment editor. My goal is to create a shrunken copy of a Brain segment for CSF segmentation without altering the original Brain segment.

For some reason, the moment effect.self().onApply() is executed, the original Brain segment is altered in a way I don’t expect. Instead of leaving the original segment untouched, it appears to contain only the voxels that were removed from the shrunken segment.

Here’s the relevant code snippet:

# Create Brain Shrunk Segment as a copy of original Brain
existingIds = set(segmentation.GetSegmentIDs())
segmentation.CopySegmentFromSegmentation(segmentation, segmentId)
newIds = set(segmentation.GetSegmentIDs())
shrunkSegmentId = list(newIds - existingIds)[0]  # The new segment ID
shrunkSegment = segmentation.GetSegment(shrunkSegmentId)
shrunkSegment.SetName(shrunkSegmentName)

# Set up Segment Editor to subtract shrunk Brain from CSF shell
slicer.app.processEvents()
segmentEditorWidget = slicer.qMRMLSegmentEditorWidget()
segmentEditorWidget.setMRMLScene(slicer.mrmlScene)
segmentEditorNode = slicer.mrmlScene.AddNewNodeByClass("vtkMRMLSegmentEditorNode")
segmentEditorWidget.setMRMLSegmentEditorNode(segmentEditorNode)
segmentEditorWidget.setSegmentationNode(segNode)

# Shrink Brain Segment
segmentEditorWidget.setActiveEffectByName("Margin")
effect = segmentEditorWidget.activeEffect()
segmentEditorNode.SetSelectedSegmentID(shrunkSegmentId)
effect.setParameter("ApplyToAllVisibleSegments", 0)
effect.setParameter("MarginSizeMm", marginMm)  # Amount to shrink
effect.self().onApply()

Theoretically, CopySegmentFromSegmentation should create a deep copy, and I don’t experience the same issue later on when applying the logical operators effect on another copy of the Brain Segment. I’ve also verified that the selected segment ID is correctly set before calling the effect.

Any guidance on how to ensure that only the selected segment is affected would be greatly appreciated. Thanks in advance.

4 posts - 3 participants