ants.utils package

Submodules

ants.utils.bias_correction module

ants.utils.bias_correction.abp_n4(image, intensity_truncation=(0.025, 0.975, 256), mask=None, usen3=False)[source]

Truncate outlier intensities and bias correct with the N4 algorithm.

ANTsR function: abpN4

Parameters:
  • image (ANTsImage) – image to correct and truncate

  • intensity_truncation (3-tuple) – quantiles for intensity truncation

  • mask (ANTsImage (optional)) – mask for bias correction

  • usen3 (boolean) – if True, use N3 bias correction instead of N4

Return type:

ANTsImage

Example

>>> import ants
>>> image = ants.image_read(ants.get_ants_data('r16'))
>>> image2 = ants.abp_n4(image)
ants.utils.bias_correction.n3_bias_field_correction(image, downsample_factor=3)[source]

N3 Bias Field Correction

ANTsR function: n3BiasFieldCorrection

Parameters:
  • image (ANTsImage) – image to be bias corrected

  • downsample_factor (scalar) – how much to downsample image before performing bias correction

Return type:

ANTsImage

Example

>>> import ants
>>> image = ants.image_read( ants.get_ants_data('r16') )
>>> image_n3 = ants.n3_bias_field_correction(image)
ants.utils.bias_correction.n3_bias_field_correction2(image, mask=None, rescale_intensities=False, shrink_factor=4, convergence={'iters': 50, 'tol': 1e-07}, spline_param=None, number_of_fitting_levels=4, return_bias_field=False, verbose=False, weight_mask=None)[source]

N3 Bias Field Correction

ANTsR function: n3BiasFieldCorrection2

Parameters:
  • image (ANTsImage) – image to bias correct

  • mask (ANTsImage) – Input mask. If not specified, the entire image is used.

  • rescale_intensities (boolean) – At each iteration, a new intensity mapping is calculated and applied but there is nothing which constrains the new intensity range to be within certain values. The result is that the range can “drift” from the original at each iteration. This option rescales to the [min,max] range of the original image intensities within the user-specified mask. A mask is required to perform rescaling. Default is False in ANTsR/ANTsPy but True in ANTs.

  • shrink_factor (scalar) – Shrink factor for multi-resolution correction, typically integer less than 4

  • convergence (dict w/ keys iters and tol) – iters : maximum number of iterations tol : the convergence tolerance. Default tolerance is 1e-7 in ANTsR/ANTsPy but 0.0 in ANTs.

  • spline_param (float or vector Parameter controlling number of control) – points in spline. Either single value, indicating the spacing in each direction, or vector with one entry per dimension of image, indicating the mesh size. If None, defaults to mesh size of 1 in all dimensions.

  • number_of_fitting_levels (python:integer) – Number of fitting levels per iteration.

  • return_bias_field (boolean) – Return bias field instead of bias corrected image.

  • verbose (boolean) – enables verbose output.

  • weight_mask (ANTsImage (optional)) – antsImage of weight mask

Return type:

ANTsImage

Example

>>> image = ants.image_read( ants.get_ants_data('r16') )
>>> image_n3 = ants.n3_bias_field_correction2(image)
ants.utils.bias_correction.n4_bias_field_correction(image, mask=None, rescale_intensities=False, shrink_factor=4, convergence={'iters': [50, 50, 50, 50], 'tol': 1e-07}, spline_param=None, return_bias_field=False, verbose=False, weight_mask=None)[source]

N4 Bias Field Correction

ANTsR function: n4BiasFieldCorrection

Parameters:
  • image (ANTsImage) – image to bias correct

  • mask (ANTsImage) – Input mask. If not specified, the entire image is used.

  • rescale_intensities (boolean) – At each iteration, a new intensity mapping is calculated and applied but there is nothing which constrains the new intensity range to be within certain values. The result is that the range can “drift” from the original at each iteration. This option rescales to the [min,max] range of the original image intensities within the user-specified mask. A mask is required to perform rescaling. Default is False in ANTsR/ANTsPy but True in ANTs.

  • shrink_factor (scalar) – Shrink factor for multi-resolution correction, typically integer less than 4

  • convergence (dict w/ keys iters and tol) – iters : vector of maximum number of iterations for each level tol : the convergence tolerance. Default tolerance is 1e-7 in ANTsR/ANTsPy but 0.0 in ANTs.

  • spline_param (float or vector) – Parameter controlling number of control points in spline. Either single value, indicating the spacing in each direction, or vector with one entry per dimension of image, indicating the mesh size. If None, defaults to mesh size of 1 in all dimensions.

  • return_bias_field (boolean) – Return bias field instead of bias corrected image.

  • verbose (boolean) – enables verbose output.

  • weight_mask (ANTsImage (optional)) – antsImage of weight mask

Return type:

ANTsImage

Example

>>> image = ants.image_read( ants.get_ants_data('r16') )
>>> image_n4 = ants.n4_bias_field_correction(image)

ants.utils.channels module

ants.utils.channels.merge_channels(image_list)[source]

Merge channels of multiple scalar ANTsImage types into one multi-channel ANTsImage

ANTsR function: mergeChannels

Parameters:

image_list (list/tuple of ANTsImage python:types) – scalar images to merge

Return type:

ANTsImage

Example

>>> import ants
>>> image = ants.image_read(ants.get_ants_data('r16'), 'float')
>>> image2 = ants.image_read(ants.get_ants_data('r16'), 'float')
>>> image3 = ants.merge_channels([image,image2])
>>> image3.components == 2
ants.utils.channels.split_channels(image)[source]

Split channels of a multi-channel ANTsImage into a collection of scalar ANTsImage types

Parameters:

image (ANTsImage) – multi-channel image to split

Return type:

list of ANTsImage types

Example

>>> import ants
>>> image = ants.image_read(ants.get_ants_data('r16'), 'float')
>>> image2 = ants.image_read(ants.get_ants_data('r16'), 'float')
>>> imagemerge = ants.merge_channels([image,image2])
>>> imagemerge.components == 2
>>> images_unmerged = ants.split_channels(imagemerge)
>>> len(images_unmerged) == 2
>>> images_unmerged[0].components == 1

ants.utils.convert_nibabel module

