nipy / nibabel

Python package to access a cacophony of neuro-imaging file formats
http://nipy.org/nibabel/
Other
634 stars 258 forks source link

Unable to save extra information to the 'extra' field of a nifti1 image #1326

Open lxmedai opened 1 month ago

lxmedai commented 1 month ago

I tried to put some extra information to the field 'extra' (which is just an empty dict by default) by using img_nii.extra = {'Test': 'See what happens'} # img_nii is my loaded nifti1 image.

This assignment worked perfectly fine. Then I tried to save it by calling: img_nii.to_filename('myTestFilename.nii.gz') , which also worked with no errors reported. But if I tried to load the nifti1 image again by calling img_nii_new = nib.load('myTestFilename.nii.gz'), what I got in the field 'extra' of img_nii_new was simply an empty dict. What should I do in order to save extra information there? I plan to save some numpy arrays to this 'extra' field. How can I solve this problem? Any suggestions?

effigies commented 4 weeks ago

The extra dictionary is purely for passing around images in memory. You could write a NIfTI extension to pack anything you want in the header, though:

https://github.com/nipy/nibabel/blob/e6ccec4dcda98911f6ad7613ac2069736e25b144/nibabel/nifti1.py#L286-L417

The basic procedure is:

ext = nb.nifti1.Nifti1Extension(0, bytestring)  # 0 for unknown, and you need some bytestring
img.header.extensions.append(ext)

Now you can save the image, and then retrieve it on a received image with img.header.extensions[0].get_content().