Create new segment in Python script

I’m attempting to create and configure a segment within a new segmentation node via Python script. Here is what I’m attempting:

    segNode = slicer.vtkMRMLSegmentationNode()
    slicer.mrmlScene.AddNode(segNode)
    segNode.CreateDefaultDisplayNodes()
    segNode.SetReferenceImageGeometryParameterFromVolumeNode(self.SSFPVolumeNode)
    theSegmentation = segNode.GetSegmentation()
    theSegmentation.AddEmptySegment("test")

The result is an error that theSegmentation does not have a method AddEmptySegment. When I check the class type, theSegmentation is a vtkObject, rather than a vtkSegmentation. Is there a reason for this? Do I need to downcast to vtkSegmentation, or is there something I’m doing incorrectly?
Thanks very much.

You need to import vtkSegmentationCorePython, we usually do it like this:
import vtkSegmentationCorePython as vtkSegmentationCore

It would be great if it was imported by default, similarly to all the other libraries, like vtkAddon etc.
@jcfr @pieper I have tried to make that happen, but it turned out to be more complicated than I thought. I’ll submit a PR shortly, I hope you can tell me what’s missing. Thanks!

1 Like

Great, thanks! That seems to work well so far.

This is the PR I made to make it easier for everybody to use segmentations from python

I’ve tried to implement this before, similarly to Csaba, and failed, too.

@jcfr, I think you implemented this for other libraries - what’s the trick that we missed?

A post was split to a new topic: Prevent a segment from changing when editing other segments