Registration

ants.registration(fixed, moving, type_of_transform='SyN', initial_transform=None, outprefix='', mask=None, moving_mask=None, mask_all_stages=False, grad_step=0.2, flow_sigma=3, total_sigma=0, aff_metric='mattes', aff_sampling=32, aff_random_sampling_rate=0.2, syn_metric='mattes', syn_sampling=32, reg_iterations=(40, 20, 0), aff_iterations=(2100, 1200, 1200, 10), aff_shrink_factors=(6, 4, 2, 1), aff_smoothing_sigmas=(3, 2, 1, 0), write_composite_transform=False, random_seed=None, verbose=False, multivariate_extras=None, restrict_transformation=None, smoothing_in_mm=False, **kwargs)[source]

Register a pair of images either through the full or simplified interface to the ANTs registration method.

ANTsR function: antsRegistration

Parameters:
  • fixed (ANTsImage) – fixed image to which we register the moving image.

  • moving (ANTsImage) – moving image to be mapped to fixed space.

  • type_of_transform (string) – A linear or non-linear registration type. Mutual information metric by default. See Notes below for more.

  • initial_transform (list of strings (optional)) – transforms to prepend

  • outprefix (string) – output will be named with this prefix.

  • mask (ANTsImage (optional)) – Registration metric mask in the fixed image space.

  • moving_mask (ANTsImage (optional)) – Registration metric mask in the moving image space.

  • mask_all_stages (boolean) – If true, apply metric mask(s) to all registration stages, instead of just the final stage.

  • grad_step (scalar) – gradient step size (not for all tx)

  • flow_sigma (scalar) – smoothing for update field At each iteration, the similarity metric and gradient is calculated. That gradient field is also called the update field and is smoothed before composing with the total field (i.e., the estimate of the total transform at that iteration). This total field can also be smoothed after each iteration.

  • total_sigma (scalar) – smoothing for total field

  • aff_metric (string) – the metric for the affine part (GC, mattes, meansquares)

  • aff_sampling (scalar) – number of bins for the mutual information metric

  • aff_random_sampling_rate (scalar) – the fraction of points used to estimate the metric. this can impact speed but also reproducibility and/or accuracy.

  • syn_metric (string) – the metric for the syn part (CC, mattes, meansquares, demons)

  • syn_sampling (scalar) – the nbins or radius parameter for the syn metric

  • reg_iterations (list/tuple of python:integers) – vector of iterations for syn. we will set the smoothing and multi-resolution parameters based on the length of this vector.

  • aff_iterations (list/tuple of python:integers) – vector of iterations for low-dimensional (translation, rigid, affine) registration.

  • aff_shrink_factors (list/tuple of python:integers) – vector of multi-resolution shrink factors for low-dimensional (translation, rigid, affine) registration.

  • aff_smoothing_sigmas (list/tuple of python:integers) – vector of multi-resolution smoothing factors for low-dimensional (translation, rigid, affine) registration.

  • random_seed (python:integer) – random seed to improve reproducibility. note that the number of ITK_GLOBAL_DEFAULT_NUMBER_OF_THREADS should be 1 if you want perfect reproducibility.

  • write_composite_transform (boolean) – Boolean specifying whether or not the composite transform (and its inverse, if it exists) should be written to an hdf5 composite file. This is false by default so that only the transform for each stage is written to file.

  • verbose (boolean) – request verbose output (useful for debugging)

  • multivariate_extras (additional metrics for multi-metric registration) –

    list of additional images and metrics which will trigger the use of multiple metrics in the registration process in the deformable stage. Each multivariate metric needs 5 entries: name of metric, fixed, moving, weight, samplingParam. the list of lists should be of the form ( ( “nameOfMetric2”, img, img, weight, metricParam ) ). Another example would be ( ( “MeanSquares”, f2, m2, 0.5, 0

    ), ( “CC”, f2, m2, 0.5, 2 ) ) . This is only compatible

    with the SyNOnly or antsRegistrationSyN* transformations.

  • restrict_transformation (This option allows the user to restrict the) – optimization of the displacement field, translation, rigid or affine transform on a per-component basis. For example, if one wants to limit the deformation or rotation of 3-D volume to the first two dimensions, this is possible by specifying a weight vector of ‘(1,1,0)’ for a 3D deformation field or ‘(1,1,0,1,1,0)’ for a rigid transformation. Restriction currently only works if there are no preceding transformations.

  • smoothing_in_mm (boolean ; currently only impacts low dimensional registration) –

  • kwargs (keyword args) – extra arguments

Returns:

warpedmovout: Moving image warped to space of fixed image. warpedfixout: Fixed image warped to space of moving image. fwdtransforms: Transforms to move from moving to fixed image. invtransforms: Transforms to move from fixed to moving image.

Return type:

dict containing follow key/value pairs

Notes

