ANTsPy functions and classes are generally faithful to the respective ANTsR versions,
with the following consistent changes in naming convention:
- camel case in ANTsR is underscore case in ANTsPy
- e.g. resampleImage -> resample_image
- anything preceeded by
ants
orantsr
in ANTsR is removed since ANTsPy uses namespaces already- e.g. antsImageRead -> ants.image_read
import ants
img = ants.image_read( ants.get_ants_data('r16') )
print(img)
Image properties are pythonic and easy to get/set:
import ants
img = ants.image_read( ants.get_ants_data('r16') )
print(img.spacing)
img.set_spacing( (2., 2.) )
print(img.origin)
img.set_origin( (100,100) )
However, we still try to keep most of the associated ANTsR functions which are stand-alone, e.g:
ants.get_spacing(img) # versus the pythonic `img.spacing`
ants.set_spacing(img, (2.,2.)) # versus `img.set_spacing`
imgclone = ants.image_clone(img) # versus img.clone()
ANTsPy provides seamless conversions to Numpy arrays. Through the use of memory buffers directly in the C++ api, these calls are instantaneous and essentially free.
import ants
img = ants.image_read( ants.get_ants_data('mni') )
img_array = img.numpy()
Do operations directly in numpy if you want, then simply make an ANTsImage right back from the numpy array (again instantaneous and "free"):
import ants
img = ants.image_read( ants.get_ants_data('mni') )
img_array = img.numpy()
img_array += 5
# copies image information and just changes the data
new_img1 = img.new_image_like(img_array)
# doesnt copy any information
new_img2 = ants.from_numpy(img_array)
# verbose way to copy information
new_img3 = ants.from_numpy(img_array, spacing=img.spacing,
origin=img.origin, direction=img.direction)
Images can be indexed (getting and setting) exactly as if they were arrays.
import ants
img = ants.image_read( ants.get_ants_data('mni') )
vals = img[200,:,:] # get a slice
img[100,:,:] = 1 # set a slice
All common mathematical operators are overloaded to work directly on ANTsImages:
import ants
import numpy as np
img = ants.image_read( ants.get_ants_data('mni') )
img2 = img.clone()
img3 = img + img2
print(np.allclose(img.numpy()+img2.numpy(), img3.numpy())) # same as if done in numpy
In ANTsR you can use the %>%
command to chain operations. That's real nice. In ANTsPy, you can
do this automatically on ANTsImages. Amazing stuff..
import ants
img = ants.image_read(ants.get_ants_data('r16'))
img = img.resample_image((64,64), 1, 0).get_mask().atropos(m = '[0.2,1x1]', c = '[2,0]', i = 'kmeans[3]', x = mask )