ants.utils.convert_nibabel.from_nibabel(nib_image)[source]

Convert a nibabel image to an ANTsImage

ants.utils.convert_nibabel.nifti_to_ants(nib_image)[source]

Converts a given Nifti image into an ANTsPy image

Parameters:

img (NiftiImage) –

Returns:

ants_image

Return type:

ANTsImage

ants.utils.convert_nibabel.to_nibabel(image)[source]

Convert an ANTsImage to a Nibabel image

ants.utils.crop_image module

ants.utils.crop_image.crop_image(image, label_image=None, label=1)[source]

Use a label image to crop a smaller ANTsImage from within a larger ANTsImage

ANTsR function: cropImage

Parameters:
  • image (ANTsImage) – image to crop

  • label_image (ANTsImage) – image with label values. If not supplied, estimated from data.

  • label (python:integer) – the label value to use

Return type:

ANTsImage

Example

>>> import ants
>>> fi = ants.image_read( ants.get_ants_data('r16') )
>>> cropped = ants.crop_image(fi)
>>> cropped = ants.crop_image(fi, fi, 100 )
ants.utils.crop_image.crop_indices(image, lowerind, upperind)[source]

Create a proper ANTsImage sub-image by indexing the image with indices. This is similar to but different from array sub-setting in that the resulting sub-image can be decropped back into its place without having to store its original index locations explicitly.

ANTsR function: cropIndices

Parameters:
  • image (ANTsImage) – image to crop

  • lowerind (list/tuple of python:integers) – vector of lower index, should be length image dimensionality

  • upperind (list/tuple of python:integers) – vector of upper index, should be length image dimensionality

Return type:

ANTsImage

Example

>>> import ants
>>> fi = ants.image_read( ants.get_ants_data("r16"))
>>> cropped = ants.crop_indices( fi, (10,10), (100,100) )
>>> cropped = ants.smooth_image( cropped, 5 )
>>> decropped = ants.decrop_image( cropped, fi )
ants.utils.crop_image.decrop_image(cropped_image, full_image)[source]

The inverse function for ants.crop_image

ANTsR function: decropImage

Parameters:
  • cropped_image (ANTsImage) – cropped image

  • full_image (ANTsImage) – image in which the cropped image will be put back

Return type:

ANTsImage

Example

>>> import ants
>>> fi = ants.image_read(ants.get_ants_data('r16'))
>>> mask = ants.get_mask(fi)
>>> cropped = ants.crop_image(fi, mask, 1)
>>> cropped = ants.smooth_image(cropped, 1)
>>> decropped = ants.decrop_image(cropped, fi)

ants.utils.denoise_image module

ants.utils.denoise_image.denoise_image(image, mask=None, shrink_factor=1, p=1, r=3, noise_model='Rician', v=0)[source]

Denoise an image using a spatially adaptive filter originally described in J. V. Manjon, P. Coupe, Luis Marti-Bonmati, D. L. Collins, and M. Robles. Adaptive Non-Local Means Denoising of MR Images With Spatially Varying Noise Levels, Journal of Magnetic Resonance Imaging, 31:192-203, June 2010.

ANTsR function: denoiseImage

Parameters:
  • image (ANTsImage) – scalar image to denoise.

  • mask (ANTsImage) – to limit the denoise region.

  • shrink_factor (scalar) – downsampling level performed within the algorithm.

  • p (python:integer or character of format '2x2' where the x separates vector entries) – patch radius for local sample.

  • r (python:integer or character of format '2x2' where the x separates vector entries) – search radius from which to choose extra local samples.

  • noise_model (string) – ‘Rician’ or ‘Gaussian’

Return type:

ANTsImage

Example

>>> import ants
>>> import numpy as np
>>> image = ants.image_read(ants.get_ants_data('r16'))
>>> # add fairly large salt and pepper noise
>>> imagenoise = image + np.random.randn(*image.shape).astype('float32')*5
>>> imagedenoise = ants.denoise_image(imagenoise, ants.get_mask(image))

ants.utils.get_ants_data module

Get local ANTsPy data

ants.utils.get_ants_data.get_ants_data(file_id=None, target_file_name=None, antsx_cache_directory=None)

Get ANTsPy test data file

ANTsR function: getANTsRData

Parameters:

name (string) –

name of test image tag to retrieve Options:

  • ’r16’

  • ’r27’

  • ’r30’

  • ’r62’

  • ’r64’

  • ’r85’

  • ’ch2’

  • ’mni’

  • ’surf’

  • ’pcasl’

Returns:

filepath of test image

Return type:

string

Example

>>> import ants
>>> mnipath = ants.get_ants_data('mni')
ants.utils.get_ants_data.get_data(file_id=None, target_file_name=None, antsx_cache_directory=None)[source]

Get ANTsPy test data file

ANTsR function: getANTsRData

Parameters:

name (string) –

name of test image tag to retrieve Options:

  • ’r16’

  • ’r27’

  • ’r30’

  • ’r62’

  • ’r64’

  • ’r85’

  • ’ch2’

  • ’mni’

  • ’surf’

  • ’pcasl’

Returns:

filepath of test image

Return type:

string

Example

>>> import ants
>>> mnipath = ants.get_ants_data('mni')

ants.utils.get_centroids module

ants.utils.get_centroids.get_centroids(image, clustparam=0)[source]

Reduces a variate/statistical/network image to a set of centroids describing the center of each stand-alone non-zero component in the image

ANTsR function: getCentroids

Parameters:
  • image (ANTsImage) – image from which centroids will be calculated

  • clustparam (python:integer) – look at regions greater than or equal to this size

Return type:

ndarray

Example

>>> import ants
>>> image = ants.image_read( ants.get_ants_data( "r16" ) )
>>> image = ants.threshold_image( image, 90, 120 )
>>> image = ants.label_clusters( image, 10 )
>>> cents = ants.get_centroids( image )

ants.utils.get_mask module

ants.utils.get_mask.get_mask(image, low_thresh=None, high_thresh=None, cleanup=2)[source]

Get a binary mask image from the given image after thresholding

ANTsR function: getMask