type_of_transform can be one of:
  • “Translation”: Translation transformation.

  • “Rigid”: Rigid transformation: Only rotation and translation.

  • “Similarity”: Similarity transformation: scaling, rotation and translation.

  • “QuickRigid”: Rigid transformation: Only rotation and translation.

    May be useful for quick visualization fixes.’

  • “DenseRigid”: Rigid transformation: Only rotation and translation.

    Employs dense sampling during metric estimation.’

  • “BOLDRigid”: Rigid transformation: Parameters typical for BOLD to

    BOLD intrasubject registration’.’

  • “Affine”: Affine transformation: Rigid + scaling.

  • “AffineFast”: Fast version of Affine.

  • “BOLDAffine”: Affine transformation: Parameters typical for BOLD to

    BOLD intrasubject registration’.’

  • “TRSAA”: translation, rigid, similarity, affine (twice). please set

    regIterations if using this option. this would be used in cases where you want a really high quality affine mapping (perhaps with mask).

  • “Elastic”: Elastic deformation: Affine + deformable.

  • “ElasticSyN”: Symmetric normalization: Affine + deformable

    transformation, with mutual information as optimization metric and elastic regularization.

  • “SyN”: Symmetric normalization: Affine + deformable transformation,

    with mutual information as optimization metric.

  • “SyNRA”: Symmetric normalization: Rigid + Affine + deformable

    transformation, with mutual information as optimization metric.

  • “SyNOnly”: Symmetric normalization: no initial transformation,

    with mutual information as optimization metric. Assumes images are aligned by an inital transformation. Can be useful if you want to run an unmasked affine followed by masked deformable registration.

  • “SyNCC”: SyN, but with cross-correlation as the metric.

  • “SyNabp”: SyN optimized for abpBrainExtraction.

  • “SyNBold”: SyN, but optimized for registrations between BOLD and T1 images.

  • “SyNBoldAff”: SyN, but optimized for registrations between BOLD

    and T1 images, with additional affine step.

  • “SyNAggro”: SyN, but with more aggressive registration

    (fine-scale matching and more deformation). Takes more time than SyN.

  • “TV[n]”: time-varying diffeomorphism with where ‘n’ indicates number of

    time points in velocity field discretization. The initial transform should be computed, if needed, in a separate call to ants.registration.

  • “TVMSQ”: time-varying diffeomorphism with mean square metric

  • “TVMSQC”: time-varying diffeomorphism with mean square metric for very large deformation

  • “antsRegistrationSyN[x]”: recreation of the antsRegistrationSyN.sh script in ANTs

    where ‘x’ is one of the transforms available (e.g., ‘t’, ‘b’, ‘s’)

  • “antsRegistrationSyNQuick[x]”: recreation of the antsRegistrationSyNQuick.sh script in ANTs

    where ‘x’ is one of the transforms available (e.g., ‘t’, ‘b’, ‘s’)

  • “antsRegistrationSyNRepro[x]”: reproducible registration. x options as above.

  • “antsRegistrationSyNQuickRepro[x]”: quick reproducible registration. x options as above.

Example

>>> import ants
>>> fi = ants.image_read(ants.get_ants_data('r16'))
>>> mi = ants.image_read(ants.get_ants_data('r64'))
>>> fi = ants.resample_image(fi, (60,60), 1, 0)
>>> mi = ants.resample_image(mi, (60,60), 1, 0)
>>> mytx = ants.registration(fixed=fi, moving=mi, type_of_transform = 'SyN' )
ants.affine_initializer(fixed_image, moving_image, search_factor=20, radian_fraction=0.1, use_principal_axis=False, local_search_iterations=10, mask=None, txfn=None)[source]

A multi-start optimizer for affine registration Searches over the sphere to find a good initialization for further registration refinement, if needed. This is a arapper for the ANTs function antsAffineInitializer.

ANTsR function: affineInitializer

Parameters:
  • fixed_image (ANTsImage) – the fixed reference image

  • moving_image (ANTsImage) – the moving image to be mapped to the fixed space

  • search_factor (scalar) – degree of increments on the sphere to search

  • radian_fraction (scalar) – between zero and one, defines the arc to search over

  • use_principal_axis (boolean) – boolean to initialize by principal axis

  • local_search_iterations (scalar) – gradient descent iterations

  • mask (ANTsImage (optional)) – optional mask to restrict registration

  • txfn (string (optional)) – filename for the transformation

Returns:

transformation matrix

Return type:

ndarray

Example

>>> import ants
>>> fi = ants.image_read(ants.get_ants_data('r16'))
>>> mi = ants.image_read(ants.get_ants_data('r27'))
>>> txfile = ants.affine_initializer( fi, mi )
>>> tx = ants.read_transform(txfile, dimension=2)
ants.apply_transforms(fixed, moving, transformlist, interpolator='linear', imagetype=0, whichtoinvert=None, compose=None, defaultvalue=0, singleprecision=False, verbose=False, **kwargs)[source]

