Friday, December 12, 2014

How to convert between voxel and mm coordinates using Python

I'm often asked how to go from voxel and mm coordinates using Python. This can be easily achieved using nibabel package with only few lines of code. The following tutorial is based on +Matthew Brett answer on the nipy mailing list.

Going from voxel to mm coordinates

import os
import nibabel as nib
Load the NIFTI file defining the space you are interested in. For the purpose of this tutorial we will use a test dataset shipped with nibabel.
data_fname = os.path.join(os.path.dirname(nib.__file__), 'tests', 'data', 'example4d.nii.gz')
img = nib.load(data_fname)
Get the affine matrix and convert the coordinates.
aff = img.get_affine()
real_pt = nib.affines.apply_affine(aff, [22, 34, 12])
array([ 73.85510254,  27.1169095 ,  29.79324198])

Going from mm to voxel coordinates

Going the other direction is even easier.
import numpy.linalg as npl
nib.affines.apply_affine(npl.inv(aff), real_pt)
array([ 22.,  34.,  12.])