Utilities¶
-
ants.
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
Returns: Return type: Example
>>> import ants >>> image = ants.image_read( ants.get_ants_data('r16') ) >>> image_n3 = ants.n3_bias_field_correction(image)
-
ants.
n4_bias_field_correction
(image, mask=None, shrink_factor=4, convergence={'iters': [50, 50, 50, 50], 'tol': 1e-07}, spline_param=200, 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 one is not passed one will be made
- 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 shrinkage factor tol : the convergence tolerance.
- spline_param (integer) – Parameter controlling number of control points in spline. Either single value, indicating how many control points, or vector with one entry per dimension of image, indicating the spacing in each direction.
- verbose (boolean) – enables verbose output.
- weight_mask (ANTsImage (optional)) – antsImage of weight mask
Returns: Return type: Example
>>> image = ants.image_read( ants.get_ants_data('r16') ) >>> image_n4 = ants.n4_bias_field_correction(image)
-
ants.
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: Returns: Return type: Example
>>> import ants >>> image = ants.image_read(ants.get_ants_data('r16')) >>> image2 = ants.abp_n4(image)
-
ants.
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 Returns: 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.
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 Returns: 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.
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: Returns: Return type: 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.
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
Returns: Return type: 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.
decrop_image
(cropped_image, full_image)[source]¶ The inverse function for ants.crop_image
ANTsR function: decropImage
Parameters: Returns: Return type: 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.
denoise_image
(image, mask=None, shrink_factor=1, p=1, r=3, noise_model='Rician')[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 (integer) – patch radius for local sample.
- r (integer) – search radius from which to choose extra local samples.
- noise_model (string) – ‘Rician’ or ‘Gaussian’
Returns: Return type: 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.
get_ants_data
(name=None)¶ Get ANTsPy test data filename
ANTsR function: getANTsRData
Parameters: name (string) – name of test image tag to retrieve Options:
- ‘r16’
- ‘r27’
- ‘r64’
- ‘r85’
- ‘ch2’
- ‘mni’
- ‘surf’
Returns: filepath of test image Return type: string Example
>>> import ants >>> mnipath = ants.get_ants_data('mni')
-
ants.
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 (integer) – look at regions greater than or equal to this size
Returns: 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.
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 (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
- Erosion with radius 2 voxels
- Retain largest component
- Dilation with radius 1 voxel
- Morphological closing
Returns: Return type: Example
>>> import ants >>> image = ants.image_read( ants.get_ants_data('r16') ) >>> mask = ants.get_mask(image)
-
ants.
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
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
Returns: 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.
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 (integer) – throw away clusters smaller than this value
- min_thresh (scalar) – threshold to a statistical map
- max_thresh (scalar) – threshold to a statistical map
Returns: 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.
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.
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')
- 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.
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 (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.
convolve_image
(image, kernel_image, crop=True)[source]¶ Convolve one image with another
ANTsR function: convolveImage
Parameters: Returns: Return type: 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.
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 (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
Returns: Return type: 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.
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: - labels : 1D-ndarray
array of label values
- vertices : pd.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.
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
Returns: Return type: 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.
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. Returns: 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.
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 (integer) – number of lines in polygon (shape=’polygon’ only)
- include_center (boolean) – include center of annulus boolean (shape=’annulus’ only)
Returns: Return type: 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.
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
Returns: Return type: Example
>>> import ants >>> image = ants.image_read( ants.get_ants_data('r16')) >>> simage = ants.smooth_image(image, (1.2,1.5))
-
ants.
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
Returns: Return type: Example
>>> import ants >>> image = ants.image_read( ants.get_ants_data('r16') ) >>> timage = ants.threshold_image(image, 0.5, 1e15)
-
ants.
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: Returns: Return type: Example
>>> import ants >>> image = ants.image_read(ants.get_ants_data('mni')).resample_image((3,3,3)) >>> imagecurv = ants.weingarten_image_curvature(image)