Nilearn

0.13.1 · active · verified Thu Apr 16

Nilearn is a Python library for statistical learning with neuroimaging data. It provides tools for general linear model (GLM) based analysis and leverages the scikit-learn toolbox for multivariate statistics, including predictive modeling, classification, decoding, and connectivity analysis. The current stable version is 0.13.1, and releases occur regularly, often including new features, enhancements, and deprecations.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart fetches the Haxby fMRI dataset, applies a ventral temporal mask, extracts time series data, and then visualizes the anatomical image with the mask overlay and a single fMRI volume. It demonstrates common steps of data loading, masking, and basic visualization.

import warnings
warnings.filterwarnings("ignore", message="The provided image has no sform in its header.")

from nilearn import datasets, plotting, maskers

# 1. Fetch a sample fMRI dataset (Haxby dataset)
haxby_dataset = datasets.fetch_haxby(subjects=1, fetch_stimuli=False)
fmri_filename = haxby_dataset.func[0]
anat_filename = haxby_dataset.anat[0]
mask_filename = haxby_dataset.mask_vt[0]

# 2. Extract signals using NiftiMasker
# The mask_strategy='epi' is often more robust for EPI images
masker = maskers.NiftiMasker(mask_img=mask_filename, smoothing_fwhm=6, standardize='zscore_sample')
fmri_data_masked = masker.fit_transform(fmri_filename)

# 3. Plot the anatomical image and overlay the mask
print(f"Shape of masked fMRI data: {fmri_data_masked.shape}")

# Plotting the anatomical image with the mask overlay
plotting.plot_anat(
    anat_filename,
    title="Anatomical image with mask overlay",
    display_mode='ortho',
    cut_coords=(0, 0, 0),
    output_file=None # Change to a filename like 'anat_with_mask.png' to save
)

# Plotting a single volume from the fMRI data
first_fmri_volume = image.index_img(fmri_filename, 0)
plotting.plot_img(
    first_fmri_volume,
    bg_img=anat_filename,
    title="First fMRI volume",
    display_mode='ortho',
    cut_coords=(0, 0, 0),
    output_file=None # Change to a filename like 'first_fmri_volume.png' to save
)

# You can also show the plots (usually at the end of a script or in an interactive session)
# plotting.show()

view raw JSON →