.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_examples/06_manipulating_images/plot_mask_computation.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note :ref:`Go to the end ` to download the full example code. or to run this example in your browser via Binder .. rst-class:: sphx-glr-example-title .. _sphx_glr_auto_examples_06_manipulating_images_plot_mask_computation.py: Understanding NiftiMasker and mask computation ============================================== In this example, the NiftiMasker is used to automatically compute a mask. * The default strategy is based on the background. * Another option is to use a template. * For raw EPI, as in :term:`resting-state` or movie watching time series, we need to use the 'epi' strategy of the NiftiMasker. In addition, we show here how to tweak the different parameters of the underlying routine that extract masks from EPI :func:`~nilearn.masking.compute_epi_mask`. .. GENERATED FROM PYTHON SOURCE LINES 21-29 Computing a mask from the background ------------------------------------ The default strategy to compute a mask is to try to detect the background. With data that has already been masked this should work well, as it relies on a homogeneous background .. GENERATED FROM PYTHON SOURCE LINES 31-36 Fetch the dataset ^^^^^^^^^^^^^^^^^ We fetch do some basic visualization of the image we will be using. .. GENERATED FROM PYTHON SOURCE LINES 36-53 .. code-block:: Python from nilearn.datasets import fetch_miyawaki2008 from nilearn.image import mean_img from nilearn.plotting import plot_epi, show miyawaki_dataset = fetch_miyawaki2008() print( "First functional nifti image (4D) is located " f"at: {miyawaki_dataset.func[0]}" ) miyawaki_filename = miyawaki_dataset.func[0] miyawaki_mean_img = mean_img(miyawaki_filename) plot_epi(miyawaki_mean_img, title="Mean EPI image") show() .. image-sg:: /auto_examples/06_manipulating_images/images/sphx_glr_plot_mask_computation_001.png :alt: plot mask computation :srcset: /auto_examples/06_manipulating_images/images/sphx_glr_plot_mask_computation_001.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none [fetch_miyawaki2008] Dataset directory found: /home/runner/work/nilearn/nilearn/nilearn_data/miyawaki2008 First functional nifti image (4D) is located at: /home/runner/work/nilearn/nilearn/nilearn_data/miyawaki2008/func/data_figure_run01.nii.gz .. GENERATED FROM PYTHON SOURCE LINES 54-58 A NiftiMasker with the default strategy --------------------------------------- Let's use the NiftiMasker with its defaults parameters. .. GENERATED FROM PYTHON SOURCE LINES 58-62 .. code-block:: Python from nilearn.maskers import NiftiMasker masker = NiftiMasker() .. GENERATED FROM PYTHON SOURCE LINES 63-65 .. include:: ../../../examples/html_repr_note.rst .. GENERATED FROM PYTHON SOURCE LINES 66-68 .. code-block:: Python masker .. raw:: html
NiftiMasker()
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.


.. GENERATED FROM PYTHON SOURCE LINES 69-71 .. code-block:: Python masker.fit(miyawaki_filename) .. raw:: html
NiftiMasker()
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.


.. GENERATED FROM PYTHON SOURCE LINES 72-78 .. note :: You can also note that after fitting, the HTML representation of the estimator looks different than before fitting. .. GENERATED FROM PYTHON SOURCE LINES 80-93 Visualize the mask ^^^^^^^^^^^^^^^^^^ We can quickly get an idea about the estimated mask for this functional image by plotting the mask. We get the estimated mask from the ``mask_img_`` attribute of the masker: the final ``_`` of this attribute name means it was generated by the :meth:`~nilearn.maskers.NiftiMasker.fit` method. We can then plot it using the :func:`~nilearn.plotting.plot_roi` function with the mean functional image as background. .. GENERATED FROM PYTHON SOURCE LINES 93-102 .. code-block:: Python from nilearn.plotting import plot_roi plot_roi( masker.mask_img_, miyawaki_mean_img, title="Mask from already masked data" ) # display the image show() .. image-sg:: /auto_examples/06_manipulating_images/images/sphx_glr_plot_mask_computation_002.png :alt: plot mask computation :srcset: /auto_examples/06_manipulating_images/images/sphx_glr_plot_mask_computation_002.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 103-110 View the generated mask ^^^^^^^^^^^^^^^^^^^^^^^ More information can be obtained about the masker and its mask by generating a masker report. This can be done using the :meth:`~nilearn.maskers.NiftiMasker.generate_report` method. .. GENERATED FROM PYTHON SOURCE LINES 110-112 .. code-block:: Python report = masker.generate_report(engine="brainsprite") .. rst-class:: sphx-glr-script-out .. code-block:: none /home/runner/work/nilearn/nilearn/.tox/doc/lib/python3.10/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_mask_computation.py:110: UserWarning: Resampling binary images with continuous or linear interpolation. This might lead to unexpected results. You might consider using nearest interpolation instead. .. GENERATED FROM PYTHON SOURCE LINES 113-115 .. include:: ../../../examples/report_note.rst .. GENERATED FROM PYTHON SOURCE LINES 116-119 .. code-block:: Python report .. raw:: html

