Converting Segmentation to Volume automatically w/ Python or Matlab

Hello there! I have 200+ CT-Volumes with matching segmentations. The Volumes are in .nrrd format and the segmentations are in seg.nrrd format. I need both of those as .nii.gz format and I want to script the conversion from one into the other format.

Regarding the Volumes, everything has been quite easy, using sitk:

import SimpleITK as sitk

img = sitk.ReadImage(“your_image.nrrd”)
sitk.WriteImage(img, “your_image.nii.gz”)

I just did the same thing with the segmenations, too, which worked fine at first glance. But the problem is now that the segmentations are not registered with the Volumes anymore. The image dimensions as well as image origins are not the same anymore and thus, I cannot process the converted images.

The same happens, when I do the following steps manually: 1. Load the .seg.nrrd files into Slicer as Segementation 2. Save the segmentation as .nrrd file instead of seg.nrrd 3. Import the .nrrd file as Volume and save the segmentation as .nii.gz

But I figured out a way to convert the data types manually while keeping all dimensions: 1. Import the Volume as well as the corresponding segmentation (.seg.nrrd) 2. Export the segmentation to a labelmap with reference volume set to my corresponding volume 3. Save the Labelmap as nii.gz (4. Not sure if I need that step for my project: Convert Labelmap to Scalar Volume and safe as nii.gz)

In both cases 3. and 4. I have a nii.gz file with matching dimensions. But since I have 200+ Volumes, I need to script that. But I haven’t found anything so far. Do you have any ideas? Thanks!

You can load the segmentation and export to volume file. If you want the segmentation to have a particular geometry (origin, spacing, axis directions, and extents) then specify the CT volume as reference volume when you export to volume file (when you call ExportSegmentsBinaryLabelmapRepresentationToFiles).

See complete example here: