ANTsPy icon indicating copy to clipboard operation
ANTsPy copied to clipboard

ENH: add components decorator

Open ncullen93 opened this issue 1 year ago • 1 comments

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.

ncullen93 avatar May 30 '24 11:05 ncullen93

Coverage Status

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

coveralls avatar May 30 '24 11:05 coveralls