NiBabel
NiBabel is an active Python package that provides read and write access to a wide array of neuroimaging file formats, including NIfTI, ANALYZE, GIFTI, MINC, MGH, ECAT, Philips PAR/REC, AFNI BRIK/HEAD, and CIFTI-2, with limited support for DICOM. It enables users to interact with image data as NumPy arrays and access format-specific metadata through structured headers. Currently at version 5.4.2, NiBabel maintains a consistent release cadence with frequent bug-fix and feature updates.
Warnings
- deprecated The `get_data()` method for accessing image data is deprecated. It returns a `numpy.ndarray` for in-memory data but an `ArrayProxy` for memory-mapped data, leading to inconsistent behavior.
- breaking NiBabel 6.0 (expected after 5.x series) will drop support for NumPy 1.x, requiring NumPy 2.0 or later.
- gotcha Minimum Python and NumPy version requirements have increased across major/minor releases. For example, NiBabel 5.4.x requires Python 3.10+ and NumPy 1.25+.
- deprecated The `nibabel.onetime.auto_attr` module is deprecated. Its functionality is now available in the standard library.
- breaking Attempting to set the qform (quaternion form) that fails decomposition will now raise a more specific `nibabel.spatialimages.HeaderDataError` instead of a generic `numpy.linalg.LinAlgError`.
Install
-
pip install nibabel
Imports
- nibabel
import nibabel as nib
- Nifti1Image
from nibabel.nifti1 import Nifti1Image
Quickstart
import nibabel as nib
import numpy as np
import os
# Create a dummy NIfTI image for demonstration
data = np.arange(27, dtype=np.int16).reshape((3, 3, 3))
affine = np.diag([2, 2, 2, 1])
img = nib.Nifti1Image(data, affine)
# Save the dummy image
output_filename = 'dummy_image.nii.gz'
nib.save(img, output_filename)
print(f"Saved dummy image to {output_filename}")
# Load the image
loaded_img = nib.load(output_filename)
# Access image data as a NumPy array
image_data = loaded_img.get_fdata()
print(f"Loaded image shape: {image_data.shape}")
print(f"Loaded image data type: {image_data.dtype}")
# Access the affine transformation matrix
image_affine = loaded_img.affine
print(f"Loaded image affine:\n{image_affine}")
# Clean up the dummy file
os.remove(output_filename)
print(f"Cleaned up {output_filename}")