Here are a couple python functions I have which I use to copy or subtract segments, adding would be a simple variation:
def setup_segment_editor(segmentationNode=None, masterVolumeNode=None):
'''Runs standard setup of segment editor widget and segment editor node'''
if segmentationNode is None:
# Create segmentation node
segmentationNode = slicer.vtkMRMLSegmentationNode()
slicer.mrmlScene.AddNode(segmentationNode)
segmentationNode.CreateDefaultDisplayNodes()
segmentEditorWidget = slicer.qMRMLSegmentEditorWidget()
segmentEditorNode = slicer.vtkMRMLSegmentEditorNode()
slicer.mrmlScene.AddNode(segmentEditorNode)
segmentEditorWidget.setMRMLSegmentEditorNode(segmentEditorNode)
segmentEditorWidget.setSegmentationNode(segmentationNode)
segmentEditorWidget.setMRMLScene(slicer.mrmlScene)
if masterVolumeNode:
segmentEditorWidget.setMasterVolumeNode(masterVolumeNode)
return segmentEditorWidget, segmentEditorNode, segmentationNode
def copy_segment(newSegmentName, segmentationNode, segmentIDToCopy):
""" Copy an existing segment into a new segment without overwriting """
import SegmentEditorEffects
segmentEditorWidget, segmentEditorNode, segmentationNode = setup_segment_editor(segmentationNode)
newSegmentID = segmentationNode.GetSegmentation().AddEmptySegment(newSegmentName)
segmentEditorNode.SetSelectedSegmentID(newSegmentID)
segmentEditorWidget.setActiveEffectByName('Logical operators')
effect = segmentEditorWidget.activeEffect()
effect.setParameter("Operation", SegmentEditorEffects.LOGICAL_COPY)
effect.setParameter("ModifierSegmentID", segmentIDToCopy)
# Masking Settings
effect.setParameter("BypassMasking",1) # probably not necessary since I adjust masking settings next
segmentEditorNode.SetMaskMode(segmentEditorNode.PaintAllowedEverywhere)
segmentEditorNode.MasterVolumeIntensityMaskOff()
segmentEditorNode.SetOverwriteMode(segmentEditorNode.OverwriteNone)
# Do the copy
effect.self().onApply()
slicer.mrmlScene.RemoveNode(segmentEditorNode)
return newSegmentID
def subtract_segment(segmentationNode, segmentID, to_subtract_segmentID):
'''Perform logical subtraction of to_subtract_segmentID from segmentID'''
import SegmentEditorEffects
segmentEditorWidget, segmentEditorNode, segmentationNode = setup_segment_editor(segmentationNode)
segmentEditorNode.SetSelectedSegmentID(segmentID)
segmentEditorWidget.setActiveEffectByName('Logical operators')
effect = segmentEditorWidget.activeEffect()
effect.setParameter("Operation", SegmentEditorEffects.LOGICAL_SUBTRACT)
effect.setParameter("BypassMasking",1)
effect.setParameter("ModifierSegmentID",to_subtract_segmentID)
effect.self().onApply()
slicer.mrmlScene.RemoveNode(segmentEditorNode)