DeformableANTs#

class medicalimageanalysis.utils.deformable.ants.DeformableANTs(reference_image=None, moving_image=None, reference_mask=None, moving_mask=None)[source]

Bases: object

Deformable registration between a reference (fixed) and moving image with ANTs, with optional masks.

All image-based methods share the same preprocessing path (_prepare()): the moving image and masks are resampled onto the reference grid, optionally histogram matched, and optionally cropped to the union of both masks. _field() turns the ANTs transform files into one displacement field on the full reference grid.

Parameters:
  • reference_image (ants.ANTsImage, optional) – Fixed image. Its grid defines the output displacement field.

  • moving_image (ants.ANTsImage, optional) – Image to be registered onto the reference.

  • reference_mask (ants.ANTsImage, optional) – Region of interest on the reference image. Any nonzero voxel is treated as inside.

  • moving_mask (ants.ANTsImage, optional) – Region of interest on the moving image. Any nonzero voxel is treated as inside.

Examples

>>> import numpy as np
>>> from medicalimageanalysis.utils.deformable.ants import DeformableANTs
>>> helper = DeformableANTs()
>>> image = helper.create_ants_image(np.zeros((16, 32, 32), dtype=np.float32), (0, 0, 0), (1, 1, 2), np.eye(3))
>>> helper.reference_image.shape
(32, 32, 16)
create_ants_image(array, origin, spacing, direction, reference=True, mask=False)[source]

Convert a (z, y, x) NumPy array to an ANTs image and store it as the reference/moving image or mask.

Parameters:
  • array (numpy.ndarray) – Volume indexed (z, y, x). Transposed to ANTs (x, y, z) order internally.

  • origin (sequence of float) – Physical position of voxel (0, 0, 0), in (x, y, z) order.

  • spacing (sequence of float) – Voxel size in (x, y, z) order, i.e. the slice spacing is the last entry.

  • direction (numpy.ndarray) – 3x3 direction cosine matrix whose columns are the x, y, z axis directions.

  • reference (bool, default True) – Store as reference (True) or moving (False).

  • mask (bool, default False) – Store as a mask. Masks are binarized (nonzero = inside) and cast to unsigned char.

Returns:

The created (and stored) image.

Return type:

ants.ANTsImage

Examples

>>> import numpy as np
>>> helper = DeformableANTs()
>>> image = helper.create_ants_image(np.zeros((16, 32, 48), dtype=np.float32), (0, 0, 0), (1, 1, 2), np.eye(3))
>>> image.shape, image.spacing
((48, 32, 16), (1.0, 1.0, 2.0))
>>> mask = helper.create_ants_image(np.ones((16, 32, 48)), (0, 0, 0), (1, 1, 2), np.eye(3), mask=True)
>>> mask.pixeltype
'unsigned char'
groupwise(images, iterations=3, transform='SyN', gradient_step=0.2, blending_weight=0.75, initial_template=None, verbose=False)[source]

Build an unbiased template from several images and return one displacement field per image.

Uses ants.build_template (iterative average of registered images, then sharpened), then registers each image to the final template. No image is the reference, so the template has no bias toward one scan. Independent of the stored images/masks.

Parameters:
  • images (list of ants.ANTsImage) – Two or more images, already rigidly aligned.

  • iterations (int, default 3) – Template-building iterations (each registers every image to the current template).

  • transform (str, default 'SyN') – ants.registration type used while building the template and for the final fields (e.g. ‘SyN’, ‘SyNOnly’, ‘antsRegistrationSyNQuick[so]’). Types with an affine stage include it in the fields.

  • gradient_step (float, default 0.2) – Template update step (how far the template moves toward the average deformation each iteration).

  • blending_weight (float, default 0.75) – Weight of the plain average vs. the sharpened average in the template (1 = no sharpening).

  • initial_template (ants.ANTsImage, optional) – Starting template. Defaults to the average of images; its grid is the template grid.

  • verbose (bool, default False) – Print ANTs progress.

Returns:

(template, fields): the template ants.ANTsImage and one displacement field per image on the template grid. Field i maps a template point to image i (pull-back), so warping image i with it moves it into template space.

Return type:

tuple

Examples

>>> import ants
>>> import numpy as np
>>> z, y, x = np.mgrid[:16, :32, :32]
>>> base = (100 * np.exp(-((x - 16) ** 2 + (y - 16) ** 2) / 40 - (z - 8) ** 2 / 10)).astype(np.float32)
>>> images = [ants.from_numpy(np.roll(base, shift, axis=2).transpose(2, 1, 0).copy()) for shift in (-2, 0, 2)]
>>> template, fields = DeformableANTs().groupwise(images, iterations=2, transform='SyNOnly')
>>> len(fields), fields[0].shape == template.shape
(3, True)
landmark(reference_points, moving_points, transform='bspline', mesh_size=4, levels=4, regularization=1e-06, verbose=False)[source]

Fit a displacement field to corresponding point pairs (no image intensities used).

