.. 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_nifti_simple.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 JupyterLite or Binder .. rst-class:: sphx-glr-example-title .. _sphx_glr_auto_examples_06_manipulating_images_plot_nifti_simple.py: Simple example of NiftiMasker use ================================= Here is a simple example of automatic mask computation using the nifti masker. The mask is computed and visualized. .. GENERATED FROM PYTHON SOURCE LINES 11-16 Retrieve the brain development functional dataset ------------------------------------------------- We fetch the dataset and print some basic information about it. .. GENERATED FROM PYTHON SOURCE LINES 16-24 .. code-block:: Python from nilearn.datasets import fetch_development_fmri dataset = fetch_development_fmri(n_subjects=1) func_filename = dataset.func[0] print(f"First functional nifti image (4D) is at: {func_filename}") .. rst-class:: sphx-glr-script-out .. code-block:: none [fetch_development_fmri] Dataset directory found: /home/runner/nilearn_data/development_fmri [fetch_development_fmri] Dataset directory found: /home/runner/nilearn_data/development_fmri/development_fmri [fetch_development_fmri] Dataset directory found: /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 .. GENERATED FROM PYTHON SOURCE LINES 25-32 Compute the mask ---------------- As the input image is an EPI image, the background is noisy and we cannot rely on the ``'background'`` masking strategy. We need to use the ``'epi'`` one. .. GENERATED FROM PYTHON SOURCE LINES 32-42 .. code-block:: Python from nilearn.maskers import NiftiMasker masker = NiftiMasker( mask_strategy="epi", memory="nilearn_cache", memory_level=1, smoothing_fwhm=8, verbose=1, ) .. GENERATED FROM PYTHON SOURCE LINES 43-45 .. include:: ../../../examples/html_repr_note.rst .. GENERATED FROM PYTHON SOURCE LINES 46-48 .. code-block:: Python masker .. raw:: html
NiftiMasker(mask_strategy='epi', memory='nilearn_cache', smoothing_fwhm=8,
                verbose=1)
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 49-51 .. code-block:: Python masker.fit(func_filename) .. rst-class:: sphx-glr-script-out .. code-block:: none \[NiftiMasker.fit] Loading data from '/home/runner/nilearn_data/development_fmri /development_fmri/sub-pixar123_task-pixar_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.1s, 0.0min \[NiftiMasker.fit] Resampling mask ________________________________________________________________________________ [Memory] Calling nilearn.image.resampling.resample_img... resample_img(, target_affine=None, target_shape=None, copy=False, interpolation='nearest') _____________________________________________________resample_img - 0.0s, 0.0min \[NiftiMasker.fit] Finished fit .. raw:: html
NiftiMasker(mask_strategy='epi', memory='nilearn_cache', smoothing_fwhm=8,
                verbose=1)
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 52-58 .. note :: You can also note that after fitting, the HTML representation of the estimator looks different than before fitting. .. GENERATED FROM PYTHON SOURCE LINES 58-60 .. code-block:: Python masker .. raw:: html
NiftiMasker(mask_strategy='epi', memory='nilearn_cache', smoothing_fwhm=8,
                verbose=1)
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 61-73 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 73-84 .. code-block:: Python from nilearn.image.image import mean_img from nilearn.plotting import plot_roi, show mask_img = masker.mask_img_ mean_func_img = mean_img(func_filename) plot_roi(mask_img, mean_func_img, display_mode="y", cut_coords=4, title="Mask") show() .. image-sg:: /auto_examples/06_manipulating_images/images/sphx_glr_plot_nifti_simple_001.png :alt: plot nifti simple :srcset: /auto_examples/06_manipulating_images/images/sphx_glr_plot_nifti_simple_001.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 85-96 Visualize the masker report --------------------------- 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. Here we use the 'brainsprite' engine that gives an interactive visualization instead of the static one generated by the matplotlib engine. .. GENERATED FROM PYTHON SOURCE LINES 96-98 .. 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. .. GENERATED FROM PYTHON SOURCE LINES 99-101 .. include:: ../../../examples/report_note.rst .. GENERATED FROM PYTHON SOURCE LINES 102-104 .. 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 24256 voxels (16.4 %) of the image.

Value
Parameter
cmap gray
detrend False
high_variance_confounds False
mask_strategy epi
memory nilearn_cache
memory_level 1
reports True
smoothing_fwhm 8
standardize False
standardize_confounds True
verbose 1


