How to clear segmentation?

Hi, is there an easy way to clear a segmentation from Python? (Or from the widget, by the way.) I’m now doing this in a module that automatically clears a segmentation after saving it. But this looks like a hack rather than the proper way to clear the segmentation contents.

num_segments = selectedSegmentation.GetSegmentation().GetNumberOfSegments()
for i in range(num_segments):
  segmentId = selectedSegmentation.GetSegmentation().GetNthSegmentID(i)
  labelMapRep = selectedSegmentation.GetBinaryLabelmapRepresentation(segmentId)
1 Like

I don’t think we ever had a use case where you have to actually clear a segmentation. The python code is fine I think - hack or not - in the absence of a way doing this in the UI.

What you could do is have a segmentation with the empty segments pre-populated (I think this is why you want to clear them so that you have the segments with the same name, color, etc.), then clone the segmentation for each segmenation run. You can clone in the Data module from the right-click menu.

You can clear the segmentation in many different ways (remove segment, remove representation, make all voxels 0 value, make the extent empty, …). It would be interesting to know what is the use case so that we can find the most suitable solution.

I have a sequence of changing image, and I would like to create a matching sequence of segmentation. I go to the first item in the image sequence, paint a segmentation, then record it in another sequence browser. Then, I would like to iterate this process through items of the image sequence. But I have hundreds of items in a sequence, so I would like to automate the process. I cannot delete the segments or segmentation because I need to keep it in the segmentation sequence browser as a proxy node.
Unfortunately I’m having issues with the code above. So I was hoping there is a more appropriate way to clear the segments.

We ended up using code in “Logical operators” effect:

Just for completeness of information, I started this thread because I has problems with the cleared segments. I couldn’t repaint on them. But I figured out later that the issue was not in the code that cleared the segments. I’m now use the code Andras quoted, but just FYI the first code also works.

In the latest nightly, there is now an option to clear selected segments from the context menu in the segments table:

Great, thanks! Can I be lazy and ask you to please paste here a link to the code that other modules and scripts can call to use this function?

I used the same approach as you to reset the segment from the GUI:


I could add a helper method to the module logic that would expose the same function to python if you think it would be useful.

That’s OK. I was just wondering if there is another function that would be preferred. This works fine.