Useful for turning a surface correspondence (e.g. from a mesh registration) into a volumetric DVF. Only the reference image grid is needed; the moving image is not used.

Parameters:
  • reference_points (array_like, shape (N, 3)) – Points on the reference, physical (x, y, z) in mm.

  • moving_points (array_like, shape (N, 3)) – Corresponding points on the moving image, same order and convention.

  • transform ({'bspline', 'tps', 'diffeo', 'syn', 'tv', 'affine', 'rigid'}, default 'bspline') – ‘bspline’ = one multi-level B-spline fit (fastest). ‘tps’ = thin-plate spline (passes exactly through the points; slow for many thousands of points). ‘diffeo’ = composition of small B-spline fits (invertible). ‘syn’ = symmetric version of ‘diffeo’. ‘tv’ = time-varying velocity field (largest deformations). ‘affine’/’rigid’ fit a linear transform.

  • mesh_size (int, default 4) – B-spline mesh size (control grid cells per axis) at the coarsest level. Not used by ‘tps’.

  • levels (int, default 4) – Number of multi-level B-spline fitting levels; the mesh doubles at each level. Not used by ‘tps’.

  • regularization (float, default 1e-6) – Ridge regularization for the ‘affine’/’rigid’ fits.

  • verbose (bool, default False) – Print fitting progress.

Returns:

3-component displacement field (fixed -> moving) in mm on the full reference grid.

Return type:

ants.ANTsImage

Examples

>>> import ants
>>> import numpy as np
>>> helper = DeformableANTs(reference_image=ants.from_numpy(np.zeros((32, 32, 16), dtype=np.float32)))
>>> reference_points = np.random.default_rng(0).uniform(4, 14, size=(50, 3))
>>> dvf = helper.landmark(reference_points, reference_points + [2, 0, 0])
>>> round(float(dvf.numpy()[8, 8, 8, 0]))
2
registration(transform='SyN', metric='CC', radius=4, bins=32, iterations=(100, 70, 50, 20), shrink_factors=(8, 4, 2, 1), smoothing_sigmas=(3, 2, 1, 0), gradient_step=0.1, update_variance=3.0, total_variance=0.0, mesh_spacing=26, time_points=4, convergence=1e-06, affine=False, label_weight=0.0, labels=None, label_sigma=2.0, extra_metrics=None, histogram_match=False, winsorize=(0.005, 0.995), crop=10, seed=42, preset=None, verbose=False)[source]

Deformable registration with antsRegistration (any ANTs deformable transform and metric).

Runs one deformable stage (optionally after an affine stage) with full control over the transform, metric, pyramid and regularization. The defaults reproduce the deformable stage of antsRegistrationSyN.sh (SyN with CC, radius 4). Assumes the images are already rigidly aligned unless affine=True.