Parameters:
  • image (ANTsImage) – image from which mask will be computed. Can be an antsImage of 2, 3 or 4 dimensions.

  • low_thresh (scalar (optional)) – An inclusive lower threshold for voxels to be included in the mask. If not given, defaults to image mean.

  • high_thresh (scalar (optional)) – An inclusive upper threshold for voxels to be included in the mask. If not given, defaults to image max

  • cleanup (python:integer) –

    If > 0, morphological operations will be applied to clean up the mask by eroding away small or weakly-connected areas, and closing holes. If cleanup is >0, the following steps are applied

    1. Erosion with radius 2 voxels

    2. Retain largest component

    3. Dilation with radius 1 voxel

    4. Morphological closing

Return type:

ANTsImage

Example

>>> import ants
>>> image = ants.image_read( ants.get_ants_data('r16') )
>>> mask = ants.get_mask(image)

ants.utils.get_neighborhood module

ants.utils.get_neighborhood.get_neighborhood_at_voxel(image, center, kernel, physical_coordinates=False)[source]

Get a hypercube neighborhood at a voxel. Get the values in a local neighborhood of an image.

ANTsR function: getNeighborhoodAtVoxel

Parameters:
  • image (ANTsImage) – image to get values from.

  • center (tuple/list) – indices for neighborhood center

  • kernel (tuple/list) – either a collection of values for neighborhood radius (in voxels) or a binary collection of the same dimension as the image, specifying the shape of the neighborhood to extract

  • physical_coordinates (boolean) – whether voxel indices and offsets should be in voxel or physical coordinates

Returns:

valuesndarray

array of neighborhood values at the voxel

indicesndarray

matrix providing the coordinates for each value

Return type:

dictionary w/ following key-value pairs

Example

>>> import ants
>>> img = ants.image_read(ants.get_ants_data('r16'))
>>> center = (2,2)
>>> radius = (3,3)
>>> retval = ants.get_neighborhood_at_voxel(img, center, radius)
ants.utils.get_neighborhood.get_neighborhood_in_mask(image, mask, radius, physical_coordinates=False, boundary_condition=None, spatial_info=False, get_gradient=False)[source]

Get neighborhoods for voxels within mask.

This converts a scalar image to a matrix with rows that contain neighbors around a center voxel

ANTsR function: getNeighborhoodInMask

Parameters:
  • image (ANTsImage) – image to get values from

  • mask (ANTsImage) – image indicating which voxels to examine. Each voxel > 0 will be used as the center of a neighborhood

  • radius (tuple/list) – array of values for neighborhood radius (in voxels)

  • physical_coordinates (boolean) – whether voxel indices and offsets should be in voxel or physical coordinates

  • boundary_condition (string (optional)) –

    how to handle voxels in a neighborhood, but not in the mask.

    None : fill values with NaN image : use image value, even if not in mask mean : use mean of all non-NaN values for that neighborhood

  • spatial_info (boolean) – whether voxel locations and neighborhood offsets should be returned along with pixel values.

  • get_gradient (boolean) – whether a matrix of gradients (at the center voxel) should be returned in addition to the value matrix (WIP)

Returns:

  • if spatial_info is False

    if get_gradient is False:
    ndarray

    an array of pixel values where the number of rows is the size of the neighborhood and there is a column for each voxel

    else if get_gradient is True:
    dictionary w/ following key-value pairs:
    valuesndarray

    array of pixel values where the number of rows is the size of the neighborhood and there is a column for each voxel.

    gradientsndarray

    array providing the gradients at the center voxel of each neighborhood

  • else if spatial_info is True

    dictionary w/ following key-value pairs:
    valuesndarray

    array of pixel values where the number of rows is the size of the neighborhood and there is a column for each voxel.

    indicesndarray

    array provinding the center coordinates for each neighborhood

    offsetsndarray

    array providing the offsets from center for each voxel in a neighborhood

Example

>>> import ants
>>> r16 = ants.image_read(ants.get_ants_data('r16'))
>>> mask = ants.get_mask(r16)
>>> mat = ants.get_neighborhood_in_mask(r16, mask, radius=(2,2))

ants.utils.iMath module

ants.utils.iMath.iMath(image, operation, *args)[source]

Perform various (often mathematical) operations on the input image/s. Additional parameters should be specific for each operation. See the the full iMath in ANTs, on which this function is based.

ANTsR function: iMath

Parameters:
  • image (ANTsImage) – input object, usually antsImage

  • operation – a string e.g. “GetLargestComponent” … the special case of “GetOperations” or “GetOperationsFull” will return a list of operations and brief description. Some operations may not be valid (WIP), but most are.

  • *args (non-keyword arguments) – additional parameters specific to the operation

Example

>>> import ants
>>> img = ants.image_read(ants.get_ants_data('r16'))
>>> img2 = ants.iMath(img, 'Canny', 1, 5, 12)
ants.utils.iMath.iMath_GC(image, radius=1)[source]
ants.utils.iMath.iMath_GD(image, radius=1)[source]
ants.utils.iMath.iMath_GE(image, radius=1)[source]
ants.utils.iMath.iMath_GO(image, radius=1)[source]
ants.utils.iMath.iMath_MC(image, radius=1, value=1, shape=1, parametric=False, lines=3, thickness=1, include_center=False)[source]
ants.utils.iMath.iMath_MD(image, radius=1, value=1, shape=1, parametric=False, lines=3, thickness=1, include_center=False)[source]
ants.utils.iMath.iMath_ME(image, radius=1, value=1, shape=1, parametric=False, lines=3, thickness=1, include_center=False)[source]
ants.utils.iMath.iMath_MO(image, radius=1, value=1, shape=1, parametric=False, lines=3, thickness=1, include_center=False)[source]
ants.utils.iMath.iMath_canny(image, sigma, lower, upper)[source]
ants.utils.iMath.iMath_fill_holes(image, hole_type=2)[source]
ants.utils.iMath.iMath_get_largest_component(image, min_size=50)[source]
ants.utils.iMath.iMath_grad(image, sigma=0.5, normalize=False)[source]
ants.utils.iMath.iMath_histogram_equalization(image, alpha, beta)[source]
ants.utils.iMath.iMath_laplacian(image, sigma=0.5, normalize=False)[source]
ants.utils.iMath.iMath_maurer_distance(image, foreground=1)[source]
ants.utils.iMath.iMath_normalize(image)[source]
ants.utils.iMath.iMath_pad(image, padding)[source]
ants.utils.iMath.iMath_perona_malik(image, conductance=0.25, n_iterations=1)[source]
ants.utils.iMath.iMath_propagate_labels_through_mask(image, labels, stopping_value=100, propagation_method=0)[source]
>>> import ants
>>> wms = ants.image_read('~/desktop/wms.nii.gz')
>>> thal = ants.image_read('~/desktop/thal.nii.gz')
>>> img2 = ants.iMath_propagate_labels_through_mask(wms, thal, 500, 0)
ants.utils.iMath.iMath_sharpen(image)[source]
ants.utils.iMath.iMath_truncate_intensity(image, lower_q, upper_q, n_bins=64)[source]
>>> import ants
>>> img = ants.image_read(ants.get_ants_data('r16'))
>>> ants.iMath_truncate_intensity( img, 0.2, 0.8 )
ants.utils.iMath.image_math(image, operation, *args)

