.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_examples/01_DataOperations/plot_mask.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 .. rst-class:: sphx-glr-example-title .. _sphx_glr_auto_examples_01_DataOperations_plot_mask.py: Masking Example =============== This tutorial illustrates methods to help with masking data. .. GENERATED FROM PYTHON SOURCE LINES 10-14 Load Data --------- First, let's load the pain data for this example. .. GENERATED FROM PYTHON SOURCE LINES 14-19 .. code-block:: default from nltools.datasets import fetch_pain data = fetch_pain() .. rst-class:: sphx-glr-script-out .. code-block:: none /usr/share/miniconda3/envs/test/lib/python3.8/site-packages/nilearn/maskers/nifti_masker.py:108: UserWarning: imgs are being resampled to the mask_img resolution. This process is memory intensive. You might want to provide a target_affine that is equal to the affine of the imgs or resample the mask beforehand to save memory and computation time. warnings.warn( .. GENERATED FROM PYTHON SOURCE LINES 20-25 Apply_Mask ---------- Spherical masks can be created using the create_sphere function. It requires specifying a center voxel and the radius of the sphere. .. GENERATED FROM PYTHON SOURCE LINES 25-32 .. code-block:: default from nltools.mask import create_sphere mask = create_sphere([0, 0, 0], radius=30) masked_data = data.apply_mask(mask) masked_data.mean().plot() .. image-sg:: /auto_examples/01_DataOperations/images/sphx_glr_plot_mask_001.png :alt: plot mask :srcset: /auto_examples/01_DataOperations/images/sphx_glr_plot_mask_001.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none /usr/share/miniconda3/envs/test/lib/python3.8/site-packages/nilearn/maskers/nifti_masker.py:108: UserWarning: imgs are being resampled to the mask_img resolution. This process is memory intensive. You might want to provide a target_affine that is equal to the affine of the imgs or resample the mask beforehand to save memory and computation time. warnings.warn( /usr/share/miniconda3/envs/test/lib/python3.8/site-packages/nilearn/image/resampling.py:291: UserWarning: Resampling binary images with continuous or linear interpolation. This might lead to unexpected results. You might consider using nearest interpolation instead. warnings.warn( .. GENERATED FROM PYTHON SOURCE LINES 33-38 Extract Mean Within ROI ----------------------- We can easily calculate the mean within an ROI for each image within a Brain_Data() instance using the extract_roi() method. .. GENERATED FROM PYTHON SOURCE LINES 38-44 .. code-block:: default import matplotlib.pyplot as plt mean = data.extract_roi(mask) plt.plot(mean) .. image-sg:: /auto_examples/01_DataOperations/images/sphx_glr_plot_mask_002.png :alt: plot mask :srcset: /auto_examples/01_DataOperations/images/sphx_glr_plot_mask_002.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none [] .. GENERATED FROM PYTHON SOURCE LINES 45-52 Expand and Contract ROIs ------------------------ Some masks have many ROIs indicated by a unique ID. It is possible to expand these masks into separate ROIs and also collapse them into a single image again. Here we will demonstrate on a k=50 parcellation hosted on http://neurovault.org. .. GENERATED FROM PYTHON SOURCE LINES 52-59 .. code-block:: default from nltools.mask import expand_mask, collapse_mask from nltools.data import Brain_Data mask = Brain_Data('http://neurovault.org/media/images/2099/Neurosynth%20Parcellation_0.nii.gz') mask.plot() .. image-sg:: /auto_examples/01_DataOperations/images/sphx_glr_plot_mask_003.png :alt: plot mask :srcset: /auto_examples/01_DataOperations/images/sphx_glr_plot_mask_003.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 60-61 We can expand this mask into 50 separate regions .. GENERATED FROM PYTHON SOURCE LINES 61-65 .. code-block:: default mask_x = expand_mask(mask) mask_x[:3].plot() .. image-sg:: /auto_examples/01_DataOperations/images/sphx_glr_plot_mask_004.png :alt: plot mask :srcset: /auto_examples/01_DataOperations/images/sphx_glr_plot_mask_004.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none /usr/share/miniconda3/envs/test/lib/python3.8/site-packages/nilearn/masking.py:974: UserWarning: Data array used to create a new image contains 64-bit ints. This is likely due to creating the array with numpy and passing `int` as the `dtype`. Many tools such as FSL and SPM cannot deal with int64 in Nifti images, so for compatibility the data has been converted to int32. return new_img_like(mask_img, unmasked, affine) .. GENERATED FROM PYTHON SOURCE LINES 66-67 We can collapse these 50 separate regions as unique values in a single image .. GENERATED FROM PYTHON SOURCE LINES 67-71 .. code-block:: default mask_c = collapse_mask(mask_x) mask_c.plot() .. image-sg:: /auto_examples/01_DataOperations/images/sphx_glr_plot_mask_005.png :alt: plot mask :srcset: /auto_examples/01_DataOperations/images/sphx_glr_plot_mask_005.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none /usr/share/miniconda3/envs/test/lib/python3.8/site-packages/nilearn/masking.py:974: UserWarning: Data array used to create a new image contains 64-bit ints. This is likely due to creating the array with numpy and passing `int` as the `dtype`. Many tools such as FSL and SPM cannot deal with int64 in Nifti images, so for compatibility the data has been converted to int32. return new_img_like(mask_img, unmasked, affine) /usr/share/miniconda3/envs/test/lib/python3.8/site-packages/nilearn/masking.py:974: UserWarning: Data array used to create a new image contains 64-bit ints. This is likely due to creating the array with numpy and passing `int` as the `dtype`. Many tools such as FSL and SPM cannot deal with int64 in Nifti images, so for compatibility the data has been converted to int32. return new_img_like(mask_img, unmasked, affine) .. GENERATED FROM PYTHON SOURCE LINES 72-78 Threshold and Regions --------------------- Images can be thresholded using an arbitrary cutoff or a percentile using the threshold method. Here we calculate the mean of the high pain images and threshold using the 95 percentile. .. GENERATED FROM PYTHON SOURCE LINES 78-82 .. code-block:: default high = data[data.X['PainLevel']==3] high.mean().threshold(lower='2.5%', upper='97.5%').plot() .. image-sg:: /auto_examples/01_DataOperations/images/sphx_glr_plot_mask_006.png :alt: plot mask :srcset: /auto_examples/01_DataOperations/images/sphx_glr_plot_mask_006.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 83-84 We might be interested in creating a binary mask from this threshold. .. GENERATED FROM PYTHON SOURCE LINES 84-88 .. code-block:: default mask_b = high.mean().threshold(lower='2.5%', upper='97.5%',binarize=True) mask_b.plot() .. image-sg:: /auto_examples/01_DataOperations/images/sphx_glr_plot_mask_007.png :alt: plot mask :srcset: /auto_examples/01_DataOperations/images/sphx_glr_plot_mask_007.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 89-90 We might also want to create separate images from each contiguous ROI. .. GENERATED FROM PYTHON SOURCE LINES 90-94 .. code-block:: default region = high.mean().threshold(lower='2.5%', upper='97.5%').regions() region.plot() .. image-sg:: /auto_examples/01_DataOperations/images/sphx_glr_plot_mask_008.png :alt: plot mask :srcset: /auto_examples/01_DataOperations/images/sphx_glr_plot_mask_008.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 95-102 Finally, we can perform operations on ROIs from a mask and then convert them back into a Brain_Data instance. In this example, let's compute a linear contrast of increasing pain for each each participant. Then, let's compute functional connectivity across participants within each ROI and calculate the degree centrality of each ROI after arbitrarily thresholding the connectivity matrix. We can then convert each ROIs degree back into a Brain_Data instance to help visualize which regions are more central in this analysis. .. GENERATED FROM PYTHON SOURCE LINES 102-131 .. code-block:: default from sklearn.metrics import pairwise_distances from nltools.data import Adjacency from nltools.mask import roi_to_brain import pandas as pd import numpy as np sub_list = data.X['SubjectID'].unique() # perform matrix multiplication to compute linear contrast for each subject lin_contrast = [] for sub in sub_list: lin_contrast.append(data[data.X['SubjectID'] == sub] * np.array([1, -1, 0])) # concatenate list of Brain_Data instances into a single instance lin_contrast = Brain_Data(lin_contrast) # Compute correlation distance between each ROI dist = Adjacency(pairwise_distances(lin_contrast.extract_roi(mask), metric='correlation'), matrix_type='distance') # Threshold functional connectivity and convert to Adjacency Matrix. Plot as heatmap dist.threshold(upper=.4, binarize=True).plot() # Convert Adjacency matrix to networkX instance g = dist.threshold(upper=.4, binarize=True).to_graph() # Compute degree centrality and convert back into Brain_Data instance. degree_centrality = roi_to_brain(pd.Series(dict(g.degree())), mask_x) degree_centrality.plot() .. rst-class:: sphx-glr-horizontal * .. image-sg:: /auto_examples/01_DataOperations/images/sphx_glr_plot_mask_009.png :alt: plot mask :srcset: /auto_examples/01_DataOperations/images/sphx_glr_plot_mask_009.png :class: sphx-glr-multi-img * .. image-sg:: /auto_examples/01_DataOperations/images/sphx_glr_plot_mask_010.png :alt: plot mask :srcset: /auto_examples/01_DataOperations/images/sphx_glr_plot_mask_010.png :class: sphx-glr-multi-img .. rst-class:: sphx-glr-script-out .. code-block:: none /usr/share/miniconda3/envs/test/lib/python3.8/site-packages/nilearn/masking.py:974: UserWarning: Data array used to create a new image contains 64-bit ints. This is likely due to creating the array with numpy and passing `int` as the `dtype`. Many tools such as FSL and SPM cannot deal with int64 in Nifti images, so for compatibility the data has been converted to int32. return new_img_like(mask_img, unmasked, affine) .. rst-class:: sphx-glr-timing **Total running time of the script:** (1 minutes 41.472 seconds) .. _sphx_glr_download_auto_examples_01_DataOperations_plot_mask.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_mask.py ` .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_mask.ipynb ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_