Writing a nrrd segmentation file in SimpleITK


How can I save my connected components to a nrrd segmentation file that I can visualize in Slicer?



Hello Diego,

What have you tried and what problems did you run into? Do you have a minimal example to reproduce your problematic situation?


What you probably need is show advanced options when loading data in Slicer and select “Label map”. That option is on by default if the file name ends in -label (e.g. out-label.nrrd), so you can just drag-drop it into Slicer.

I have connected components in my image after:

cc = sitk.ConnectedComponentsImageFilter()
results = cc.Execute(im_input)

I want to save results as a nrrd segmentation file that I can visualize in Slicer.

Hello @Diego_C ,

Just save the results as an image:

sitk.WriteImage(results, 'cc_results.mha')

Then you just load this image and overlay onto the original (I usually use ITK-SNAP for quick visualizations as it loads faster than Slicer. When I need more functionality I go with Slicer).

Thanks @zivy I need to show the results in Slicer though. I was thinking of writing the segmentation metadata myself but I was wondering if there was a simpler way of doing it with SimpleITK?

Hi @Diego_C ,

Not sure what you mean by “segmentation metadata”. If you write the segmentation to disk you just open the saved file in Slicer.

If you want to programmatically open Slicer and display the image with overlay you will have to:

  1. Set Slicer as your viewing command (see ImageViewer).
  2. Create the color overlay image yourself (see visualization notebook), as the viewer expects a single image.

If you want to save segment name, color, standard DICOM terminology, etc. in the nrrd file then you can do that by adding metadata fields using itk::MetaDataDictionary and pass it on to the reader using SetMetaDataDictionary. Definition of seg.nrrd file custom metadata fields is available here.


Hey @zivy the nrrd files need to have a particular set of metadata headers so you can use them with the Segmentation Module in Slicer. I was wondering if there was a way to get this without having to coding it myself.

Thank you @lassoan this is what I was thinking I had to do. Thanks for the reference!



Hello Andras Lasso,
I want to save a segment label with its name, but I can not see how I do this using SimpleITK. The code to save my segment is:
writer = sitk.ImageFileWriter()
writer.Execute(label, segment.seg.nrrd’, True,0)
I need some help.