Perform various (often mathematical) operations on the input image/s. Additional parameters should be specific for each operation. See the the full iMath in ANTs, on which this function is based.

ANTsR function: iMath

Parameters:
  • image (ANTsImage) – input object, usually antsImage

  • operation – a string e.g. “GetLargestComponent” … the special case of “GetOperations” or “GetOperationsFull” will return a list of operations and brief description. Some operations may not be valid (WIP), but most are.

  • *args (non-keyword arguments) – additional parameters specific to the operation

Example

>>> import ants
>>> img = ants.image_read(ants.get_ants_data('r16'))
>>> img2 = ants.iMath(img, 'Canny', 1, 5, 12)
ants.utils.iMath.multiply_images(image1, image2)[source]

ants.utils.image_similarity module

ants.utils.image_similarity.image_similarity(fixed_image, moving_image, metric_type='MeanSquares', fixed_mask=None, moving_mask=None, sampling_strategy='regular', sampling_percentage=1.0)[source]

Measure similarity between two images. NOTE: Similarity is actually returned as distance (i.e. dissimilarity) per ITK/ANTs convention. E.g. using Correlation metric, the similarity of an image with itself returns -1.

ANTsR function: imageSimilarity

Parameters:
  • fixed (ANTsImage) – the fixed image

  • moving (ANTsImage) – the moving image

  • metric_type (string) –

    image metric to calculate

    MeanSquares Correlation ANTSNeighborhoodCorrelation MattesMutualInformation JointHistogramMutualInformation Demons

  • fixed_mask (ANTsImage (optional)) – mask for the fixed image

  • moving_mask (ANTsImage (optional)) – mask for the moving image

  • sampling_strategy (string (optional)) –

    sampling strategy, default is full sampling

    None (Full sampling) random regular

  • sampling_percentage (scalar) – percentage of data to sample when calculating metric Must be between 0 and 1

Return type:

scalar

Example

>>> import ants
>>> x = ants.image_read(ants.get_ants_data('r16'))
>>> y = ants.image_read(ants.get_ants_data('r30'))
>>> metric = ants.image_similarity(x,y,metric_type='MeanSquares')

ants.utils.image_to_cluster_images module

ants.utils.image_to_cluster_images.image_to_cluster_images(image, min_cluster_size=50, min_thresh=1e-06, max_thresh=1)[source]

Converts an image to several independent images.

Produces a unique image for each connected component 1 through N of size > min_cluster_size

ANTsR function: image2ClusterImages

Parameters:
  • image (ANTsImage) – input image

  • min_cluster_size (python:integer) – throw away clusters smaller than this value

  • min_thresh (scalar) – threshold to a statistical map

  • max_thresh (scalar) – threshold to a statistical map

Return type:

list of ANTsImage types

Example

>>> import ants
>>> image = ants.image_read(ants.get_ants_data('r16'))
>>> image = ants.threshold_image(image, 1, 1e15)
>>> image_cluster_list = ants.image_to_cluster_images(image)

ants.utils.impute module

ants.utils.impute.impute(data, method='mean', value=None, nan_value=nan)[source]

Impute missing values on a numpy ndarray in a column-wise manner.

ANTsR function: antsrimpute

Parameters:
  • data (numpy.ndarray) – data to impute

  • method (string or float) –

    type of imputation method to use Options:

    mean median constant KNN BiScaler NuclearNormMinimization SoftImpute IterativeSVD

  • value (scalar (optional)) –

    optional arguments for different methods if method == ‘constant’

    constant value

    if method == ‘KNN’

    number of nearest neighbors to use

  • nan_value (scalar) – value which is interpreted as a missing value

Returns:

  • ndarray if ndarray was given

  • OR

  • pd.DataFrame if pd.DataFrame was given

Example

>>> import ants
>>> import numpy as np
>>> data = np.random.randn(4,10)
>>> data[2,3] = np.nan
>>> data[3,5] = np.nan
>>> data_imputed = ants.impute(data, 'mean')

Details

KNN: Nearest neighbor imputations which weights samples using the mean squared

difference on features for which two rows both have observed data.

SoftImpute: Matrix completion by iterative soft thresholding of SVD

decompositions. Inspired by the softImpute package for R, which is based on Spectral Regularization Algorithms for Learning Large Incomplete Matrices by Mazumder et. al.

IterativeSVD: Matrix completion by iterative low-rank SVD decomposition.

Should be similar to SVDimpute from Missing value estimation methods for DNA microarrays by Troyanskaya et. al.

MICE: Reimplementation of Multiple Imputation by Chained Equations.

MatrixFactorization: Direct factorization of the incomplete matrix into

low-rank U and V, with an L1 sparsity penalty on the elements of U and an L2 penalty on the elements of V. Solved by gradient descent.

NuclearNormMinimization: Simple implementation of Exact Matrix Completion

via Convex Optimization by Emmanuel Candes and Benjamin Recht using cvxpy. Too slow for large matrices.

BiScaler: Iterative estimation of row/column means and standard deviations

to get doubly normalized matrix. Not guaranteed to converge but works well in practice. Taken from Matrix Completion and Low-Rank SVD via Fast Alternating Least Squares.

ants.utils.invariant_image_similarity module

