Motion correction in ANTsPy

We rely on ants.registration to do motion correction which provides the user with full access to parameters and outputs. The key steps, then, are to:

  • split the N dimensional (e.g. N=4) image to a list of N-1 dimensional images
  • run registration to a selected fixed image for each image in the list
  • merge the results back to a N dimensional image.

In [2]:
import ants
import numpy as np

We illustrate the steps below by building a 3D "functional" image and then "motion correcting" just as we would do with functional MRI or any other dynamic modality.


In [6]:
image = ants.image_read(ants.get_ants_data('r16'))
image2 = ants.image_read(ants.get_ants_data('r64'))
ants.set_spacing( image, (2,2) )
ants.set_spacing( image2, (2,2) )
imageTar = ants.make_image( ( *image2.shape, 2 ) )
ants.set_spacing( imageTar, (2,2,2) )
fmri = ants.list_to_ndimage( imageTar, [image,image2] )

Now we motion correct this image just using the first slice as target.


In [13]:
ants.set_direction( fmri, np.eye( 3 ) * 2 )
images_unmerged = ants.ndimage_to_list( fmri )
motion_corrected = list()
for i in range( len( images_unmerged ) ):
    areg = ants.registration( images_unmerged[0], images_unmerged[i], "SyN" )
    motion_corrected.append( areg[ 'warpedmovout' ] )

Merge the resuling list back to a 3D image.


In [27]:
motCorr = ants.list_to_ndimage( fmri, motion_corrected )
# ants.image_write( motCorr, '/tmp/temp.nii.gz' )

Done!