Note
Go to the end to download the full example code. or to run this example in your browser via Binder
Extracting signals from brain regions using the NiftiLabelsMasker¶
This simple example shows how to extract signals from functional
fMRI data and brain regions defined through an atlas.
More precisely, this example shows how to use the
NiftiLabelsMasker object to perform this
operation in just a few lines of code.
Retrieve the brain development functional dataset¶
We start by fetching the brain development functional dataset and we restrict the example to one subject only.
from nilearn.datasets import fetch_atlas_harvard_oxford, fetch_development_fmri
dataset = fetch_development_fmri(n_subjects=1)
func_filename = dataset.func[0]
# print basic information on the dataset
print(f"First functional nifti image (4D) is at: {func_filename}")
[fetch_development_fmri] Dataset directory found: /home/runner/work/nilearn/nilearn/nilearn_data/development_fmri
First functional nifti image (4D) is at: /home/runner/work/nilearn/nilearn/nilearn_data/development_fmri/sub-pixar123_task-pixar_space-MNI152NLin2009cAsym_desc-preproc_bold.nii.gz
Load an atlas¶
We then load the Harvard-Oxford atlas to define the brain regions and the first label correspond to the background.
atlas = fetch_atlas_harvard_oxford("cort-maxprob-thr25-2mm")
print(f"The atlas contains {len(atlas.labels) - 1} non-overlapping regions")
[fetch_atlas_harvard_oxford] Dataset directory found: /home/runner/work/nilearn/nilearn/nilearn_data/fsl
The atlas contains 48 non-overlapping regions
Instantiate the mask and visualize atlas¶
Instantiate the masker with label image and label values.
We use standardize="zscore_sample"
so that the extracted time-series are shifted to zero mean
and scaled to unit variance.
detrend=True is used to remove linear trends in the signal.
from nilearn.maskers import NiftiLabelsMasker
masker = NiftiLabelsMasker(
atlas.maps,
lut=atlas.lut,
standardize="zscore_sample",
detrend=True,
verbose=1,
)
Visualize the atlas¶
We need to call fit prior to generating the mask.
We can then generate a report to visualize the atlas.
Here we use the ‘brainsprite’ engine
that gives an interactive visualization
instead of the static one generated
by the matplotlib engine.
Note
The generated report can be:
displayed in a Notebook,
opened in a browser using the
.open_in_browser()method,or saved to a file using the
.save_as_html(output_filepath)method.
masker.fit()
report = masker.generate_report(engine="brainsprite")
report
[NiftiLabelsMasker.fit] Loading regions from <nibabel.nifti1.Nifti1Image object at 0x7fa18ae7e290>
[NiftiLabelsMasker.fit] Finished fit
/home/runner/work/nilearn/nilearn/.tox/doc/lib/python3.11/site-packages/numpy/core/fromnumeric.py:771: UserWarning:
Warning: 'partition' will ignore the 'mask' of the MaskedArray.
/home/runner/work/nilearn/nilearn/examples/06_manipulating_images/plot_nifti_labels_simple.py:73: UserWarning:
No image provided to fit in NiftiLabelsMasker. Plotting ROIs of label image on the MNI152Template for reporting.
Fitting the masker on data and generating a report¶
We can again generate a report, but this time, the provided functional image is displayed with the ROI of the atlas. The report also contains a summary table giving the region sizes in mm3.
[NiftiLabelsMasker.fit] Loading data from sub-pixar123_task-...
[NiftiLabelsMasker.fit] Loading regions from <nibabel.nifti1.Nifti1Image object at 0x7fa18ae7e290>
[NiftiLabelsMasker.fit] Resampling regions
[NiftiLabelsMasker.fit] Finished fit
Process the data with the NiftiLabelsMasker¶
In order to extract the signals, we need to call transform on the
functional data.
signals = masker.transform(func_filename)
# signals is a 2D numpy array, (n_time_points x n_regions)
print(f"{signals.shape=}")
[NiftiLabelsMasker.wrapped] Loading data from sub-pixar123_task-...
[NiftiLabelsMasker.wrapped] Extracting region signals
[NiftiLabelsMasker.wrapped] Cleaning extracted signals
signals.shape=(168, 48)
Output to dataframe and plot¶
You can use set_output
to decide the output format of transform.
If you want to output to a DataFrame, you can choose
"pandas" or "polars".
from nilearn.plotting import show
masker.set_output(transform="pandas")
signals_df = masker.transform(func_filename)
print(signals_df.head())
signals_df[["Frontal Pole", "Insular Cortex", "Superior Frontal Gyrus"]].plot(
title="Signals from 3 regions", figsize=(15, 5)
)
show()

[NiftiLabelsMasker.wrapped] Loading data from sub-pixar123_task-...
[NiftiLabelsMasker.wrapped] Extracting region signals
[NiftiLabelsMasker.wrapped] Cleaning extracted signals
Frontal Pole Insular Cortex ... Supracalcarine Cortex Occipital Pole
0 0.786647 -0.475993 ... -3.151791 -1.222847
1 0.427424 -0.940412 ... -1.680400 -1.668592
2 -0.598958 -1.404831 ... -0.357431 -1.359115
3 0.087524 -0.469319 ... 0.594483 -2.010538
4 -0.119027 -0.401370 ... 0.210600 -2.189545
[5 rows x 48 columns]
Total running time of the script: (0 minutes 5.680 seconds)
Estimated memory usage: 332 MB