ants.utils.invariant_image_similarity.convolve_image(image, kernel_image, crop=True)[source]

Convolve one image with another

ANTsR function: convolveImage

Parameters:
  • image (ANTsImage) – image to convolve

  • kernel_image (ANTsImage) – image acting as kernel

  • crop (boolean) – whether to automatically crop kernel_image

Return type:

ANTsImage

Example

>>> import ants
>>> fi = ants.image_read(ants.get_ants_data('r16'))
>>> convimg = ants.make_image( (3,3), (1,0,1,0,-4,0,1,0,1) )
>>> convout = ants.convolve_image( fi, convimg )
>>> convimg2 = ants.make_image( (3,3), (0,1,0,1,0,-1,0,-1,0) )
>>> convout2 = ants.convolve_image( fi, convimg2 )
ants.utils.invariant_image_similarity.invariant_image_similarity(image1, image2, local_search_iterations=0, metric='MI', thetas=array([0., 90., 180., 270., 360.]), thetas2=array([0., 90., 180., 270., 360.]), thetas3=array([0., 90., 180., 270., 360.]), scale_image=1, do_reflection=False, txfn=None, transform='Affine')[source]

Similarity metrics between two images as a function of geometry

Compute similarity metric between two images as image is rotated about its center w/ or w/o optimization

ANTsR function: invariantImageSimilarity

Parameters:
  • image1 (ANTsImage) – reference image

  • image2 (ANTsImage) – moving image

  • local_search_iterations (python:integer) – integer controlling local search in multistart

  • metric (string) –

    which metric to use

    MI GC

  • thetas (1D-ndarray/list/tuple) – numeric vector of search angles in degrees

  • thetas2 (1D-ndarray/list/tuple) – numeric vector of search angles in degrees around principal axis 2 (3D)

  • thetas3 (1D-ndarray/list/tuple) – numeric vector of search angles in degrees around principal axis 3 (3D)

  • scale_image (scalar) – global scale

  • do_reflection (boolean) – whether to reflect image about principal axis

  • txfn (string (optional)) – if present, write optimal tx to .mat file

  • transform (string) –

    type of transform to use

    Rigid Similarity Affine

Returns:

dataframe with metric values and transformation parameters

Return type:

pd.DataFrame

Example

>>> import ants
>>> img1 = ants.image_read(ants.get_ants_data('r16'))
>>> img2 = ants.image_read(ants.get_ants_data('r64'))
>>> metric = ants.invariant_image_similarity(img1,img2)

ants.utils.label_clusters module

ants.utils.label_clusters.label_clusters(image, min_cluster_size=50, min_thresh=1e-06, max_thresh=1, fully_connected=False)[source]

This will give a unique ID to each connected component 1 through N of size > min_cluster_size

ANTsR function: labelClusters

Parameters:
  • image (ANTsImage) – input image e.g. a statistical map

  • min_cluster_size (python:integer) – throw away clusters smaller than this value

  • min_thresh (scalar) – threshold to a statistical map

  • max_thresh (scalar) – threshold to a statistical map

  • fully_connected (boolean) – boolean sets neighborhood connectivity pattern

Return type:

ANTsImage

Example

>>> import ants
>>> image = ants.image_read( ants.get_ants_data('r16') )
>>> timageFully = ants.label_clusters( image, 10, 128, 150, True )
>>> timageFace = ants.label_clusters( image, 10, 128, 150, False )

ants.utils.label_image_centroids module

ants.utils.label_image_centroids.label_image_centroids(image, physical=False, convex=True, verbose=False)[source]

Converts a label image to coordinates summarizing their positions

ANTsR function: labelImageCentroids

Parameters:
  • image (ANTsImage) – image of integer labels

  • physical (boolean) – whether you want physical space coordinates or not

  • convex (boolean) – if True, return centroid if False return point with min average distance to other points with same label

Returns:

labels1D-ndarray

array of label values

verticespd.DataFrame

coordinates of label centroids

Return type:

dictionary w/ following key-value pairs

Example

>>> import ants
>>> import numpy as np
>>> image = ants.from_numpy(np.asarray([[[0,2],[1,3]],[[4,6],[5,7]]]).astype('float32'))
>>> labels = ants.label_image_centroids(image)

ants.utils.label_stats module

ants.utils.label_stats.label_stats(image, label_image)[source]

Get label statistics from image

ANTsR function: labelStats

Parameters:
  • image (ANTsImage) – Image from which statistics will be calculated

  • label_image (ANTsImage) – Label image

Return type:

ndarray ?

Example

>>> import ants
>>> image = ants.image_read( ants.get_ants_data('r16') , 2 )
>>> image = ants.resample_image( image, (64,64), 1, 0 )
>>> mask = ants.get_mask(image)
>>> segs1 = ants.kmeans_segmentation( image, 3 )
>>> stats = ants.label_stats(image, segs1['segmentation'])

ants.utils.labels_to_matrix module

ants.utils.labels_to_matrix.labels_to_matrix(image, mask, target_labels=None, missing_val=nan)[source]

Convert a labeled image to an n x m binary matrix where n = number of voxels and m = number of labels. Only includes values inside the provided mask while including background ( image == 0 ) for consistency with timeseries2matrix and other image to matrix operations.

ANTsR function: labels2matrix

Parameters:
  • image (ANTsImage) – input label image

  • mask (ANTsImage) – defines domain of interest

  • target_labels (list/tuple) – defines target regions to be returned. if the target label does not exist in the input label image, then the matrix will contain a constant value of missing_val (default None) in that row.

  • missing_val (scalar) – value to use for missing label values

Return type:

ndarray

Example

>>> import ants
>>> fi = ants.image_read(ants.get_ants_data('r16')).resample_image((60,60),1,0)
>>> mask = ants.get_mask(fi)
>>> labs = ants.kmeans_segmentation(fi,3)['segmentation']
>>> labmat = ants.labels_to_matrix(labs, mask)

ants.utils.mask_image module

ants.utils.mask_image.mask_image(image, mask, level=1, binarize=False)[source]

Mask an input image by a mask image. If the mask image has multiple labels, it is possible to specify which label(s) to mask at.

ANTsR function: maskImage

