Note
Go to the end to download the full example code or to run this example in your browser via Binder.
Simple example of NiftiMasker use¶
Here is a simple example of automatic mask computation using the nifti masker. The mask is computed and visualized.
Warning
If you are using Nilearn with a version older than 0.9.0,
then you should either upgrade your version or import maskers
from the input_data module instead of the maskers module.
That is, you should manually replace in the following example all occurrences of:
from nilearn.maskers import NiftiMasker
with:
from nilearn.input_data import NiftiMasker
Retrieve the brain development functional dataset
from nilearn import datasets
dataset = datasets.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 found in
/home/runner/nilearn_data/development_fmri
[fetch_development_fmri] Dataset found in
/home/runner/nilearn_data/development_fmri/development_fmri
[fetch_development_fmri] Dataset found in
/home/runner/nilearn_data/development_fmri/development_fmri
First functional nifti image (4D) is at: /home/runner/nilearn_data/development_fmri/development_fmri/sub-pixar123_task-pixar_space-MNI152NLin2009cAsym_desc-preproc_bold.nii.gz
Compute the mask
from nilearn.maskers import NiftiMasker
# As this is raw movie watching based EPI, the background is noisy and we
# cannot rely on the 'background' masking strategy. We need to use the 'epi'
# one
nifti_masker = NiftiMasker(
standardize="zscore_sample",
mask_strategy="epi",
memory="nilearn_cache",
memory_level=1,
smoothing_fwhm=8,
verbose=1,
)
nifti_masker.fit(func_filename)
mask_img = nifti_masker.mask_img_
[NiftiMasker.fit] Loading data from
'/home/runner/nilearn_data/development_fmri/development_fmri/sub-pixar123_task-p
ixar_space-MNI152NLin2009cAsym_desc-preproc_bold.nii.gz'
[NiftiMasker.fit] Computing mask
________________________________________________________________________________
[Memory] Calling nilearn.masking.compute_epi_mask...
compute_epi_mask('/home/runner/nilearn_data/development_fmri/development_fmri/sub-pixar123_task-pixar_space-MNI152NLin2009cAsym_desc-preproc_bold.nii.gz', verbose=0)
_________________________________________________compute_epi_mask - 0.4s, 0.0min
[NiftiMasker.fit] Resampling mask
________________________________________________________________________________
[Memory] Calling nilearn.image.resampling.resample_img...
resample_img(<nibabel.nifti1.Nifti1Image object at 0x7f9c6a12c160>, target_affine=None, target_shape=None, copy=False, interpolation='nearest')
_____________________________________________________resample_img - 0.0s, 0.0min
[NiftiMasker.fit] Finished fit
Visualize the mask using the plot_roi method
from nilearn.image.image import mean_img
from nilearn.plotting import plot_roi
# calculate mean image for the background
mean_func_img = mean_img(func_filename)
plot_roi(mask_img, mean_func_img, display_mode="y", cut_coords=4, title="Mask")

<nilearn.plotting.displays._slicers.YSlicer object at 0x7f9c6a0c13c0>
Visualize the mask using the ‘generate_report’ method
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.
Preprocess data with the NiftiMasker
nifti_masker.fit(func_filename)
fmri_masked = nifti_masker.transform(func_filename)
# fmri_masked is now a 2D matrix, (n_voxels x n_time_points)
[NiftiMasker.fit] Loading data from
'/home/runner/nilearn_data/development_fmri/development_fmri/sub-pixar123_task-p
ixar_space-MNI152NLin2009cAsym_desc-preproc_bold.nii.gz'
[NiftiMasker.fit] Computing mask
[NiftiMasker.fit] Resampling mask
[NiftiMasker.fit] Finished fit
________________________________________________________________________________
[Memory] Calling nilearn.maskers.nifti_masker.filter_and_mask...
filter_and_mask('/home/runner/nilearn_data/development_fmri/development_fmri/sub-pixar123_task-pixar_space-MNI152NLin2009cAsym_desc-preproc_bold.nii.gz',
<nibabel.nifti1.Nifti1Image object at 0x7f9c47f89ba0>, { 'clean_args': None,
'clean_kwargs': {},
'cmap': 'gray',
'detrend': False,
'dtype': None,
'high_pass': None,
'high_variance_confounds': False,
'low_pass': None,
'reports': True,
'runs': None,
'smoothing_fwhm': 8,
'standardize': 'zscore_sample',
'standardize_confounds': True,
't_r': None,
'target_affine': None,
'target_shape': None}, memory_level=1, memory=Memory(location=nilearn_cache/joblib), verbose=1, confounds=None, sample_mask=None, copy=True, dtype=None, sklearn_output_config=None)
[NiftiMasker.wrapped] Loading data from <nibabel.nifti1.Nifti1Image object at
0x7f9c47d1feb0>
[NiftiMasker.wrapped] Smoothing images
[NiftiMasker.wrapped] Extracting region signals
[NiftiMasker.wrapped] Cleaning extracted signals
__________________________________________________filter_and_mask - 1.3s, 0.0min
Run an algorithm
from sklearn.decomposition import FastICA
n_components = 10
ica = FastICA(
n_components=n_components, random_state=42, tol=0.001, max_iter=2000
)
components_masked = ica.fit_transform(fmri_masked.T).T
/home/runner/work/nilearn/nilearn/.tox/doc/lib/python3.10/site-packages/sklearn/decomposition/_fastica.py:127: ConvergenceWarning: FastICA did not converge. Consider increasing tolerance or the maximum number of iterations.
warnings.warn(
Reverse masking, and display the corresponding map
components = nifti_masker.inverse_transform(components_masked)
from nilearn.image import index_img
# Visualize results
from nilearn.plotting import plot_stat_map, show
# calculate mean image for the background
mean_func_img = mean_img(func_filename)
plot_stat_map(
index_img(components, 0),
mean_func_img,
display_mode="y",
cut_coords=4,
title="Component 0",
)
show()

[NiftiMasker.inverse_transform] Computing image from signals
________________________________________________________________________________
[Memory] Calling nilearn.masking.unmask...
unmask(array([[0.244354, ..., 2.145976],
...,
[0.500638, ..., 0.718085]], shape=(10, 24256)),
<nibabel.nifti1.Nifti1Image object at 0x7f9c47f89ba0>)
___________________________________________________________unmask - 0.2s, 0.0min
Total running time of the script: (0 minutes 22.398 seconds)
Estimated memory usage: 668 MB