Apply a transform list to map an image from one domain to another. In image registration, one computes mappings between (usually) pairs of images. These transforms are often a sequence of increasingly complex maps, e.g. from translation, to rigid, to affine to deformation. The list of such transforms is passed to this function to interpolate one image domain into the next image domain, as below. The order matters strongly and the user is advised to familiarize with the standards established in examples.

ANTsR function: antsApplyTransforms

Parameters:
  • fixed (ANTsImage) – fixed image defining domain into which the moving image is transformed.

  • moving (AntsImage) – moving image to be mapped to fixed space.

  • transformlist (list of strings) – list of transforms generated by ants.registration where each transform is a filename.

  • interpolator (string) –

    Choice of interpolator. Supports partial matching.

    linear nearestNeighbor multiLabel for label images (deprecated, prefer genericLabel) gaussian bSpline cosineWindowedSinc welchWindowedSinc hammingWindowedSinc lanczosWindowedSinc genericLabel use this for label images

  • imagetype (python:integer) – choose 0/1/2/3 mapping to scalar/vector/tensor/time-series

  • whichtoinvert (list of booleans (optional)) – Must be same length as transformlist. whichtoinvert[i] is True if transformlist[i] is a matrix, and the matrix should be inverted. If transformlist[i] is a warp field, whichtoinvert[i] must be False. If the transform list is a matrix followed by a warp field, whichtoinvert defaults to (True,False). Otherwise it defaults to [False]*len(transformlist)).

  • compose (string (optional)) – if it is a string pointing to a valid file location, this will force the function to return a composite transformation filename.

  • defaultvalue (scalar) – Default voxel value for mappings outside the image domain.

  • singleprecision (boolean) – if True, use float32 for computations. This is useful for reducing memory usage for large datasets, at the cost of precision.

  • verbose (boolean) – print command and run verbose application of transform.

  • kwargs (keyword arguments) – extra parameters

Return type:

ANTsImage or string (transformation filename)

Example

>>> import ants
>>> fixed = ants.image_read( ants.get_ants_data('r16') )
>>> moving = ants.image_read( ants.get_ants_data('r64') )
>>> fixed = ants.resample_image(fixed, (64,64), 1, 0)
>>> moving = ants.resample_image(moving, (64,64), 1, 0)
>>> mytx = ants.registration(fixed=fixed , moving=moving ,
                             type_of_transform = 'SyN' )
>>> mywarpedimage = ants.apply_transforms( fixed=fixed, moving=moving,
                                           transformlist=mytx['fwdtransforms'] )
ants.create_jacobian_determinant_image(domain_image, tx, do_log=False, geom=False)[source]

Compute the jacobian determinant from a transformation file

ANTsR function: createJacobianDeterminantImage

Parameters:
  • domain_image (ANTsImage) – image that defines transformation domain

  • tx (string) – deformation transformation file name

  • do_log (boolean) – return the log jacobian

  • geom (bolean) – use the geometric jacobian calculation (boolean)

Return type:

ANTsImage

Example

>>> import ants
>>> fi = ants.image_read( ants.get_ants_data('r16'))
>>> mi = ants.image_read( ants.get_ants_data('r64'))
>>> fi = ants.resample_image(fi,(128,128),1,0)
>>> mi = ants.resample_image(mi,(128,128),1,0)
>>> mytx = ants.registration(fixed=fi , moving=mi, type_of_transform = ('SyN') )
>>> jac = ants.create_jacobian_determinant_image(fi,mytx['fwdtransforms'][0],1)
ants.create_warped_grid(image, grid_step=10, grid_width=2, grid_directions=(True, True), fixed_reference_image=None, transform=None, foreground=1, background=0)[source]

Deforming a grid is a helpful way to visualize a deformation field. This function enables a user to define the grid parameters and apply a deformable map to that grid.

ANTsR function: createWarpedGrid

Parameters:
  • image (ANTsImage) – input image

  • grid_step (scalar) – width of grid blocks

  • grid_width (scalar) – width of grid lines

  • grid_directions (tuple of booleans) – directions in which to draw grid lines, boolean vector

  • fixed_reference_image (ANTsImage (optional)) – reference image space

  • transform (list/tuple of strings (optional)) – vector of transforms

  • foreground (scalar) – intensity value for grid blocks

  • background (scalar) – intensity value for grid lines

Return type:

ANTsImage

Example

>>> import ants
>>> fi = ants.image_read( ants.get_ants_data( 'r16' ) )
>>> mi = ants.image_read( ants.get_ants_data( 'r64' ) )
>>> mygr = ants.create_warped_grid( mi )
>>> mytx = ants.registration(fixed=fi, moving=mi, type_of_transform = ('SyN') )
>>> mywarpedgrid = ants.create_warped_grid( mi, grid_directions=(False,True),
                        transform=mytx['fwdtransforms'], fixed_reference_image=fi )