Parameters:
  • image (ANTsImage) – Input image.

  • mask (ANTsImage) – Mask or label image.

  • level (scalar or tuple of scalars) – Level(s) at which to mask image. If vector or list of values, output image is non-zero at all locations where label image matches any of the levels specified.

  • binarize (boolean) – whether binarize the output image

Return type:

ANTsImage

Example

>>> import ants
>>> myimage = ants.image_read(ants.get_ants_data('r16'))
>>> mask = ants.get_mask(myimage)
>>> myimage_mask = ants.mask_image(myimage, mask, 3)
>>> seg = ants.kmeans_segmentation(myimage, 3)
>>> myimage_mask = ants.mask_image(myimage, seg['segmentation'], (1,3))

ants.utils.mni2tal module

ants.utils.mni2tal.mni2tal(xin)[source]

mni2tal for converting from ch2/mni space to tal - very approximate.

This is a standard approach but it’s not very accurate.

ANTsR function: mni2tal

Parameters:

xin (tuple) – point in mni152 space.

Return type:

tuple

Example

>>> import ants
>>> ants.mni2tal( (10,12,14) )

References

http://bioimagesuite.yale.edu/mni2tal/501_95733_More%20Accurate%20Talairach%20Coordinates%20SLIDES.pdf http://imaging.mrc-cbu.cam.ac.uk/imaging/MniTalairach

ants.utils.morphology module

ants.utils.morphology.morphology(image, operation, radius, mtype='binary', value=1, shape='ball', radius_is_parametric=False, thickness=1, lines=3, include_center=False)[source]

Apply morphological operations to an image

ANTsR function: morphology

Parameters:
  • input (ANTsImage) – input image

  • operation (string) –

    operation to apply

    ”close” Morpholgical closing “dilate” Morpholgical dilation “erode” Morpholgical erosion “open” Morpholgical opening

  • radius (scalar) – radius of structuring element

  • mtype (string) –

    type of morphology

    ”binary” Binary operation on a single value “grayscale” Grayscale operations

  • value (scalar) – value to operation on (type=’binary’ only)

  • shape (string) –

    shape of the structuring element ( type=’binary’ only )

    ”ball” spherical structuring element “box” box shaped structuring element “cross” cross shaped structuring element “annulus” annulus shaped structuring element “polygon” polygon structuring element

  • radius_is_parametric (boolean) – used parametric radius boolean (shape=’ball’ and shape=’annulus’ only)

  • thickness (scalar) – thickness (shape=’annulus’ only)

  • lines (python:integer) – number of lines in polygon (shape=’polygon’ only)

  • include_center (boolean) – include center of annulus boolean (shape=’annulus’ only)

Return type:

ANTsImage

Example

>>> import ants
>>> fi = ants.image_read( ants.get_ants_data('r16') , 2 )
>>> mask = ants.get_mask( fi )
>>> dilated_ball = ants.morphology( mask, operation='dilate', radius=3, mtype='binary', shape='ball')
>>> eroded_box = ants.morphology( mask, operation='erode', radius=3, mtype='binary', shape='box')
>>> opened_annulus = ants.morphology( mask, operation='open', radius=5, mtype='binary', shape='annulus', thickness=2)

ants.utils.multi_label_morphology module

Morphology operations on multi-label ANTsImage types

ants.utils.multi_label_morphology.multi_label_morphology(image, operation, radius, dilation_mask=None, label_list=None, force=False)[source]

Morphology on multi label images.

Wraps calls to iMath binary morphology. Additionally, dilation and closing operations preserve pre-existing labels. The choices of operation are:

Dilation: dilates all labels sequentially, but does not overwrite original labels. This reduces dependence on the intensity ordering of adjoining labels. Ordering dependence can still arise if two or more labels dilate into the same space - in this case, the label with the lowest intensity is retained. With a mask, dilated labels are multiplied by the mask and then added to the original label, thus restricting dilation to the mask region.

Erosion: Erodes labels independently, equivalent to calling iMath iteratively.

Closing: Close holes in each label sequentially, but does not overwrite original labels.

Opening: Opens each label independently, equivalent to calling iMath iteratively.

Parameters:
  • image (ANTsImage) – Input image should contain only 0 for background and positive integers for labels.

  • operation (string) – One of MD, ME, MC, MO, passed to iMath.

  • radius (python:integer) – radius of the morphological operation.

  • dilation_mask (ANTsImage) – Optional binary mask to constrain dilation only (eg dilate cortical label into WM).

  • label_list (list or tuple or numpy.ndarray) – Optional list of labels, to perform operation upon. Defaults to all unique intensities in image.

Return type:

ANTsImage

Example

>>> import ants
>>> img = ants.image_read(ants.get_data('r16'))
>>> labels = ants.get_mask(img,1,150) + ants.get_mask(img,151,225) * 2
>>> labels_dilated = ants.multi_label_morphology(labels, 'MD', 2)
>>> # should see original label regions preserved in dilated version
>>> # label N should have mean N and 0 variance
>>> print(ants.label_stats(labels_dilated, labels))

ants.utils.ndimage_to_list module

ants.utils.ndimage_to_list.list_to_ndimage(image, image_list)[source]

Merge list of multiple scalar ANTsImage types of dimension into one ANTsImage of dimension plus one

ANTsR function: mergeListToNDImage

Parameters:
  • image (target image space) –

  • image_list (list/tuple of ANTsImage python:types) – scalar images to merge into target image space

Return type:

ANTsImage

Example

>>> import ants
>>> image = ants.image_read(ants.get_ants_data('r16'))
>>> image2 = ants.image_read(ants.get_ants_data('r16'))
>>> imageTar = ants.make_image( ( *image2.shape, 2 ) )
>>> image3 = ants.list_to_ndimage( imageTar, [image,image2])
>>> image3.dimension == 3
ants.utils.ndimage_to_list.ndimage_to_list(image)[source]

Split a n dimensional ANTsImage into a list of n-1 dimensional ANTsImages

Parameters:

image (ANTsImage) – n-dimensional image to split

Return type:

list of ANTsImage types

Example

