import nibabel as nib
from nilearn.plotting import view_img
from nilearn.masking import apply_mask
from nilearn.maskers import NiftiMasker
from nilearn import image
import numpy as np
from matplotlib import pyplot as plt
Extracting Average Ventricle Signal
= nib.load('data/tmp/s4101_bold_rest.nii.gz')
bold = nib.load('data/tmp/s4101_anal_ventricle_bmask_corrected.nii.gz')
mask 10), cmap='viridis') view_img(mask, image.index_img(bold,
/share/pkg.8/python3/3.10.12/install/lib/python3.10/site-packages/numpy/core/fromnumeric.py:784: UserWarning:
Warning: 'partition' will ignore the 'mask' of the MaskedArray.
/share/pkg.8/python3/3.10.12/install/lib/python3.10/site-packages/nilearn/image/resampling.py:294: UserWarning:
Resampling binary images with continuous or linear interpolation. This might lead to unexpected results. You might consider using nearest interpolation instead.
We need to resample the mask onto the functional images, else apply_mask will let us know that the two have different affines.
= image.resample_to_img(mask, bold, interpolation='nearest')
rs_mask 10), cmap='viridis') view_img(mask, image.index_img(bold,
/share/pkg.8/python3/3.10.12/install/lib/python3.10/site-packages/numpy/core/fromnumeric.py:784: UserWarning:
Warning: 'partition' will ignore the 'mask' of the MaskedArray.
/share/pkg.8/python3/3.10.12/install/lib/python3.10/site-packages/nilearn/image/resampling.py:294: UserWarning:
Resampling binary images with continuous or linear interpolation. This might lead to unexpected results. You might consider using nearest interpolation instead.
Now to apply the mask.
= apply_mask(bold, rs_mask)
masked # view_img(image.index_img(masked, 10), image.index_img(bold, 10), cmap='viridis')
# For some reason this is a 2D array.
type(masked), masked.shape
# supposedly this tis timepoints x voxels
(numpy.ndarray, (400, 1158))
Masked data is a voxel-by-voxel timeseries, collapsing the 4D image across spatial dimensions to 2D. The unmask
function takes the data back to 4D.
plt.matshow(masked)
Apparantly there’s also NiftiMasker
.
= NiftiMasker(rs_mask, standardize=True)
mskr = mskr.fit_transform(bold)
ts
type(ts), ts.shape
/share/pkg.8/python3/3.10.12/install/lib/python3.10/site-packages/joblib/memory.py:353: FutureWarning:
The default strategy for standardize is currently 'zscore' which incorrectly uses population std to calculate sample zscores. The new strategy 'zscore_sample' corrects this behavior by using the sample std. In release 0.13, the default strategy will be replaced by the new strategy and the 'zscore' option will be removed. Please use 'zscore_sample' instead.
(numpy.ndarray, (400, 1158))
This again produces a collapsed timeseries.
A more straightforward approach is to just multiply, yielding a 4D image again.
= image.math_img("im * ms", im=bold, ms=image.concat_imgs([rs_mask] * bold.shape[-1]))
masked4d 10), None, cmap='viridis', black_bg=True) view_img(image.index_img(masked4d,