.. 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 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 :class:`~nilearn.maskers.NiftiMasker`. 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/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 .. GENERATED FROM PYTHON SOURCE LINES 25-31 Compute the mask ---------------- As the input image is an :term:`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 31-41 .. code-block:: Python from nilearn.maskers import NiftiMasker masker = NiftiMasker( mask_strategy="epi", memory="nilearn_cache", memory_level=1, smoothing_fwhm=8, standardize="zscore_sample", ) .. GENERATED FROM PYTHON SOURCE LINES 42-44 .. include:: ../../../examples/html_repr_note.rst .. GENERATED FROM PYTHON SOURCE LINES 45-47 .. code-block:: Python masker .. raw:: html
NiftiMasker(mask_strategy='epi', memory='nilearn_cache', smoothing_fwhm=8,
                standardize='zscore_sample')
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 48-50 .. code-block:: Python masker.fit(func_filename) .. raw:: html
NiftiMasker(mask_strategy='epi', memory='nilearn_cache', smoothing_fwhm=8,
                standardize='zscore_sample')
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 51-57 .. note :: You can also note that after fitting, the HTML representation of the estimator looks different than before fitting. .. GENERATED FROM PYTHON SOURCE LINES 59-71 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 71-82 .. 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 83-94 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 94-96 .. 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 97-99 .. include:: ../../../examples/report_note.rst .. GENERATED FROM PYTHON SOURCE LINES 100-102 .. 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 zscore_sample
standardize_confounds True
verbose 0


.. GENERATED FROM PYTHON SOURCE LINES 103-110 Preprocess data with the NiftiMasker ------------------------------------ We extract the data from the nifti image. By default this will return a 2D NumPy array with shape (n_samples, n_features). .. 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 (168, 24256) .. GENERATED FROM PYTHON SOURCE LINES 114-122 Output to dataframe ------------------- You can use :meth:`~nilearn.maskers.NiftiLabelsMasker.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 122-127 .. 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 niftimasker0 niftimasker1 ... niftimasker24254 niftimasker24255 0 -1.006351 -0.323282 ... -1.211367 -0.711075 1 -1.968796 -0.664021 ... -1.561624 -0.514343 2 -2.163321 -0.273362 ... -1.835269 -0.823911 3 -0.791810 0.323022 ... 0.414807 1.005020 4 -1.493661 0.811071 ... 0.557249 0.901407 [5 rows x 24256 columns] .. GENERATED FROM PYTHON SOURCE LINES 128-137 Run an algorithm and visualize the results ------------------------------------------ We can pass the extracted data to a wide range of algorithm. Here we will just do an independent component analysis, turn 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 137-156 .. 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 /home/runner/work/nilearn/nilearn/.tox/doc/lib/python3.10/site-packages/sklearn/decomposition/_fastica.py:128: ConvergenceWarning: FastICA did not converge. Consider increasing tolerance or the maximum number of iterations. .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 20.000 seconds) **Estimated memory usage:** 634 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.1?urlpath=lab/tree/notebooks/auto_examples/06_manipulating_images/plot_nifti_simple.ipynb :alt: Launch binder :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 `_