Extract timeseries from all voxels within ROI using Nilearn
Goal
I am trying to extract the timeseries for all voxels within an ROI using Nilearn. Other topics similar to this seem to be incomplete or the information that was provided was not sufficient enough for me to solve the task given my inexperience with Nilearn.
Intended steps
I want to load in a nifti image
import nibabel as nib
file = "/path/to/file.nii.gz"
data = nib.load(file)
datamat = data.get_fdata()
and then apply NiftiLabelMasker
to extract ROIs
from nilearn.masking import NiftiLabelMasker
from nilearn.datasets import fetch_atlas_harvard_oxford
atlas = fetch_atlas_harvard_oxford("cort-maxprob-thr25-2mm")
masker = NiftiLabelsMasker(
atlas.maps,
labels=atlas.labels,
standardize="zscore_sample",
)
masker.fit(file)
masked_data = masker.transform(file)
I then want to use this information to apply it back to the original data. So, if I want the time series for the Superior Parietal Lobule
labels = masker.labels
spl = labels.index('Superior Parietal Lobule')
spl_data = masker.inverse_transform(data[:, np.where(masked_data == spl)]) # something to this effect; this exact line is only meant for conceptual purposes
Another important task I am trying to accomplish is ensuring that this returned data is 2d np.ndarray
. So if I call
spl_data.shape
---
(240, 56) # TRs X Voxels
I know that NilearnLabelsMasker.inverse_transform()
returns the data into a 3d matrix.
Any help is appreciated.