From 14a555a47060eabc75fbf443b7af14b2a30119ce Mon Sep 17 00:00:00 2001 From: Nick Tustison Date: Fri, 16 Feb 2024 13:24:27 -0800 Subject: [PATCH] ENH: Histogram equalization --- ants/utils/__init__.py | 1 + ants/utils/histogram_equalize_image.py | 38 ++++++++++++++++++++++++++ 2 files changed, 39 insertions(+) create mode 100644 ants/utils/histogram_equalize_image.py diff --git a/ants/utils/__init__.py b/ants/utils/__init__.py index f13af7f8..0b379019 100644 --- a/ants/utils/__init__.py +++ b/ants/utils/__init__.py @@ -17,6 +17,7 @@ from .get_neighborhood import (get_neighborhood_in_mask, get_neighborhood_at_voxel) from .histogram_match_image import histogram_match_image +from .histogram_equalize_image import histogram_equalize_image from .hausdorff_distance import hausdorff_distance from .image_similarity import image_similarity from .image_to_cluster_images import image_to_cluster_images diff --git a/ants/utils/histogram_equalize_image.py b/ants/utils/histogram_equalize_image.py new file mode 100644 index 00000000..88c7db46 --- /dev/null +++ b/ants/utils/histogram_equalize_image.py @@ -0,0 +1,38 @@ +__all__ = ['histogram_equalize_image'] + +import numpy as np + +from .. import core + +def histogram_equalize_image(image, number_of_histogram_bins=256): + """ + Histogram equalize image + + # from http://www.janeriksolem.net/histogram-equalization-with-python-and.html + + Arguments + --------- + image : ANTsImage + source image + + number_of_histogram_bins : integer + number of bins for cumulative histogram + + Example + ------- + >>> import ants + >>> src_img = ants.image_read(ants.get_data('r16')) + >>> src_img_eq = ants.histogram_equalize_image(src_img) + """ + + image_array = image.numpy() + image_histogram, bins = np.histogram(image_array.flatten(), number_of_histogram_bins, density=True) + cdf = image_histogram.cumsum() + cdf = (number_of_histogram_bins-1) * cdf / cdf[-1] + image_array_equalized_flat = np.interp(image_array.flatten(), bins[:-1], cdf) + image_array_equalized = image_array_equalized_flat.reshape(image_array.shape) + image_equalized = core.from_numpy(image_array_equalized) + + return core.copy_image_info(image, image_equalized) + +