Skip to content

Instantly share code, notes, and snippets.

@bthirion
Created January 5, 2016 21:26
Show Gist options
  • Save bthirion/21db31438b1b450cb1ee to your computer and use it in GitHub Desktop.
Save bthirion/21db31438b1b450cb1ee to your computer and use it in GitHub Desktop.
Get the neighbors of target voxels
"""
Get the neighbors of target voxels
"""
import numpy as np
from nilearn import datasets
from nilearn import input_data
from sklearn.feature_extraction import image
### Load nyu_rest dataset #####################################################
nyu_dataset = datasets.fetch_nyu_rest(n_subjects=1)
nifti_masker = input_data.NiftiMasker(memory='nilearn_cache',
mask_strategy='epi', memory_level=1,
standardize=False)
func_filename = nyu_dataset.func[0]
fmri_masked = nifti_masker.fit_transform(func_filename)
mask = nifti_masker.mask_img_.get_data().astype(np.bool)
roi = mask[mask > 0] # but could be any niimg
# Compute connectivity matrix: which voxel is connected to which
shape = mask.shape
connectivity = image.grid_to_graph(n_x=shape[0], n_y=shape[1],
n_z=shape[2], mask=mask)
neighbors = connectivity.tolil().rows
# whant the neighbors only within a given roi ?
neighbors_within_roi = [neighbors[i] for i in range(mask.sum()) if roi[i]]
# then you can extract signals etc
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment