Registration
- 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, verbose=False, multivariate_extras=None, restrict_transformation=None, smoothing_in_mm=False, singleprecision=True, use_legacy_histogram_matching=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 (
ants.core.ANTsImage) – fixed image to which we register the moving image.moving (
ants.core.ANTsImage) – moving image to be mapped to fixed space.type_of_transform (
str) – A linear or non-linear registration type. Mutual information metric by default. See Notes below for more.initial_transform (
listofstrings (optional)) – transforms to prepend. If None, a translation is computed to align the image centers of mass, unless the type of transform is deformable-only (time-varying diffeomorphisms, SyNOnly, or antsRegistrationSyN*[so|bo]). To force initialization with an identity transform, set this to ‘Identity’.outprefix (
str) – 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 (
bool) – 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 fieldaff_metric (
str) – the metric for the affine part (GC, mattes, meansquares)aff_sampling (
scalar) – number of bins for the mutual information metricaff_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 (
str) – the metric for the syn part (CC, mattes, meansquares, demons)syn_sampling (
scalar) – the nbins or radius parameter for the syn metricreg_iterations (
list/tupleofintegers) – vector of iterations for syn. we will set the smoothing and multi-resolution parameters based on the length of this vector.aff_iterations (
list/tupleofintegers) – vector of iterations for low-dimensional (translation, rigid, affine) registration.aff_shrink_factors (
list/tupleofintegers) – vector of multi-resolution shrink factors for low-dimensional (translation, rigid, affine) registration.aff_smoothing_sigmas (
list/tupleofintegers) – vector of multi-resolution smoothing factors for low-dimensional (translation, rigid, affine) registration.write_composite_transform (
bool) – 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 (
bool) – 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 usertorestrict 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) –singleprecision (
bool) – if True, use float32 for computations. This is useful for reducing memory usage for large datasets, at the cost of precision.use_legacy_histogram_matching (
bool) – if True, use the original histogram matching in ANTs. This is not recommended, but is available for backwards compatibilty with earlier versions, where it was always turned on. The default is False. A better implementation of histogram matching is available in the ants.histogram_match_image2 function.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
The output dict contains file names, designed to be used with ants.apply_transforms. As in ANTs, the forward affine transform .mat file is present in both the fwdtransforms and invtransforms lists. The matrix is inverted at run time by ants.apply_transforms when applying an inverse transform (see its whichtoinvert parameter).
- type_of_transform can be one of:
“Translation”: Translation transformation.
“Rigid”: Rigid transformation: Only rotation and translation.
“Similarity”: Similarity transformation: uniform 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 + shear (12 parameters).
“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 with no rigid or affine stages.
Uses mutual information as optimization metric.
“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.
“SyNLessAggro”: Does exactly the same thing as “SyNAggro”.
- “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:
t: translation (1 stage) r: rigid (1 stage) a: rigid + affine (2 stages) s: rigid + affine + deformable syn (3 stages) sr: rigid + deformable syn (2 stages) so: deformable syn only (1 stage) b: rigid + affine + deformable b-spline syn (3 stages) br: rigid + deformable b-spline syn (2 stages) bo: deformable b-spline syn only (1 stage)
- “antsRegistrationSyNQuick[x]”: recreation of the antsRegistrationSyNQuick.sh script in ANTs.
x options as above.
“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' ) >>> mytx = ants.registration(fixed=fi, moving=mi, type_of_transform = 'antsRegistrationSyN[t]' ) >>> mytx = ants.registration(fixed=fi, moving=mi, type_of_transform = 'antsRegistrationSyN[b]' ) >>> mytx = ants.registration(fixed=fi, moving=mi, type_of_transform = 'antsRegistrationSyN[s]' )
- 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 wrapper for the ANTs function antsAffineInitializer.
ANTsR function: affineInitializer
- Parameters:
fixed_image (
ants.core.ANTsImage) – the fixed reference imagemoving_image (
ants.core.ANTsImage) – the moving image to be mapped to the fixed spacesearch_factor (
scalar) – degree of increments on the sphere to searchradian_fraction (
scalar) – between zero and one, defines the arc to search overuse_principal_axis (
bool) – boolean to initialize by principal axislocal_search_iterations (
scalar) – gradient descent iterationsmask (
ANTsImage (optional)) – optional mask to restrict registrationtxfn (
string (optional)) – filename for the transformation
- Returns:
transformation matrix
- Return type:
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)
- 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 (
ants.core.ANTsImage) – fixed image defining domain into which the moving image is transformed. The output will have the same pixel type as this image.moving (
AntsImage) – moving image to be mapped to fixed space.transformlist (
listofstrings) – list of transforms generated by ants.registration where each transform is a filename.interpolator (
str) –- 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 (
int) –choose 0/1/2/3/4 mapping to scalar/vector/tensor/time-series/multi-channel images.
Default is 0 (scalar).
Vectors and tensors are assumed to be stored in index coordinates, and will be rebased into the fixed index space. They will also be reoriented to account for the physical rotation component of the transform.
whichtoinvert (
listofbooleans (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 (
bool) – if True, use float32 for computations. This is useful for reducing memory usage for large datasets, at the cost of precision.verbose (
bool) – print command and run verbose application of transform.kwargs (
keyword arguments) – extra parameters
- Return type:
ants.core.ANTsImageorstring (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'] )
- 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:
- Return type:
ants.core.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)
- 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 (
ants.core.ANTsImage) – input imagegrid_step (
scalar) – width of grid blocksgrid_width (
scalar) – width of grid linesgrid_directions (
tupleofbooleans) – directions in which to draw grid lines, boolean vectorfixed_reference_image (
ANTsImage (optional)) – reference image spacetransform (
list/tupleofstrings (optional)) – vector of transformsforeground (
scalar) – intensity value for grid blocksbackground (
scalar) – intensity value for grid lines
- Return type:
ants.core.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( mygr, grid_directions=(False,True), transform=mytx['fwdtransforms'], fixed_reference_image=fi )
- fsl2antstransform(matrix, reference, moving)[source]
Convert an FSL linear transform to an antsrTransform
ANTsR function: fsl2antsrtransform
- Parameters:
matrix (
ndarray/list) – 4x4 matrix of transform parametersreference (
ants.core.ANTsImage) – target imagemoving (
ants.core.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)
- image_mutual_information(image1, image2)[source]
Compute mutual information between two ANTsImage types
ANTsR function: antsImageMutualInformation
- Parameters:
image1 (
ants.core.ANTsImage) – image 1image2 (
ants.core.ANTsImage) – image 2
- 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
- reflect_image(image, axis=None, tx=None, metric='mattes')[source]
Reflect an image along an axis
ANTsR function: reflectImage
- Parameters:
image (
ants.core.ANTsImage) – image to reflectaxis (
integer (optional)) – which dimension to reflect across, numbered from 0 to imageDimension-1tx (
string (optional)) – transformation type to estimate after reflectionmetric (
str) – similarity metric for image registration. see antsRegistration.
- Return type:
ants.core.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
- reorient_image()
- 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 (
ants.core.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 )
- 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:
- Return type:
ants.core.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)
- 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 (
ants.core.ANTsImage) – image to resampletarget (
ants.core.ANTsImage) – image of reference, the output will be in this space and will have the same pixel type.interp_type (
str) –- 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 (
int) – choose 0/1/2/3 mapping to scalar/vector/tensor/time-seriesverbose (
bool) – print command and run verbose application of transform.kwargs (
keyword arguments) – additional arugment passed to antsApplyTransforms C code
- Return type:
ants.core.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)