ants.fsl2antstransform(matrix, reference, moving)[source]

Convert an FSL linear transform to an antsrTransform

ANTsR function: fsl2antsrtransform

Parameters:
  • matrix (ndarray/list) – 4x4 matrix of transform parameters

  • reference (ANTsImage) – target image

  • moving (ANTsImage) – moving image

Return type:

ANTsTransform

Examples

>>> import ants
>>> import numpy as np
>>> fslmat = np.zeros((4,4))
>>> np.fill_diagonal(fslmat, 1)
>>> img = ants.image_read(ants.get_ants_data('ch2'))
>>> tx = ants.fsl2antstransform(fslmat, img, img)
ants.image_mutual_information(image1, image2)[source]

Compute mutual information between two ANTsImage types

ANTsR function: antsImageMutualInformation

Parameters:
Return type:

scalar

Example

>>> import ants
>>> fi = ants.image_read( ants.get_ants_data('r16') ).clone('float')
>>> mi = ants.image_read( ants.get_ants_data('r64') ).clone('float')
>>> mival = ants.image_mutual_information(fi, mi) # -0.1796141
ants.reflect_image(image, axis=None, tx=None, metric='mattes')[source]

Reflect an image along an axis

ANTsR function: reflectImage

Parameters:
  • image (ANTsImage) – image to reflect

  • axis (python:integer (optional)) – which dimension to reflect across, numbered from 0 to imageDimension-1

  • tx (string (optional)) – transformation type to estimate after reflection

  • metric (string) – similarity metric for image registration. see antsRegistration.

Return type:

ANTsImage

Example

>>> import ants
>>> fi = ants.image_read( ants.get_ants_data('r16'), 'float' )
>>> axis = 2
>>> asym = ants.reflect_image(fi, axis, 'Affine')['warpedmovout']
>>> asym = asym - fi
ants.reorient_image()
ants.get_center_of_mass(image)[source]

Compute an image center of mass in physical space which is defined as the mean of the intensity weighted voxel coordinate system.

ANTsR function: getCenterOfMass

Parameters:

image (ANTsImage) – image from which center of mass will be computed

Return type:

scalar

Example

>>> fi = ants.image_read( ants.get_ants_data("r16"))
>>> com1 = ants.get_center_of_mass( fi )
>>> fi = ants.image_read( ants.get_ants_data("r64"))
>>> com2 = ants.get_center_of_mass( fi )
ants.resample_image(image, resample_params, use_voxels=False, interp_type=1)[source]

Resample image by spacing or number of voxels with various interpolators. Works with multi-channel images.

ANTsR function: resampleImage

Parameters:
  • image (ANTsImage) – input image

  • resample_params (tuple/list) – vector of size dimension with numeric values

  • use_voxels (boolean) – True means interpret resample params as voxel counts

  • interp_type (python:integer) – one of 0 (linear), 1 (nearest neighbor), 2 (gaussian), 3 (windowed sinc), 4 (bspline)

Return type:

ANTsImage

Example

>>> import ants
>>> fi = ants.image_read( ants.get_ants_data("r16"))
>>> finn = ants.resample_image(fi,(50,60),True,0)
>>> filin = ants.resample_image(fi,(1.5,1.5),False,1)
>>> img = ants.image_read( ants.get_ants_data("r16"))
>>> img = ants.merge_channels([img, img])
>>> outimg = ants.resample_image(img, (128,128), True)
ants.resample_image_to_target(image, target, interp_type='linear', imagetype=0, verbose=False, **kwargs)[source]

Resample image by using another image as target reference. This function uses ants.apply_transform with an identity matrix to achieve proper resampling.

ANTsR function: resampleImageToTarget

Parameters:
  • image (ANTsImage) – image to resample

  • target (ANTsImage) – image of reference, the output will be in this space

  • interp_type (string) –

    Choice of interpolator. Supports partial matching.

    linear nearestNeighbor multiLabel for label images but genericlabel is preferred gaussian bSpline cosineWindowedSinc welchWindowedSinc hammingWindowedSinc lanczosWindowedSinc genericLabel use this for label images

  • imagetype (python:integer) – choose 0/1/2/3 mapping to scalar/vector/tensor/time-series

  • verbose (boolean) – print command and run verbose application of transform.

  • kwargs (keyword arguments) – additional arugment passed to antsApplyTransforms C code

Return type:

ANTsImage

Example

>>> import ants
>>> fi = ants.image_read(ants.get_ants_data('r16'))
>>> fi2mm = ants.resample_image(fi, (2,2), use_voxels=0, interp_type='linear')
>>> resampled = ants.resample_image_to_target(fi2mm, fi, verbose=True)