NiftiMasker Applying a mask to extract time-series from Niimg-like objects. NiftiMasker is useful when preprocessing (detrending, standardization, resampling, etc.) of in-mask :term:`voxels` is necessary. Use case: working with time series of :term:`resting-state` or task maps.

Opacity

This report shows the input Nifti image overlaid with the outlines of the mask. We recommend to inspect the report for the overlap between the mask and the input image.

The mask includes 5438 voxels (4.4 %) of the image.

Value
Parameter
cmap gray
detrend False
high_variance_confounds False
mask_strategy background
memory_level 1
reports True
standardize False
standardize_confounds True
verbose 0


.. GENERATED FROM PYTHON SOURCE LINES 120-126 Computing a mask from raw :term:`EPI` data ------------------------------------------ From raw :term:`EPI` data, there is no uniform background, and a different strategy is necessary. .. GENERATED FROM PYTHON SOURCE LINES 128-135 Fetch the dataset ^^^^^^^^^^^^^^^^^ Here we fetch the movie watching based brain development fMRI dataset and once again do some basic visualization of the data. Here we only work with the first 100 volumes of the image to speed up computation. .. GENERATED FROM PYTHON SOURCE LINES 135-149 .. code-block:: Python from nilearn.datasets import fetch_development_fmri from nilearn.image import index_img dataset = fetch_development_fmri(n_subjects=1) epi_filename = dataset.func[0] epi_img = index_img(epi_filename, slice(0, 100)) mean_func_img = mean_img(epi_img) plot_epi(mean_func_img, title="Mean EPI image") show() .. image-sg:: /auto_examples/06_manipulating_images/images/sphx_glr_plot_mask_computation_003.png :alt: plot mask computation :srcset: /auto_examples/06_manipulating_images/images/sphx_glr_plot_mask_computation_003.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none [fetch_development_fmri] Dataset directory found: /home/runner/work/nilearn/nilearn/nilearn_data/development_fmri .. GENERATED FROM PYTHON SOURCE LINES 150-155 Simple mask extraction from :term:`EPI` images ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ We need to specify an ``'epi'`` mask_strategy, as this is raw :term:`EPI` data .. GENERATED FROM PYTHON SOURCE LINES 155-161 .. code-block:: Python masker = NiftiMasker(mask_strategy="epi") masker.fit(epi_img) report = masker.generate_report(engine="brainsprite") report .. rst-class:: sphx-glr-script-out .. code-block:: none /home/runner/work/nilearn/nilearn/.tox/doc/lib/python3.10/site-packages/numpy/core/fromnumeric.py:771: UserWarning: Warning: 'partition' will ignore the 'mask' of the MaskedArray. .. raw:: html

NiftiMasker Applying a mask to extract time-series from Niimg-like objects. NiftiMasker is useful when preprocessing (detrending, standardization, resampling, etc.) of in-mask :term:`voxels` is necessary. Use case: working with time series of :term:`resting-state` or task maps.

Opacity

This report shows the input Nifti image overlaid with the outlines of the mask. We recommend to inspect the report for the overlap between the mask and the input image.

The mask includes 24428 voxels (16.6 %) of the image.

Value
Parameter
cmap gray
detrend False
high_variance_confounds False
mask_strategy epi
memory_level 1
reports True
standardize False
standardize_confounds True
verbose 0


.. GENERATED FROM PYTHON SOURCE LINES 162-172 Generate mask with strong opening --------------------------------- We can fine-tune the outline of the mask by increasing the number of opening steps (``opening=10``) using the ``mask_args`` argument of the NiftiMasker. This effectively performs :term:`erosion` and :term:`dilation` operations on the outer voxel layers of the mask, which can for example remove remaining skull parts in the image. .. GENERATED FROM PYTHON SOURCE LINES 172-178 .. code-block:: Python masker = NiftiMasker(mask_strategy="epi", mask_args={"opening": 10}) masker.fit(epi_img) report = masker.generate_report(engine="brainsprite") report .. raw:: html

