Save a custom attribute in header of Nifti

Hey,

I want to indicate to my python code if a Nifti image is an image or a segmentation.

To accomplish that I want to store a single attribute in the Nifti header in one of the more flexible Nifti header fields such as a specific int in the intent_code field or a specific string in the intent_name field or the ITK_FileNotes field.

However, as it turns out SimpleITK deduces the header fields from the image data and is not so flexible in modifying specific header fields. See here: [Python] Nifti metadata cannot be modified · Issue #2177 · SimpleITK/SimpleITK · GitHub

For example in this code, I can modify the header in memory, but all changes are ignored when saving the image as Nifti. So this code does not solve my problem:

import SimpleITK as sitk

load_filepath = "image.nii.gz"
save_filepath = "new_image.nii.gz"

print("Load image...")
image_sitk = sitk.ReadImage(load_filepath)
# Change some header fields
print("intent_code: ", image_sitk.GetMetaData("intent_code"))
print("ITK_FileNotes: ", image_sitk.GetMetaData("ITK_FileNotes"))
print("pixdim[1]: ", image_sitk.GetMetaData("pixdim[1]"))
image_sitk.SetMetaData("intent_code", "1002")
image_sitk.SetMetaData("ITK_FileNotes", "Test")
# Save the image (All header modifications are ignored by SimpleITK)
sitk.WriteImage(image_sitk, save_filepath)

# New image will have only unmodified header
print("Load new image...")
image_sitk = sitk.ReadImage(save_filepath)
print("intent_code: ", image_sitk.GetMetaData("intent_code"))
print("ITK_FileNotes: ", image_sitk.GetMetaData("ITK_FileNotes"))

Are there any Nifti header fields that I can modify with SimpleITK or is there some other way to indicate in the header that the image is a segmentation?

Best,
Karol

Hello @Karol-G,

Per our previous discussion, this is an ITK issue and should have been opened on that toolkit’s issue tracker, not here.

In any case, this PR adds support for writing the nifti descrip (exposed as ITK_FileNotes) field which should address your issue. Note that this will take some time till it is included in an official SimpleITK release (you can always access the latest version from GitHub).

1 Like