How to react to a segmentation node being changed using cut, erase, paint?

Hello,

How can I react to a segmentation node being changed using the cut, erase and paint capabilities of the segmentation extension? At first I tried to attach slicer.vtkMRMLSegmentationNode.SegmentationChangedEvent this event to the segmentation node and tried to react to it but whenever I changed the segment the control did not go inside my function to react to it. And after that I tried using vtk.vtkSegmentation.SourceRepresentationModified, event but this also so did not work. Is the problem is in my code and one of the above mentioned event is the correct one to use? Or is it totally a different event to react to?

Thank you for your help.

Looks like you need something like:

segmentationNode.GetSegmentation().AddObserver(slicer.vtkSegmentation.RepresentationModified, print)
1 Like

I just tried it. and I also tired SourceRepresentationModified too. Both of them did not work.

            # --- Snip ----

            self.targetSegementationNode.GetSegmentation().AddObserver(
                slicer.vtkSegmentation.RepresentationModified,
                self.onSegmentModified
            )
            
            self.segmentBtn.setEnabled(False)
            self.cancelPreviewBtn.setEnabled(False)
            self.previewBtn.setEnabled(False)

            # Disable undo
            disableShortcut("Ctrl+z")
            
        except Exception as e:
            slicer.util.errorDisplay(f"Error - {e}")
            traceback.print_exc()

    def onSegmentModified(self, caller, event):
        """
        Callback for when the segmentation is modified (Paint/Erase/Cut).
        """
        print("Segment content changed (Erase/Paint detected)!")

When I used the cut tool it did not print.

Try something simple and it should work. I just have one segmentation and when I use the code I pasted I get a print when I use the paint effect on the segmentation. Try to debug in the python console before using the approach in more complex code so that you are confident you know a certain call will work.

3 Likes

Thanks for the solution. It worked.