[Neuroimaging] Extract XYZ coordinates in mm using nibabel

Matthew Brett matthew.brett at gmail.com
Mon Jan 23 13:15:56 EST 2017


Hi,

On Sun, Jan 22, 2017 at 10:19 PM, shuang wu <shuanw at uw.edu> wrote:
> Hi there:
>
> I am recently using the nibabel (nib) package in python to try to extract
> the information from .img file. I use nib.load.get_data() to extract the
> intensity values from the img file, but I do not know how to extract those
> corresponding xyz coordinates in mm.
>
> In Matlab, I can use [Y, xyz] = spm_read_vols(vol) to extract both the
> intensity values Y and the coordinates xyz in mm.
>
> Is there anyway to do the same thing using python?
>
> Thanks in advance for any help!

There's no canned way of doing that in nibabel, but this snippet will
do the job:

In [1]: import numpy as np
In [2]: import nibabel as nib
In [3]: img = nib.load('test.nii')
In [4]: shape, affine = img.shape[:3], img.affine
In [5]: coords = np.array(np.meshgrid(*(range(i) for i in shape),
indexing='ij'))
In [6]: coords = np.rollaxis(coords, 0, len(shape) + 1)
In [7]: mm_coords = nib.affines.apply_affine(affine, coords)

For background see: http://nipy.org/nibabel/coordinate_systems.html

Cheers,

Matthew


More information about the Neuroimaging mailing list