.. GENERATED FROM PYTHON SOURCE LINES 105-110 Preprocess data with the NiftiMasker ------------------------------------ We extract the data from the nifti image and turn it into a numpy array. .. GENERATED FROM PYTHON SOURCE LINES 110-113 .. code-block:: Python fmri_masked = masker.transform(func_filename) print(fmri_masked.shape) .. rst-class:: sphx-glr-script-out .. code-block:: none /home/runner/work/nilearn/nilearn/examples/06_manipulating_images/plot_nifti_simple.py:110: 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'. ________________________________________________________________________________ [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', , { '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': False, '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, sklearn_output_config=None) \[NiftiMasker.wrapped] Loading data from \[NiftiMasker.wrapped] Smoothing images \[NiftiMasker.wrapped] Extracting region signals \[NiftiMasker.wrapped] Cleaning extracted signals /home/runner/work/nilearn/nilearn/examples/06_manipulating_images/plot_nifti_simple.py:110: 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'. __________________________________________________filter_and_mask - 0.7s, 0.0min (168, 24256) .. GENERATED FROM PYTHON SOURCE LINES 114-115 ``fmri_masked`` is now a 2D numpy array, (n_voxels x n_time_points). .. GENERATED FROM PYTHON SOURCE LINES 117-123 Output to dataframe ------------------- You can also use 'set_output()' to decide the output format of 'transform'. If you want to output to a DataFrame, you can choose 'pandas' or 'polars'. .. GENERATED FROM PYTHON SOURCE LINES 123-128 .. code-block:: Python masker.set_output(transform="pandas") fmri_masked = masker.transform(func_filename) print(fmri_masked.head) .. rst-class:: sphx-glr-script-out .. code-block:: none /home/runner/work/nilearn/nilearn/examples/06_manipulating_images/plot_nifti_simple.py:124: 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'. ________________________________________________________________________________ [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', , { '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': False, '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, sklearn_output_config={'transform': 'pandas'}) \[NiftiMasker.wrapped] Loading data from \[NiftiMasker.wrapped] Smoothing images \[NiftiMasker.wrapped] Extracting region signals \[NiftiMasker.wrapped] Cleaning extracted signals /home/runner/work/nilearn/nilearn/examples/06_manipulating_images/plot_nifti_simple.py:124: 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'. __________________________________________________filter_and_mask - 0.7s, 0.0min .. GENERATED FROM PYTHON SOURCE LINES 129-139 Run an algorithm and visualize the results ------------------------------------------ Given that we now have a numpy array, we can then pass the data the wide range of algorithm. Here we will just do an independent component analysis, turned the extracted component back into images (using :meth:`~nilearn.maskers.NiftiMasker.inverse_transform`), then we will plot the first component. .. GENERATED FROM PYTHON SOURCE LINES 139-158 .. code-block:: Python from sklearn.decomposition import FastICA from nilearn.image import index_img from nilearn.plotting import plot_stat_map, show ica = FastICA(n_components=10, random_state=42, tol=0.001, max_iter=2000) components_masked = ica.fit_transform(fmri_masked.T).T components = masker.inverse_transform(components_masked) plot_stat_map( index_img(components, 0), mean_func_img, display_mode="y", cut_coords=4, title="Component 0", ) show() .. image-sg:: /auto_examples/06_manipulating_images/images/sphx_glr_plot_nifti_simple_002.png :alt: plot nifti simple :srcset: /auto_examples/06_manipulating_images/images/sphx_glr_plot_nifti_simple_002.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none \[NiftiMasker.inverse_transform] Computing image from signals ________________________________________________________________________________ [Memory] Calling nilearn.masking.unmask... unmask(array([[-1.0416 , ..., -0.558067], ..., [ 0.574022, ..., -0.41854 ]]), ) ___________________________________________________________unmask - 0.1s, 0.0min .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 8.051 seconds) **Estimated memory usage:** 616 MB .. _sphx_glr_download_auto_examples_06_manipulating_images_plot_nifti_simple.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.0?urlpath=lab/tree/notebooks/auto_examples/06_manipulating_images/plot_nifti_simple.ipynb :alt: Launch binder :width: 150 px .. container:: lite-badge .. image:: images/jupyterlite_badge_logo.svg :target: ../../lite/lab/index.html?path=auto_examples/06_manipulating_images/plot_nifti_simple.ipynb :alt: Launch JupyterLite :width: 150 px .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_nifti_simple.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_nifti_simple.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: plot_nifti_simple.zip ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_