NiBabel

5.4.2 · active · verified Sat Apr 11

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

Install

Imports

Quickstart

This quickstart demonstrates how to create a simple NIfTI image, save it to disk, then load it back into NiBabel. It shows how to access the image's data as a NumPy array and retrieve its affine transformation matrix. Finally, it cleans up the created dummy file.

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}")

view raw JSON →