NiftiMasker Applying a mask to extract time-series from Niimg-like objects. NiftiMasker is useful when preprocessing (detrending, standardization, resampling, etc.) of in-mask :term:`voxels` is necessary. Use case: working with time series of :term:`resting-state` or task maps.

Opacity

This report shows the input Nifti image overlaid with the outlines of the mask. We recommend to inspect the report for the overlap between the mask and the input image.

The mask includes 11617 voxels (7.9 %) of the image.

Value
Parameter
cmap gray
detrend False
high_variance_confounds False
mask_args {'opening': 10}
mask_strategy epi
memory_level 1
reports True
standardize False
standardize_confounds True
verbose 0


.. GENERATED FROM PYTHON SOURCE LINES 179-190 Generate mask with a high lower cutoff -------------------------------------- The NiftiMasker calls the :func:`~nilearn.masking.compute_epi_mask` function to compute the mask from the EPI. It has two important parameters: ``lower_cutoff`` and ``upper_cutoff``. These set the grey-value bounds in which the masking algorithm will search for its threshold (0 being the minimum of the image and 1 the maximum). We will here increase the lower cutoff to enforce selection of those voxels that appear as bright in the :term:`EPI` image. .. GENERATED FROM PYTHON SOURCE LINES 190-199 .. code-block:: Python masker = NiftiMasker( mask_strategy="epi", mask_args={"upper_cutoff": 0.9, "lower_cutoff": 0.8, "opening": False}, ) masker.fit(epi_img) report = masker.generate_report(engine="brainsprite") report .. raw:: html

NiftiMasker Applying a mask to extract time-series from Niimg-like objects. NiftiMasker is useful when preprocessing (detrending, standardization, resampling, etc.) of in-mask :term:`voxels` is necessary. Use case: working with time series of :term:`resting-state` or task maps.

Opacity

This report shows the input Nifti image overlaid with the outlines of the mask. We recommend to inspect the report for the overlap between the mask and the input image.

The mask includes 24809 voxels (16.8 %) of the image.

Value
Parameter
cmap gray
detrend False
high_variance_confounds False
mask_args {'upper_cutoff': 0.9, 'lower_cutoff': 0.8, 'opening': False}
mask_strategy epi
memory_level 1
reports True
standardize False
standardize_confounds True
verbose 0


.. GENERATED FROM PYTHON SOURCE LINES 200-209 Computing the mask from the :term:`MNI` template ------------------------------------------------ A mask can also be computed from the :term:`MNI` template. In this case, it is resampled to the target image. Three options are available: ``'whole-brain-template'``, ``'gm-template'``, and ``'wm-template'`` depending on whether the whole-brain, gray matter, or white matter template should be used. .. GENERATED FROM PYTHON SOURCE LINES 209-215 .. code-block:: Python masker = NiftiMasker(mask_strategy="whole-brain-template") masker.fit(epi_img) report = masker.generate_report(engine="brainsprite") report .. rst-class:: sphx-glr-script-out .. code-block:: none /home/runner/work/nilearn/nilearn/.tox/doc/lib/python3.10/site-packages/numpy/core/fromnumeric.py:771: UserWarning: Warning: 'partition' will ignore the 'mask' of the MaskedArray. .. raw:: html

NiftiMasker Applying a mask to extract time-series from Niimg-like objects. NiftiMasker is useful when preprocessing (detrending, standardization, resampling, etc.) of in-mask :term:`voxels` is necessary. Use case: working with time series of :term:`resting-state` or task maps.

Opacity

This report shows the input Nifti image overlaid with the outlines of the mask. We recommend to inspect the report for the overlap between the mask and the input image.

The mask includes 21781 voxels (14.8 %) of the image.

Value
Parameter
cmap gray
detrend False
high_variance_confounds False
mask_strategy whole-brain-template
memory_level 1
reports True
standardize False
standardize_confounds True
verbose 0