>>> import ants
>>> image = ants.image_read(ants.get_ants_data('r16'))
>>> image2 = ants.image_read(ants.get_ants_data('r16'))
>>> imageTar = ants.make_image( ( *image2.shape, 2 ) )
>>> image3 = ants.list_to_ndimage( imageTar, [image,image2])
>>> image3.dimension == 3
>>> images_unmerged = ants.ndimage_to_list( image3 )
>>> len(images_unmerged) == 2
>>> images_unmerged[0].dimension == 2

ants.utils.pad_image module

ants.utils.pad_image.pad_image(image, shape=None, pad_width=None, value=0.0, return_padvals=False)[source]

Pad an image to have the given shape or to be isotropic.

Parameters:
  • image (ANTsImage) – image to pad

  • shape (tuple) –

    • if shape is given, the image will be padded in each dimension until it has this shape

    • if shape and pad_width are both None, the image will be padded along each dimension to match the largest existing dimension so that it has isotropic dimensions.

  • pad_width (list of python:integers or list-of-list of python:integers) – How much to pad in each direction. If a single list is supplied (e.g., [4,4,4]), then the image will be padded by half that amount on both sides. If a list-of-list is supplied (e.g., [(0,4),(0,4),(0,4)]), then the image will be padded unevenly on the different sides

  • pad_value (scalar) – value with which image will be padded

Example

>>> import ants
>>> img = ants.image_read(ants.get_data('r16'))
>>> img2 = ants.pad_image(img, shape=(300,300))
>>> mni = ants.image_read(ants.get_data('mni'))
>>> mni2 = ants.pad_image(mni)
>>> mni3 = ants.pad_image(mni, pad_width=[(0,4),(0,4),(0,4)])
>>> mni4 = ants.pad_image(mni, pad_width=(4,4,4))

ants.utils.process_args module

ants.utils.process_args.get_lib_fn(string)[source]
ants.utils.process_args.get_pointer_string(image)[source]
ants.utils.process_args.short_ptype(pixeltype)[source]

ants.utils.quantile module

ants.utils.quantile.bandpass_filter_matrix(matrix, tr=1, lowf=0.01, highf=0.1, order=3)[source]

Bandpass filter the input time series image

ANTsR function: frequencyFilterfMRI

Parameters:
  • image (input time series image) –

  • tr (sampling time python:interval (inverse of sampling rate)) –

  • lowf (low frequency cutoff) –

  • highf (high frequency cutoff) –

  • order (order of the butterworth filter run using filtfilt) –

Return type:

filtered matrix

Example

>>> import numpy as np
>>> import ants
>>> import matplotlib.pyplot as plt
>>> brainSignal = np.random.randn( 400, 1000 )
>>> tr = 1
>>> filtered = ants.bandpass_filter_matrix( brainSignal, tr = tr )
>>> nsamples = brainSignal.shape[0]
>>> t = np.linspace(0, tr*nsamples, nsamples, endpoint=False)
>>> k = 20
>>> plt.plot(t, brainSignal[:,k], label='Noisy signal')
>>> plt.plot(t, filtered[:,k], label='Filtered signal')
>>> plt.xlabel('time (seconds)')
>>> plt.grid(True)
>>> plt.axis('tight')
>>> plt.legend(loc='upper left')
>>> plt.show()
ants.utils.quantile.compcor(boldImage, ncompcor=4, quantile=0.975, mask=None, filter_type=False, degree=2)[source]

Compute noise components from the input image

ANTsR function: compcor

this is adapted from nipy code https://github.com/nipy/nipype/blob/e29ac95fc0fc00fedbcaa0adaf29d5878408ca7c/nipype/algorithms/confounds.py

Parameters:
  • boldImage (input time series image) –

  • ncompcor (number of noise components to return) –

  • quantile (quantile defining high-variance) –

  • mask (mask defining brain or specific tissues) –

  • filter_type (python:type off filter to apply to time series before computing) –

    noise components.

    ’polynomial’ - Legendre polynomial basis False - None (mean-removal only)

  • degree (order of polynomial used to remove trends from the timeseries) –

Returns:

components: a numpy array

basis: a numpy array containing the (non-constant) filter regressors

Return type:

dictionary containing

Example

>>> cc = ants.compcor( ants.image_read(ants.get_ants_data("ch2")) )
ants.utils.quantile.get_average_of_timeseries(image, idx=None)[source]

Average the timeseries into a dimension-1 image. image: input time series image idx: indices over which to average

ants.utils.quantile.ilr(data_frame, voxmats, ilr_formula, verbose=False)[source]

Image-based linear regression.

This function simplifies calculating p-values from linear models in which there is a similar formula that is applied many times with a change in image-based predictors. Image-based variables are stored in the input matrix list. They should be named consistently in the input formula and in the image list. If they are not, an error will be thrown. All input matrices should have the same number of rows and columns.

This function takes advantage of statsmodels R-style formulas.

ANTsR function: ilr

Parameters:
  • data_frame (This data frame contains all relevant predictors except for) – the matrices associated with the image variables. One should convert any categorical predictors ahead of time using pd.get_dummies.

  • voxmats (The named list of matrices that contains the changing) – predictors.

  • ilr_formula (This is a character string that defines a valid regression) – formula in the R-style.

  • verbose (will prpython:int a little bit of diagnostic information that allows) – a degree of model checking

Returns:

  • A list of different matrices that contain names derived from the

  • formula and the coefficients of the regression model. The size of

  • the output values ( p-values, t-values, parameter values ) will match

  • the input matrix and, as such, can be converted to an image via make_image

Example

>>> nsub = 20
>>> mu, sigma = 0, 1
>>> outcome = np.random.normal( mu, sigma, nsub )
>>> covar = np.random.normal( mu, sigma, nsub )
>>> mat = np.random.normal( mu, sigma, (nsub, 500 ) )
>>> mat2 = np.random.normal( mu, sigma, (nsub, 500 ) )
>>> data = {'covar':covar,'outcome':outcome}
>>> df = pd.DataFrame( data )
>>> vlist = { "mat1": mat, "mat2": mat2 }
>>> myform = " outcome ~ covar * mat1 "
>>> result = ilr( df, vlist, myform)
>>> myform = " mat2 ~ covar + mat1 "
>>> result = ants.ilr( df, vlist, myform)
ants.utils.quantile.quantile(image, q, nonzero=True)[source]

Get the quantile values from an ANTsImage

