Save segmentation with orig values as nii.gz when classes missing

I have several binary masks saved as nii.gz. Let’s say that I have 3 classes 1,2 and 3. But 2 is missing. I want to load nii.gz into slicer as a segmentation along with the volume. And manually paint the second class. Then save as nii.gz. The new class should have value 2 and the other values should be unchanged.

When I load the file, the segmentation loads as Segment_1 and Segment_3. I add a segment. Slicer names it Segment_2.
All good up to this point…
Now when I export to binary label mask and save as Newfile.nii.gz, I believe that my classes are mixed up. I load Newfile.nii.gz as a volume and mouse over. Now instead of 1,2,3 (or 1,3,4) I have 1,3,2. Class 3 has a value =2 and Class 2 has a value=3.

Any suggestions?

Slicer flattens the segmentations into labelmap in the order your segments are. So if your segment order is like:

Segment_1
Segment_3
Segment_2

Segment_2 will get index of 3.

If you want to get it index of 2, move one segment up before you export. Or better yet, use a color table that defines the indices, that way order doesn’t matter.

I tried moving one up. I do not think that it changed anything. The problem is that I have a bunch of classes and more than one are missing (sometimes).

Is it possible to load a segmentation and then save it with the same values? Assuming some are missing?

My work around right now is to save only the new class. Then I can add that class into the orig file.

How do you know? It does changes things.

If you want Slicer to export your labelmap with specific numbers, you should really use a color table. That gives you full control over what the indices will be.

“move one segment up before you export.” This refers to the order in subject heirarchy? Or is it only the move up/down in the Segmentation Module. Want to check before I try again. I just dragged it up in the subject heirarchy. May not be the same thing… That was the first thing that I tried… That’s why I wrote "I do not think that it changed anything. "

In the Segmentations or Segment editor module. Right click on the segment you want to move up, and choose “Move Segment One Up” (or something like that) from the context menu. But SH should follow that.

That works. But I would need also need to add empty segments.

That’s because you want to skip indices for labels that are not there. As I said, if you want to have full control, use a color table.

It can go something like
1 Segment_1
2 Segment_2
3 Segment_3

And it doesn’t matter if you have if you didn’t have Segment_1 and Segment_2. Segment_3 will get index number of 3.