.. GENERATED FROM PYTHON SOURCE LINES 216-228 Compute and resample a mask --------------------------- NiftiMasker also allows passing parameters directly to :func:`~nilearn.image.resample_img`. We can specify a ``target_affine``, a ``target_shape``, or both. For more information on these arguments, see :doc:`plot_affine_transformation`. The NiftiMasker report allows us to see the mask before and after resampling. Simply hover over the report to see the mask from the original image. .. GENERATED FROM PYTHON SOURCE LINES 228-236 .. code-block:: Python import numpy as np masker = NiftiMasker(mask_strategy="epi", target_affine=np.eye(3) * 8) masker.fit(epi_img) report = masker.generate_report(engine="brainsprite") report .. rst-class:: sphx-glr-script-out .. code-block:: none /home/runner/work/nilearn/nilearn/.tox/doc/lib/python3.10/site-packages/numpy/core/fromnumeric.py:771: UserWarning: Warning: 'partition' will ignore the 'mask' of the MaskedArray. .. raw:: html

NiftiMasker Applying a mask to extract time-series from Niimg-like objects. NiftiMasker is useful when preprocessing (detrending, standardization, resampling, etc.) of in-mask :term:`voxels` is necessary. Use case: working with time series of :term:`resting-state` or task maps.

Opacity

This report shows the input Nifti image overlaid with the outlines of the mask. We recommend to inspect the report for the overlap between the mask and the input image.

The mask includes 3040 voxels (15.0 %) of the image.

Value
Parameter
cmap gray
detrend False
high_variance_confounds False
mask_strategy epi
memory_level 1
reports True
standardize False
standardize_confounds True
target_affine [[8.0, 0.0, 0.0], [0.0, 8.0, 0.0], [0.0, 0.0, 8.0]]
verbose 0


.. GENERATED FROM PYTHON SOURCE LINES 237-241 After mask computation: extracting time series ---------------------------------------------- We extract detrended and non-detrended time series. .. GENERATED FROM PYTHON SOURCE LINES 241-248 .. code-block:: Python trended_data = NiftiMasker( mask_strategy="epi", verbose=1, standardize="zscore_sample" ).fit_transform(epi_img) detrended_data = NiftiMasker( mask_strategy="epi", detrend=True, verbose=1 ).fit_transform(epi_img) .. rst-class:: sphx-glr-script-out .. code-block:: none [NiftiMasker.wrapped] Loading data from [NiftiMasker.wrapped] Computing mask [NiftiMasker.wrapped] Resampling mask [NiftiMasker.wrapped] Finished fit [NiftiMasker.wrapped] Loading data from [NiftiMasker.wrapped] Extracting region signals [NiftiMasker.wrapped] Cleaning extracted signals [NiftiMasker.wrapped] Loading data from [NiftiMasker.wrapped] Computing mask [NiftiMasker.wrapped] Resampling mask [NiftiMasker.wrapped] Finished fit /home/runner/work/nilearn/nilearn/examples/06_manipulating_images/plot_mask_computation.py:246: FutureWarning: boolean values for 'standardize' will be deprecated in nilearn 0.15.0. Use 'zscore_sample' instead of 'True' or use 'None' instead of 'False'. [NiftiMasker.wrapped] Loading data from [NiftiMasker.wrapped] Extracting region signals [NiftiMasker.wrapped] Cleaning extracted signals .. GENERATED FROM PYTHON SOURCE LINES 249-251 Once extracted, the timeseries are numpy arrays, so we can use numpy operations on them. .. GENERATED FROM PYTHON SOURCE LINES 251-260 .. code-block:: Python print( f"Trended:\tmean {np.mean(trended_data):.2f},\t" f"std {np.std(trended_data):.2f}" ) print( f"Detrended:\tmean {np.mean(detrended_data):.2f},\t" f"std {np.std(detrended_data):.2f}" ) .. rst-class:: sphx-glr-script-out .. code-block:: none Trended: mean -0.00, std 0.99 Detrended: mean -0.00, std 5.88 .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 10.243 seconds) **Estimated memory usage:** 324 MB .. _sphx_glr_download_auto_examples_06_manipulating_images_plot_mask_computation.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: binder-badge .. image:: images/binder_badge_logo.svg :target: https://mybinder.org/v2/gh/nilearn/nilearn/0.14.1?urlpath=lab/tree/notebooks/auto_examples/06_manipulating_images/plot_mask_computation.ipynb :alt: Launch binder :width: 150 px .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_mask_computation.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_mask_computation.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: plot_mask_computation.zip ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_