Parameters:
  • transform (str, default 'SyN') –

    ANTs deformable transform:

    • 'SyN': symmetric diffeomorphic normalization (Gaussian regularization). The standard choice.

    • 'BSplineSyN': SyN with B-spline regularization (smoother, fewer folding artifacts).

    • 'GaussianDisplacementField': dense field, Gaussian regularized (elastic/fluid; not symmetric).

    • 'BSplineDisplacementField': dense field, B-spline regularized.

    • 'TimeVaryingVelocityField': velocity field integrated over time; handles very large deformations, but is several times slower than SyN and needs more iterations to converge.

    • 'TimeVaryingBSplineVelocityField': B-spline version of the above.

    ANTs’ Exponential/BSplineExponential transforms are not offered: their optimizer barely moves with these settings (tested), so SyN is the better diffeomorphic choice.

  • metric ({'CC', 'Mattes', 'MI', 'MeanSquares', 'Demons', 'GC'}, default 'CC') – ‘CC’ = neighborhood cross correlation (best for same modality, robust to intensity drift; slowest). ‘Mattes’/’MI’ = mutual information (multimodal, faster). ‘MeanSquares’/’Demons’ = same modality with matching intensities (fastest). ‘GC’ = global correlation; one value for the whole image, so it is a weak driver for local deformation and mainly useful in the affine stage or as an extra metric.

  • radius (int, default 4) – Neighborhood radius in voxels for ‘CC’.

  • bins (int, default 32) – Histogram bins for ‘Mattes’ and ‘MI’.

  • iterations (sequence of int, default (100, 70, 50, 20)) – Iterations per resolution level, coarse to fine.

  • shrink_factors (sequence of int, default (8, 4, 2, 1)) – Image downsampling per level; same length as iterations.

  • smoothing_sigmas (sequence of float, default (3, 2, 1, 0)) – Gaussian image smoothing per level, in voxels; same length as iterations.

  • gradient_step (float, default 0.1) – Step size of each update (0.1-0.25 is typical; larger is faster but less stable).

  • update_variance (float, default 3.0) – Gaussian variance (voxels^2) of the update field (fluid-like regularization). Used by ‘SyN’, ‘GaussianDisplacementField’ and ‘TimeVaryingVelocityField’.

  • total_variance (float, default 0.0) – Gaussian variance (voxels^2) of the total field (elastic-like regularization; 0 = off, as in antsRegistrationSyN.sh). Used by ‘SyN’, ‘GaussianDisplacementField’ and ‘TimeVaryingVelocityField’.

  • mesh_spacing (float, default 26) – B-spline control point spacing in mm at the base level (the antsRegistrationSyN.sh -s default). Used by the B-spline transforms.

  • time_points (int, default 4) – Number of time points of the velocity field. Used by the time-varying transforms.

  • convergence (float, default 1e-6) – Stop a level when the metric changes less than this over the last 10 iterations.

  • affine (bool, default False) – Run a masked affine stage (MI) before the deformable stage. The affine is included in the output field.

  • label_weight (float, default 0.0) – Label guidance: weight of a MeanSquares term on Gaussian-blurred label images, relative to the intensity metric (weight 1.0). The labels drive the deformation where intensity contrast is poor (e.g. liver in non-contrast CT). 0 disables. With no labels, the stored reference_mask/moving_mask are used. Start around 0.5-1.

  • labels (list of tuple, optional) – Label pairs (reference_label, moving_label) (binary ants.ANTsImage, one pair per structure) used when label_weight > 0. Each pair adds its own term with weight label_weight.

  • label_sigma (float, default 2.0) – Gaussian blur of the labels in mm before matching, so the term has a gradient beyond the label edge.

  • extra_metrics (list of tuple, optional) – Additional metric terms for the deformable stage as (metric, fixed_image, moving_image, weight, parameter), e.g. ('MeanSquares', fixed_label_blurred, moving_label_blurred, 0.5, 0). Images must be on the reference grid (they are cropped with the main images). parameter is the radius for ‘CC’ and the number of bins for ‘Mattes’/’MI’.

  • histogram_match (bool, default False) – Histogram-match the moving image to the reference (useful for same modality with ‘MeanSquares’/’Demons’; leave off for ‘CC’/’MI’).

  • winsorize (tuple of float or None, default (0.005, 0.995)) – Lower and upper quantiles at which ANTs clips intensities before registering; None disables.

  • crop (float, default 10) – Mask-union crop margin in mm (0 disables).

  • seed (int or None, default 42) – Random seed for metric sampling, for reproducible results. None uses ANTs’ default.

  • preset (str, optional) – Instead of the custom stage above, run an ants.registration preset (e.g. 'SyNOnly', 'ElasticSyN', 'antsRegistrationSyNQuick[so]', 'antsRegistrationSyN[bo]'). Only metric, radius/bins, iterations, gradient_step, the variances, masks and crop are passed on, and only where that preset uses them; transform, affine, the label and extra metric terms, winsorize and seed are not used. Presets with an affine/rigid stage include it in the output field. Quick presets skip the full-resolution level, which can leave small cropped regions almost unregistered.

  • verbose (bool, default False) – Print the ANTs command line and progress.

Returns:

3-component displacement field (fixed -> moving) in mm on the full reference grid.

Return type:

ants.ANTsImage

Examples

>>> import numpy as np
>>> z, y, x = np.mgrid[:16, :32, :32]
>>> fixed = (100 * np.exp(-((x - 16) ** 2 + (y - 16) ** 2) / 40 - (z - 8) ** 2 / 10)).astype(np.float32)
>>> helper = DeformableANTs()
>>> _ = helper.create_ants_image(fixed, (0, 0, 0), (1, 1, 2), np.eye(3))
>>> _ = helper.create_ants_image(np.roll(fixed, 2, axis=2), (0, 0, 0), (1, 1, 2), np.eye(3), reference=False)
>>> dvf = helper.registration(metric='MeanSquares', iterations=(40, 20, 10), shrink_factors=(4, 2, 1),
...                           smoothing_sigmas=(2, 1, 0))
>>> dvf.shape, round(float(dvf.numpy()[16, 16, 8, 0]))
((32, 32, 16), 2)
>>> dvf = helper.registration(transform='BSplineSyN', metric='MeanSquares', mesh_spacing=10,
...                           iterations=(40, 20, 10), shrink_factors=(4, 2, 1), smoothing_sigmas=(2, 1, 0))
>>> round(float(dvf.numpy()[16, 16, 8, 0]))
2

Label-guided, using the stored masks:

>>> mask = (fixed > 30).astype(np.uint8)
>>> _ = helper.create_ants_image(mask, (0, 0, 0), (1, 1, 2), np.eye(3), mask=True)
>>> _ = helper.create_ants_image(np.roll(mask, 2, axis=2), (0, 0, 0), (1, 1, 2), np.eye(3), reference=False,
...                              mask=True)
>>> dvf = helper.registration(metric='MeanSquares', label_weight=1.0, iterations=(40, 20, 10),
...                           shrink_factors=(4, 2, 1), smoothing_sigmas=(2, 1, 0))
>>> round(float(dvf.numpy()[16, 16, 8, 0]))
2