Extract voxel coordinates

With nilearn, is it possible to extract voxel coordinates from every voxel within an ROI image consisting of ones and zeros?

If you have a nibabel image as img, you can do the following:

import numpy as np
import nibabel as nib

data = img.get_fdata()  # get image data as a numpy array
idx = np.where(data)  # find voxels that are not zeroes
ijk = np.vstack(idx).T  # list of arrays to (voxels, 3) array
xyz = nib.affines.apply_affine(img.affine, ijk)  # get mm coords

See this blog post for the mm to voxel and voxel to mm conversions with nibabel.

2 Likes