ants.utils.quantile.rank_intensity(x, mask=None, get_mask=True, method='max')[source]

Rank transform the intensity of the input image with or without masking. Intensities will transform from [0,1,2,55] to [0,1,2,3] so this may not be appropriate for quantitative images - however, you never know. rank transformations generally improve robustness so it is an empirical question that should be evaluated.

Parameters:
  • x (ANTsImage) – input image

  • mask (ANTsImage) – optional mask

  • get_mask (boolean) – will estimate a mask when none provided

  • method (a scipy rank method (max,min,average,dense)) –

return: transformed image

Example

>>> rank_intensity( some_image )
ants.utils.quantile.regress_components(data, components, remove_mean=True)[source]

Returns data with components regressed out. :param bool remove_mean: whether or not demean data (i.e. degree 0), :param int axis: numpy array axes along which regression is performed

ants.utils.quantile.regress_poly(degree, data, remove_mean=True, axis=-1)[source]

Returns data with degree polynomial regressed out. :param bool remove_mean: whether or not demean data (i.e. degree 0), :param int axis: numpy array axes along which regression is performed

ants.utils.scalar_rgb_vector module

ants.utils.scalar_rgb_vector.rgb_to_vector(image)[source]

Convert an RGB ANTsImage to a Vector ANTsImage

Parameters:

image (ANTsImage) – RGB image to be converted

Return type:

ANTsImage

Example

>>> import ants
>>> mni = ants.image_read(ants.get_data('mni'))
>>> mni_rgb = mni.scalar_to_rgb()
>>> mni_vector = mni.rgb_to_vector()
>>> mni_rgb2 = mni.vector_to_rgb()
ants.utils.scalar_rgb_vector.scalar_to_rgb(image, mask=None, filename=None, cmap='red', custom_colormap_file=None, min_input=None, max_input=None, min_rgb_output=None, max_rgb_output=None, vtk_lookup_table=None)[source]

Usage: ConvertScalarImageToRGB imageDimension inputImage outputImage mask colormap [customColormapFile] [minimumInput] [maximumInput] [minimumRGBOutput=0] [maximumRGBOutput=255] <vtkLookupTable> Possible colormaps: grey, red, green, blue, copper, jet, hsv, spring, summer, autumn, winter, hot, cool, overunder, custom

Example

>>> import ants
>>> img = ants.image_read(ants.get_data('r16'))
>>> img_color = img.scalar_to_rgb(cmap='jet')
ants.utils.scalar_rgb_vector.vector_to_rgb(image)[source]

Convert an Vector ANTsImage to a RGB ANTsImage

Parameters:

image (ANTsImage) – RGB image to be converted

Return type:

ANTsImage

Example

>>> import ants
>>> img = ants.image_read(ants.get_data('r16'), pixeltype='unsigned char')
>>> img_rgb = img.clone().scalar_to_rgb()
>>> img_vec = img_rgb.rgb_to_vector()
>>> img_rgb2 = img_vec.vector_to_rgb()

ants.utils.slice_image module

ants.utils.slice_image.slice_image(image, axis, idx, collapse_strategy=0)[source]

Slice an image.

Parameters:
  • axis (python:integer) – Which axis.

  • idx (python:integer) – Which slice number.

  • collapse_strategy (python:integer) – Collapse strategy for sub-matrix: 0, 1, or 2. 0: collapse to sub-matrix if positive-definite. Otherwise throw an exception. Default. 1: Collapse to identity. 2: Collapse to sub-matrix if positive definite. Otherwise collapse to identity.

Example

>>> import ants
>>> mni = ants.image_read(ants.get_data('mni'))
>>> mni2 = ants.slice_image(mni, axis=1, idx=100)

ants.utils.smooth_image module

ants.utils.smooth_image.smooth_image(image, sigma, sigma_in_physical_coordinates=True, FWHM=False, max_kernel_width=32)[source]

Smooth an image

ANTsR function: smoothImage

Parameters:
  • image – Image to smooth

  • sigma – Smoothing factor. Can be scalar, in which case the same sigma is applied to each dimension, or a vector of length dim(inimage) to specify a unique smoothness for each dimension.

  • sigma_in_physical_coordinates (boolean) – If true, the smoothing factor is in millimeters; if false, it is in pixels.

  • FWHM (boolean) – If true, sigma is interpreted as the full-width-half-max (FWHM) of the filter, not the sigma of a Gaussian kernel.

  • max_kernel_width (scalar) – Maximum kernel width

Return type:

ANTsImage

Example

>>> import ants
>>> image = ants.image_read( ants.get_ants_data('r16'))
>>> simage = ants.smooth_image(image, (1.2,1.5))

ants.utils.threshold_image module

ants.utils.threshold_image.threshold_image(image, low_thresh=None, high_thresh=None, inval=1, outval=0, binary=True)[source]

Converts a scalar image into a binary image by thresholding operations

ANTsR function: thresholdImage

Parameters:
  • image (ANTsImage) – Input image to operate on

  • low_thresh (scalar (optional)) – Lower edge of threshold window

  • hight_thresh (scalar (optional)) – Higher edge of threshold window

  • inval (scalar) – Output value for image voxels in between lothresh and hithresh

  • outval (scalar) – Output value for image voxels lower than lothresh or higher than hithresh

  • binary (boolean) – if true, returns binary thresholded image if false, return binary thresholded image multiplied by original image

Return type:

ANTsImage

Example

>>> import ants
>>> image = ants.image_read( ants.get_ants_data('r16') )
>>> timage = ants.threshold_image(image, 0.5, 1e15)

ants.utils.weingarten_image_curvature module

ants.utils.weingarten_image_curvature.weingarten_image_curvature(image, sigma=1.0, opt='mean')[source]

Uses the weingarten map to estimate image mean or gaussian curvature

ANTsR function: weingartenImageCurvature

Parameters:
  • image (ANTsImage) – image from which curvature is calculated

  • sigma (scalar) – smoothing parameter

  • opt (string) – mean by default, otherwise gaussian or characterize

Return type:

ANTsImage

Example

>>> import ants
>>> image = ants.image_read(ants.get_ants_data('mni')).resample_image((3,3,3))
>>> imagecurv = ants.weingarten_image_curvature(image)

Module contents