ANTsX / ANTsPy

A fast medical imaging analysis library in Python with algorithms for registration, segmentation, and more.
https://antspyx.readthedocs.io
Apache License 2.0
586 stars 161 forks source link

ENH: add components decorator #670

Open ncullen93 opened 1 month ago

ncullen93 commented 1 month ago

There are many functions that do not natively support vector images in the C++ but can work in the Python code by splitting the image, applying the function to each component, and then merging the image back. Such functions look like this:

@image_method
def crop_image(image):
   if image.has_components:
      return ants.merge_channels([crop_image(img) for img in ants.split_channels(image)])
   libfn = get_lib_fn('cropImage')
   return ants.from_pointer(libfn(image.pointer))

This PR removes that first if-statement by adding a decorator called @components_method. This decorator will let you add such split-apply-merge support to any function. It saves code and is more robust, so the function will now look like this:

@image_method
@components_method
def crop_image(image):
   libfn = get_lib_fn('cropImage')
   return ants.from_pointer(libfn(image.pointer))

And now the function knows to do the split-apply-merge thing if the image has components.

NOTE that this should not be applied to functions that natively support component images in the C++ code (although it wont really hurt I think), but I think that is very few of them.

coveralls commented 1 month ago

Coverage Status

coverage: 84.728% (+0.04%) from 84.688% when pulling 95f46ad4a7463a9e6de6cab2f98553ee726acece on components-decorator into c4f0e324b7475167242e45ae1b8aed892efbf289 on master.