'Memmap AttributeError when trying to access nifti image header

After loading a NIFTI (.nii) image (using Nibabel) with the code scan = nibabel.load(filepath), it is useful to display the image header information via scan.header.

If you call scan.get_fdata() before calling scan.header, the error arises: AttributeError: 'memmap' object has no attribute 'header'. Example of such code:

scan = nibabel.load(test_image.nii)
scan_volume_data = scan.get_fdata()
print(scan.header)


Solution 1:[1]

You have to call scan.header before calling scan.get_fdata(). This is because after calling scan.get_fdata(), the image object gets transformed to a memmap (memory-map) object, which loses the header information. Example of correct code is the following:

scan = nibabel.load(test_image.nii)
print(scan.header)
scan_volume_data = scan.get_fdata()

We can observe the change of the image datatype with the following code:

scan = nibabel.load(test_image.nii)
print(type(scan)) # <class 'numpy.memmap'>
scan_volume_data = scan.get_fdata()
print(type(scan)) # <class 'nibabel.nifti1.Nifti1Image'>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nimantha