How do you call a function when a segmentation is modified?

Hello,

I’m looking to create an observer that will allow me to call a method when the segmentation is modified via the segment editor.

Here’s a class I’ve created:

import slicer
from vtk import vtkCommand

class SegmentationWatcher:
    SAVE_FOLDER = 'tmp'
    def __init__(self, extension_path: str, segmentationNode):
        self.__extension_path = extension_path
        self.segmentationNode = segmentationNode
        self.callbackObject = None

    def segmentationModifiedCallback(self, caller, event):
        print("Modified")

    def startWatching(self):
        if self.callbackObject is None:
            self.callbackObject = self.segmentationNode.AddObserver(vtkCommand.ModifiedEvent, self.segmentationModifiedCallback)

    def stopWatching(self):
        if self.callbackObject:
            self.segmentationNode.RemoveObserver(self.callbackObject)
            self.callbackObject = None

However, the function is never called. I deduced that the event was not good.
I saw that the SegmentationModifiedCallbackCommand attribute existed.

So I did this:

import slicer

class SegmentationWatcher:
    SAVE_FOLDER = 'tmp'
    def __init__(self, extension_path: str, segmentationNode):
        self.__extension_path = extension_path
        self.segmentationNode = segmentationNode
        self.callbackObject = None

    def segmentationModifiedCallback(self, caller, event):
        print("Modified")

    def startWatching(self):
        if self.callbackObject is None:
            self.callbackObject = self.segmentationNode.AddObserver(slicer.vtkMRMLSegmentationNode.SegmentationModifiedCallbackCommand,
                                                                    self.segmentationModifiedCallback)

    def stopWatching(self):
        if self.callbackObject:
            self.segmentationNode.RemoveObserver(self.callbackObject)
            self.callbackObject = None

But I have this error :

AttributeError: 'MRMLCore.vtkMRMLSegmentationNode' object has no attribute 'SegmentationModifiedCallbackCommand'

This is normal because the attribute is protected. I’ve tried to make the class an inheritance of slicer.vtkMRMLSegmentationNode but I still have error.

I’d like to know if it’s possible to access it or if another method is more interesting?

Thank you very much in advance for your help and have a nice day!

I think that you are looking for vtkMRMLSegmentationNode::SegmentationChangedEvent.

I tend to use this event:

segmentationNode.AddObserver(slicer.vtkSegmentation.RepresentationModified, self.onSegmentContentModified)

In this case the callback looks like this so you can see which segment was just modified:

  @vtk.calldata_type(vtk.VTK_STRING)
  def onSegmentContentModified(self, caller, eventId, callData=None):
    segmentID = callData
    ...

Also just for completeness I checked SegmentationChangedEvent and it seems to be for something else:

1 Like