# Writing a nrrd segmentation file in SimpleITK

**URL:** https://discourse.itk.org/t/writing-a-nrrd-segmentation-file-in-simpleitk/3903
**Category:** Engineering
**Tags:** simpleitk, python
**Created:** [February 25, 2021, 3:59am UTC](https://discourse.itk.org/t/writing-a-nrrd-segmentation-file-in-simpleitk/3903 "2021-02-25T03:59:40Z")
**Posts on this page:** 14
**Page:** 1

<div class="post-metadata">

### Author: ![Diego\_C](https://discourse.itk.org/user_avatar/discourse.itk.org/diego_c/32/279_2.png) [@Diego\_C](https://discourse.itk.org/u/Diego_C)
#### Post date: [February 25, 2021, 3:59am UTC](https://discourse.itk.org/t/writing-a-nrrd-segmentation-file-in-simpleitk/3903/1 "2021-02-25T03:59:40Z")

</div>

Hi!

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

Thanks,

Diego

---

<div class="post-metadata">

### Author: ![blowekamp](https://discourse.itk.org/user_avatar/discourse.itk.org/blowekamp/32/79_2.png) [@blowekamp](https://discourse.itk.org/u/blowekamp)
#### Post date: [February 25, 2021, 2:03pm UTC](https://discourse.itk.org/t/writing-a-nrrd-segmentation-file-in-simpleitk/3903/2 "2021-02-25T14:03:35Z")

</div>

Hello Diego,

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

Thanks.

---

<div class="post-metadata">

### Author: ![dzenanz](https://discourse.itk.org/user_avatar/discourse.itk.org/dzenanz/32/1093_2.png) [@dzenanz](https://discourse.itk.org/u/dzenanz)
#### Post date: [February 25, 2021, 4:53pm UTC](https://discourse.itk.org/t/writing-a-nrrd-segmentation-file-in-simpleitk/3903/3 "2021-02-25T16:53:46Z")

</div>

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.

---

<div class="post-metadata">

### Author: ![Diego\_C](https://discourse.itk.org/user_avatar/discourse.itk.org/diego_c/32/279_2.png) [@Diego\_C](https://discourse.itk.org/u/Diego_C)
#### Post date: [February 25, 2021, 7:46pm UTC](https://discourse.itk.org/t/writing-a-nrrd-segmentation-file-in-simpleitk/3903/4 "2021-02-25T19:46:14Z")

</div>

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.

---

<div class="post-metadata">

### Author: ![zivy](https://discourse.itk.org/user_avatar/discourse.itk.org/zivy/32/1726_2.png) [@zivy](https://discourse.itk.org/u/zivy)
#### Post date: [February 25, 2021, 7:54pm UTC](https://discourse.itk.org/t/writing-a-nrrd-segmentation-file-in-simpleitk/3903/5 "2021-02-25T19:54:20Z")

</div>

Hello @Diego_C ,

Just save the results as an image:

```auto
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).

---

<div class="post-metadata">

### Author: ![Diego\_C](https://discourse.itk.org/user_avatar/discourse.itk.org/diego_c/32/279_2.png) [@Diego\_C](https://discourse.itk.org/u/Diego_C)
#### Post date: [February 25, 2021, 7:55pm UTC](https://discourse.itk.org/t/writing-a-nrrd-segmentation-file-in-simpleitk/3903/6 "2021-02-25T19:55:52Z")

</div>

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?

---

<div class="post-metadata">

### Author: ![zivy](https://discourse.itk.org/user_avatar/discourse.itk.org/zivy/32/1726_2.png) [@zivy](https://discourse.itk.org/u/zivy)
#### Post date: [February 25, 2021, 8:08pm UTC](https://discourse.itk.org/t/writing-a-nrrd-segmentation-file-in-simpleitk/3903/7 "2021-02-25T20:08:58Z")

</div>

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](https://simpleitk.org/doxygen/latest/html/classitk_1_1simple_1_1ImageViewer.html)).
2. Create the color overlay image yourself (see [visualization notebook](https://github.com/InsightSoftwareConsortium/SimpleITK-Notebooks/blob/master/Python/05_Results_Visualization.ipynb)), as the viewer expects a single image.

---

<div class="post-metadata">

### Author: ![lassoan](https://discourse.itk.org/user_avatar/discourse.itk.org/lassoan/32/27_2.png) [@lassoan](https://discourse.itk.org/u/lassoan)
#### Post date: [February 26, 2021, 12:41am UTC](https://discourse.itk.org/t/writing-a-nrrd-segmentation-file-in-simpleitk/3903/8 "2021-02-26T00:41:50Z")

</div>

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](https://apidocs.slicer.org/master/classvtkMRMLSegmentationStorageNode.html#details).

---

<div class="post-metadata">

### Author: ![Diego\_C](https://discourse.itk.org/user_avatar/discourse.itk.org/diego_c/32/279_2.png) [@Diego\_C](https://discourse.itk.org/u/Diego_C)
#### Post date: [February 26, 2021, 3:41am UTC](https://discourse.itk.org/t/writing-a-nrrd-segmentation-file-in-simpleitk/3903/9 "2021-02-26T03:41:45Z")

</div>

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.

---

<div class="post-metadata">

### Author: ![Diego\_C](https://discourse.itk.org/user_avatar/discourse.itk.org/diego_c/32/279_2.png) [@Diego\_C](https://discourse.itk.org/u/Diego_C)
#### Post date: [February 26, 2021, 3:43am UTC](https://discourse.itk.org/t/writing-a-nrrd-segmentation-file-in-simpleitk/3903/10 "2021-02-26T03:43:18Z")

</div>

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

Cheers,

Diego

---

<div class="post-metadata">

### Author: ![fghazouani](https://discourse.itk.org/letter_avatar_proxy/v4/letter/f/f07891/32.png) [@fghazouani](https://discourse.itk.org/u/fghazouani)
#### Post date: [January 13, 2022, 1:44pm UTC](https://discourse.itk.org/t/writing-a-nrrd-segmentation-file-in-simpleitk/3903/11 "2022-01-13T13:44:28Z")

</div>

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.

---

<div class="post-metadata">

### Author: ![ibro45](https://discourse.itk.org/user_avatar/discourse.itk.org/ibro45/32/1639_2.png) [@ibro45](https://discourse.itk.org/u/ibro45)
#### Post date: [October 22, 2023, 12:33am UTC](https://discourse.itk.org/t/writing-a-nrrd-segmentation-file-in-simpleitk/3903/12 "2023-10-22T00:33:14Z")

</div>

@lassoan [this](https://slicer.readthedocs.io/en/latest/developer_guide/modules/segmentations.html) was pretty insightful, thank you!

Is there any nice example somewhere of assigning these correctly to a LabelMap with multiple labels? Especially when there are many labels and when `SegmentN_Layer` and `SegmentN_LabelValue` should be used.

---

<div class="post-metadata">

### Author: ![zivy](https://discourse.itk.org/user_avatar/discourse.itk.org/zivy/32/1726_2.png) [@zivy](https://discourse.itk.org/u/zivy)
#### Post date: [October 22, 2023, 5:17pm UTC](https://discourse.itk.org/t/writing-a-nrrd-segmentation-file-in-simpleitk/3903/13 "2023-10-22T17:17:25Z")

</div>

Hello @ibro45,

Not exactly what you are looking for but closely related, an example of three labels saved to seg.nrrd format is available in the [results visualization notebook](https://github.com/InsightSoftwareConsortium/SimpleITK-Notebooks/blob/e805f171ef633575486b48377db4e0715d42f63d/Python/05_Results_Visualization.ipynb#L860), `visual_comparison_of_segmentation` function.

---

<div class="post-metadata">

### Author: ![ibro45](https://discourse.itk.org/user_avatar/discourse.itk.org/ibro45/32/1639_2.png) [@ibro45](https://discourse.itk.org/u/ibro45)
#### Post date: [October 24, 2023, 3:55pm UTC](https://discourse.itk.org/t/writing-a-nrrd-segmentation-file-in-simpleitk/3903/14 "2023-10-24T15:55:09Z")

</div>

Thank you so much @zivy, that really helped.

For future reference, I’ll explain what I did:

I needed to save overlapping segmentations with a particular name and color. I first collected the binary masks for each segmentation and then composed them using `sitk.Compose`. Then, I set the metadata for each segment in the composed mask. Code:

```python
from SimpleITK import sitk

def set_individual_segment_metadata(mask, seg_num, name, color, tags=None):
    # `seg_num` starts from 0, but ID starts from 1
    mask.SetMetaData(f"Segment{seg_num}_ID", str(seg_num + 1))
    # A separate layer per label, allows overlapping segmentations.
    mask.SetMetaData(f"Segment{seg_num}_Layer", str(seg_num))
    # Each label is saved in a separate layer, so we just need to set the foreground of each to 1
    mask.SetMetaData(f"Segment{seg_num}_LabelValue", "1")

    mask.SetMetaData(f"Segment{seg_num}_Name", name)
    mask.SetMetaData(f"Segment{seg_num}_NameAutoGenerated", "0")

    mask.SetMetaData(f"Segment{seg_num}_Color", color)
    mask.SetMetaData(f"Segment{seg_num}_ColorAutoGenerated", "0")

    # Extent, as defined in https://github.com/InsightSoftwareConsortium/SimpleITK-Notebooks/blob/e805f171ef633575486b48377db4e0715d42f63d/Python/05_Results_Visualization.ipynb#L860
    mask.SetMetaData(
        f"Segment{seg_num}_Extent", 
        f"0 {mask.GetWidth()-1} 0 {mask.GetHeight()-1} 0 {mask.GetDepth()-1}"
    )

    if tags is not None:
        mask.SetMetaData(f"Segment{seg_num}_Tags", tags)

    return mask

# Combine all masks
mask = sitk.Compose([
    LA, LV, ...
])

# Set metadata per segment, make sure to apply in the same order as above
mask = set_individual_segment_metadata(mask, 0, "LA", "1.0 0.0 0.0") # Red
mask = set_individual_segment_metadata(mask, 1, "LV", "0.0 1.0 0.0") # Green
...

# Common metadata
mask.SetMetaData("Segmentation_MasterRepresentation", "Binary labelmap")
mask.SetMetaData("Segmentation_ReferenceImageExtentOffset", "0 0 0")
mask.SetMetaData("Segmentation_ContainedRepresentationNames", "Binary labelmap|")

```
