Written and maintained by CASRAI Editorial Board
Published · Last updated
On this page
nibabel is a free Python package that reads and writes neuroimaging file formats, including NIfTI, and hands the image to you as a NumPy array together with an affine matrix and the file header. In a research pipeline it is the layer that turns a file such as sub-01_bold.nii.gz into numbers you can check, mask, average and save again without losing the spatial information. You install it with pip install nibabel, load an image with nib.load(), and read img.shape, img.affine and img.header before you analyse anything.
What nibabel is used for in research
The nibabel home page describes the package as read and write access to common neuroimaging file formats: ANALYZE (plain, SPM99, SPM2 and later), GIFTI, NIfTI1, NIfTI2, CIFTI-2, MINC1, MINC2, AFNI BRIK/HEAD, ECAT and Philips PAR/REC, plus FreeSurfer MGH, geometry, annotation and morphometry files. DICOM support is described as limited. The image data are exposed as NumPy arrays, and the header can be read in full or selectively. The package is released under the MIT licence (with some BSD-licensed code), and releases carry a Zenodo DOI badge in the release notes, which is the route to cite the exact version you used.
That makes nibabel a plumbing tool rather than an analysis package. Typical research uses are checking that a converted scan has the voxel size and orientation you expect, extracting a region-of-interest time series with NumPy, building a binary mask and writing it back as a NIfTI file another program can open, and sanity-checking images before a large preprocessing run. It is the right starting point when your lab has a custom analysis in Python and needs to get images in and out of it. If you instead need a ready-made preprocessing workflow, see the guides on fMRIPrep and the FMRIB Software Library (FSL); if you start from scanner DICOM files, dcm2niix converts them to NIfTI, which nibabel then reads.
The three things every nibabel image holds
The nibabel documentation defines an image as the association of three things: an N-dimensional array containing the image data, a 4 by 4 affine matrix mapping array coordinates to coordinates in a RAS+ world space, and image metadata in the form of a header. Most analysis mistakes with neuroimaging files come from using the array and forgetting the other two, which is why the worked example below prints all three before it computes anything.
Install or access nibabel
The nibabel installation page describes the package as pure Python and gives the standard command:
pip install nibabel
If pip reports a permission error, the same page recommends installing with the --user flag or inside a virtual environment. On Debian and Ubuntu, the page also lists a NeuroDebian package (apt-get install python-nibabel). The home page gives two further commands: pip install git+https://github.com/nipy/nibabel for the development version, and pip install nibabel[test] to add the test dependencies, after which pytest --pyargs nibabel runs the test suite.
Requirements
The installation page lists Python 3.10 or newer, NumPy 1.25 or newer and Packaging 20.0 or newer as requirements. The Python Package Index metadata for release 5.5.0, checked on the same day, lists Python 3.11 or newer, so read the requirement on the PyPI page for the exact release you install. Three optional packages unlock specific formats: SciPy 1.11 or newer for SPM-style ANALYZE files, h5py 3.8 or newer for MINC2, and PyDICOM 2.3.0 or newer for the DICOM reader. The data table below lists these minimums side by side.
Check that it works
The installation page suggests two checks. import nibabel in a Python session confirms the package imports, and python -c "import nibabel; nibabel.test()" runs the bundled tests (this needs the test extra described above).
Step-by-step: load, inspect and save a NIfTI image
The steps below use the example file example4d.nii.gz that ships inside the nibabel package and is used throughout the official documentation, so you can follow along without any of your own data. The sequence is: load, inspect shape and type, check voxel size and orientation, extract the array, compute something with NumPy, then save a new image on the same grid.
- Import and locate the file.
import os, numpy as np, nibabel as nib, thenfrom nibabel.testing import data_pathandfname = os.path.join(data_path, 'example4d.nii.gz'). Thenibabel.testingmodule is part of the test tooling, so installnibabel[test]if the import fails. For your own scans, replacefnamewith the path to your NIfTI file. - Load the image.
img = nib.load(fname). nibabel works out the format from the file name. Loading does not read the voxel data into memory yet. - Inspect without loading data.
img.shapegives(128, 96, 24, 2)for this file,img.get_data_dtype()reports the stored type (16-bit signed integers here), andimg.affine.shapeis(4, 4). The documentation notes that this information is available without loading the main image data. - Check the header.
hdr = img.header, thenhdr.get_zooms()for voxel sizes andhdr.get_xyzt_units()for the spatial and time units, which is('mm', 'sec')for this file. - Check the orientation.
nib.aff2axcodes(img.affine)returns the axis codes nearest to each voxel axis; for this file it is('L', 'A', 'S'). To reorder the voxel axes as close as possible to RAS+, usenib.as_closest_canonical(img). - Get the array.
data = img.get_fdata()returns a floating-point NumPy array (64-bit by default) and, on a proxy image, keeps a cached copy for later calls. - Compute with NumPy. For example, build a mask from the temporal mean and average the voxels inside it at each time point:
mean_vol = data.mean(axis=-1),mask = mean_vol > mean_vol.mean(),ts = data[mask].mean(axis=0). - Save a new image on the same grid.
mask_img = nib.Nifti1Image(mask.astype(np.uint8), img.affine)andnib.save(mask_img, 'mask.nii.gz'). Passing the original affine is what keeps the mask aligned with the source scan; the new header is initialised from the array (shape and data type) with defaults for everything else.
What this produced when run
Running exactly this sequence with nibabel 5.5.0 gave a mask of shape (128, 96, 24) with 102,241 voxels above the whole-volume mean of the temporal-mean image, a time series of length 2 (the file has two volumes), and a saved mask.nii.gz that reloads with the same shape and an affine equal to the source image’s. The mask is a toy threshold chosen to show the mechanics; it is not a recommended brain-extraction method.
Output: how to read shape, affine and header
Treat the output of the inspection steps as a checklist to run before every analysis.
Shape and data type
The shape is the array dimensions: three spatial axes, and for functional data a fourth axis of volumes. For example4d.nii.gz that is 128 by 96 by 24 voxels and 2 volumes. The documented NIfTI1 header listing shows the same numbers in its dim field ([4 128 96 24 2 1 1 1], where the first value is the number of dimensions) and the stored type in datatype (int16).
Voxel size
header.get_zooms() returns the voxel sizes; the documentation describes the first three as millimetres and the last as the time between scans, the equivalent of voxel size on the time axis. For the example file the zooms are about 2.0, 2.0, 2.2 and 2000.0. Notice that the documentation describes the fourth value as milliseconds while get_xyzt_units() on the same file reports ('mm', 'sec'). Do not assume the time unit; read it from get_xyzt_units() for your file and confirm it against your acquisition protocol.
Affine and orientation
The affine stores the relationship between voxel coordinates in the array and coordinates in the reference space, and nibabel’s world axes are always RAS+ (left to Right, posterior to Anterior, inferior to Superior). The documentation makes the key point that a voxel coordinate on its own tells you almost nothing about where the data came from in the scanner; the affine supplies that. This is also why two images of the same person, such as an EPI volume (shape 53 by 61 by 33 in the docs’ worked example) and an anatomical scan (57 by 67 by 56), cannot be compared voxel by voxel: they have different fields of view and orientations, and only the affine relates each to the shared reference space.
Raw header access
img.header.structarr gives the raw header fields, for example raw['xyzt_units']. The documentation says plainly that this lowest level is for people who know the file format well and comes without any safety net. For routine edits use the setter methods, which the documentation says keep the header compliant with the format specification.
Memory, slicing and the image cache
By default, the first get_fdata() call on a proxy image fills an internal cache, and later calls return that same array. The documentation points out the consequence: if you modify the returned array, the cached copy changes too, and img.uncache() discards the cache. To save memory you have three documented options: call img.uncache(), read with np.asarray(img.dataobj) so nothing is cached, or call get_fdata(caching='unchanged') so an empty cache stays empty. img.in_memory tells you whether the array is currently cached.
For large 4D files you often need only part of the data. Slicing the array proxy, or using img.slicer, loads only what you ask for. The documentation shows img.slicer[..., 0] returning the first volume as a new image with shape (128, 96, 24), and img.slicer[32:-32, ...] cropping the first axis while adjusting the affine so that data at a given RAS+ location do not move (the X translation changes by 64 mm for that crop). Taking every second voxel with an integer step downsamples without filtering, and the documentation warns this induces aliasing along the downsampled axes.
Troubleshooting
pip reports a permission error
Use pip install --user nibabel or create a virtual environment, as the installation page advises.
ImportError for nibabel.testing or a missing pytest
The nibabel.testing module (where the example file lives) imports pytest; with a plain pip install nibabel in a fresh environment this import failed in a check run for this page, and installing nibabel[test] fixed it. Your own analysis code does not need nibabel.testing.
A format will not open
Some formats depend on optional packages: SciPy for SPM-style ANALYZE, h5py for MINC2 and PyDICOM for DICOM. Install the one listed in the data table and retry. For DICOM series from a scanner, converting to NIfTI first with dcm2niix is the usual research route, since nibabel’s DICOM support is described as limited.
Your mask or ROI is in the wrong place
Check nib.aff2axcodes(img.affine) for each image and compare the affines. Images on different grids cannot be combined voxel by voxel. If the orientation codes differ, nib.as_closest_canonical() reorders the axes, but it does not resample one image onto another’s grid.
Memory errors on large 4D data
Slice the proxy, use caching='unchanged', or call uncache() as described above.
Which version did I use?
nib.__version__ prints the installed version. Record it in your methods section, together with the Zenodo DOI from the release notes for that version.
Free alternatives and neighbours
nibabel handles file input and output and array access. If you need statistical modelling or registration, other free tools do that work. The table lists two Python options, with each description taken from the project’s own home page.
| Tool | What the project says it does | Relation to nibabel |
|---|---|---|
| Nilearn | Approachable and versatile analyses of brain volumes and surfaces, with statistical and machine-learning tools, including GLM-based analysis and decoding. | Higher-level analysis and plotting; use it when you want statistical or machine-learning workflows rather than raw file access. |
| SimpleITK | Open-source multi-dimensional image analysis in Python, R, Java, C#, Lua, Ruby, TCL and C++, treating images as spatial objects in physical space, with registration and segmentation tools. | General biomedical image analysis and registration beyond neuroimaging file handling. |
For viewing images, the MRIcroGL guide covers a free viewer, and for sharing a finished dataset in a standard layout, see the guide to OpenNeuro and BIDS neuroimaging data sharing.
Frequently asked questions
What is nibabel used for?
nibabel reads and writes neuroimaging file formats such as NIfTI, GIFTI, CIFTI-2, MINC and AFNI files in Python and returns image data as NumPy arrays with access to the affine and header, according to its official documentation.
How do I install nibabel?
Run pip install nibabel, using --user or a virtual environment if you see a permission error. The installation page also lists a NeuroDebian package for Debian and Ubuntu, and pip install nibabel[test] adds the test dependencies.
How do I open a NIfTI file with nibabel?
Use img = nib.load('file.nii.gz'), then img.get_fdata() for the array, img.affine for the voxel-to-world matrix and img.header for the metadata.
Does nibabel load the whole image when I call load?
No. Loading creates an image object whose data are an array proxy; the array is read when you ask for it, for example with get_fdata(), which caches the result by default.
Does nibabel read DICOM files?
The documentation describes DICOM support as limited and lists PyDICOM 2.3.0 or newer as the optional dependency for it. Many labs convert DICOM to NIfTI first.
How do I cite nibabel?
Cite the exact version you ran. The release notes carry a Zenodo DOI badge for each release, and nib.__version__ reports the installed version.
Sources
- NiBabel documentation home page, https://nipy.org/nibabel/ (read 2026-11-14)
- NiBabel installation, https://nipy.org/nibabel/installation.html (read 2026-11-14)
- NiBabel getting started, https://nipy.org/nibabel/gettingstarted.html (read 2026-11-14)
- Nibabel images, https://nipy.org/nibabel/nibabel_images.html (read 2026-11-14)
- Coordinate systems and affines, https://nipy.org/nibabel/coordinate_systems.html (read 2026-11-14)
- Image voxel orientation, https://nipy.org/nibabel/image_orientation.html (read 2026-11-14)
- Images and memory, https://nipy.org/nibabel/images_and_memory.html (read 2026-11-14)
- nibabel on the Python Package Index, https://pypi.org/project/nibabel/ (read 2026-11-14)
- Nilearn home page, https://nilearn.github.io/stable/index.html (read 2026-11-14)
- SimpleITK home page, https://simpleitk.org/ (read 2026-11-14)
Data: nibabel software requirements and optional format dependencies
Minimum versions of the Python interpreter, NumPy, Packaging and the optional packages that unlock specific file formats in nibabel, compiled from the official nibabel installation page and the formats list on the project home page.
Period covered: nibabel 5.5.0.
| Component | Minimum version | Needed for | Required or optional |
|---|---|---|---|
| Python | 3.10 (installation page); PyPI metadata for 5.5.0 lists 3.11 | Running nibabel | Required |
| NumPy | 1.25 | Image data as arrays | Required |
| Packaging | 20.0 | Version handling inside nibabel | Required |
| SciPy | 1.11 | SPM ANALYZE files | Optional |
| h5py | 3.8 | MINC2 files | Optional |
| PyDICOM | 2.3.0 | DICOM reading (limited support) | Optional |
Sources
- NiBabel installation (accessed 2026-11-14)
- NiBabel home page (accessed 2026-11-14)
- nibabel on PyPI (accessed 2026-11-14)
Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.







