Skip to main content

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])
real_pt
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.])

Comments

  1. This is ansuperior writing service point that doesn't always sink in within the context of the classroom. In the first superior writing service paragraph you either hook the reader's interest or lose it. Of course your teacher, who's getting paid to teach you how to write an good essay, 
    python Training institute in Chennai
    python Training institute in Bangalore

    ReplyDelete
  2. Thnx a lot
    But I hv tried tht but still i hv errors :(

    ReplyDelete
  3. Attend The Python Training in Hyderabad From ExcelR. Practical Python Training Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Python Training in Hyderabad.
    python training in bangalore

    ReplyDelete
  4. Business Analytics or Data Analytics or data science training in hyderabad is an extremely popular, in-demand profession which requires a professional to possess sound knowledge of analysing data in all dimensions and uncover the unseen truth coupled with logic and domain knowledge to impact the top-line (increase business) and bottom-line (increase revenue). ExcelR’s Data Science curriculum is meticulously designed and delivered matching the industry needs and considered to be the best in the industry.

    ReplyDelete

Post a Comment