diff --git a/src/machinevisiontoolbox/ImageWholeFeatures.py b/src/machinevisiontoolbox/ImageWholeFeatures.py index 9ee301e8..7117a1be 100644 --- a/src/machinevisiontoolbox/ImageWholeFeatures.py +++ b/src/machinevisiontoolbox/ImageWholeFeatures.py @@ -869,6 +869,41 @@ def peak2d( return ret[:, -1], ret[:, :2].T +# Histogram comparison methods. hellinger is another name for bhattacharyya, which is +# the same calculation in OpenCV. emd has no OpenCV constant: it is computed directly. +_HISTOGRAM_COMPARE_METHODS: dict[str, int | None] = { + "correlation": cv2.HISTCMP_CORREL, + "chisqr": cv2.HISTCMP_CHISQR, + "intersection": cv2.HISTCMP_INTERSECT, + "bhattacharyya": cv2.HISTCMP_BHATTACHARYYA, + "hellinger": cv2.HISTCMP_BHATTACHARYYA, + "chisqr_alt": cv2.HISTCMP_CHISQR_ALT, + "kl_div": cv2.HISTCMP_KL_DIV, + "emd": None, +} + + +def _resolve_compare_method(method: str) -> str: + """Map a method name, or a unique abbreviation of one, to its full name. + + An exact match wins, so ``"chisqr"`` is not ambiguous with ``"chisqr_alt"``. + Otherwise the abbreviation must match the start of exactly one method, or of + several names for the same method (``"b"``, ``"h"``). + """ + name = method.lower() + if name in _HISTOGRAM_COMPARE_METHODS: + return name + matches = [m for m in _HISTOGRAM_COMPARE_METHODS if m.startswith(name)] + if matches and len({_HISTOGRAM_COMPARE_METHODS[m] for m in matches}) == 1: + return matches[0] + choices = ", ".join(_HISTOGRAM_COMPARE_METHODS) + if matches: + raise ValueError( + f"ambiguous comparison method {method!r}, it could be: {', '.join(matches)}" + ) + raise ValueError(f"unknown comparison method {method!r}, choose from: {choices}") + + class Histogram: def __init__( self, @@ -1208,6 +1243,103 @@ def ncdf(self) -> np.ndarray: ) return self.cdf + def compare(self, other: "Histogram", method: str = "correlation") -> float | list[float]: + """ + Compare with another histogram + + :param other: histogram to compare with + :param method: comparison method, see below, case insensitive and can be + abbreviated to any unique prefix, defaults to "correlation" + :raises ValueError: the histograms have a different number of bins or planes + :raises ValueError: unknown or ambiguous method + :return: comparison metric, a list if the histograms have more than one plane + :rtype: float or list of float + + Compares each plane of this histogram with the same plane of ``other``, + using the histogram counts. Both are first normalized to sum to one, see + :meth:`pdf`, so the histograms can come from images of different sizes. + The histograms must have the same number of bins. + + The methods are the six of OpenCV's ``compareHist`` and the earth mover's + distance. For a pair of histograms :math:`H_1` (this one) and :math:`H_2` + (``other``): + + - ``"correlation"``: Pearson correlation coefficient, from -1 to 1. A larger + value means more similar. + - ``"chisqr"``: chi-squared distance, normalized by :math:`H_1`. A smaller + value means more similar. + - ``"intersection"``: sum of the smaller of each pair of bins, from 0 to 1. + A larger value means more similar. + - ``"bhattacharyya"``: Bhattacharyya distance, from 0 to 1, also called + ``"hellinger"``. A smaller value means more similar. + - ``"chisqr_alt"``: alternative chi-squared distance, which is symmetric. A + smaller value means more similar. + - ``"kl_div"``: Kullback-Leibler divergence of :math:`H_2` from :math:`H_1`. + A smaller value means more similar. + - ``"emd"``: earth mover's distance (L1), in units of bins. A smaller value + means more similar. + + .. note:: ``h1.compare(h2)`` is not always the same as ``h2.compare(h1)``. + ``"chisqr"`` and ``"kl_div"`` are not symmetric in the two histograms. + The other methods are. + + .. note:: The earth mover's distance is the minimum amount of "work" needed + to turn one histogram into the other, where moving a fraction of the + pixels by one bin costs that fraction. For 1D histograms it is the sum + of the absolute differences of the two cumulative distributions. + + Example: + + .. runblock:: pycon + + >>> from machinevisiontoolbox import Image + >>> h1 = Image.Read("flowers1.png", mono=True).hist() + >>> h2 = Image.Read("flowers2.png", mono=True).hist() + >>> h1.compare(h2, "correlation") + >>> h1.compare(h2, "kl") # abbreviation of "kl_div" + >>> h2.compare(h1, "kl") # not the same + + :seealso: :meth:`pdf` :meth:`cdf` `cv2.compareHist `_ + + .. versionadded:: 2.5.0 + """ + name = _resolve_compare_method(method) + + if not isinstance(other, Histogram): + raise TypeError("can only compare with another Histogram") + if self.nplanes != other.nplanes: + raise ValueError( + f"histograms have different numbers of planes: {self.nplanes} and {other.nplanes}" + ) + if len(self._x) != len(other._x): + raise ValueError( + f"histograms have different numbers of bins: {len(self._x)} and {len(other._x)}" + ) + if np.any(np.sum(self._h, axis=0) == 0) or np.any(np.sum(other._h, axis=0) == 0): + raise ValueError("cannot compare an empty histogram") + + # one column per plane, normalized to sum to one + p1 = self.pdf.reshape(len(self._x), -1) + p2 = other.pdf.reshape(len(other._x), -1) + + cvmethod = _HISTOGRAM_COMPARE_METHODS[name] + result: list[float] = [] + for k in range(p1.shape[1]): + if cvmethod is None: + # earth mover's distance (L1) for 1D histograms, in units of bins + d = float(np.sum(np.abs(np.cumsum(p1[:, k] - p2[:, k])))) + else: + d = float( + cv2.compareHist( + np.ascontiguousarray(p1[:, k], dtype=np.float32), + np.ascontiguousarray(p2[:, k], dtype=np.float32), + cvmethod, + ) + ) + result.append(d) + + return result[0] if self.nplanes == 1 else result + def plot( self, type: Literal[ diff --git a/tests/test_image_whole_features.py b/tests/test_image_whole_features.py index 4c739542..724b77aa 100644 --- a/tests/test_image_whole_features.py +++ b/tests/test_image_whole_features.py @@ -525,5 +525,113 @@ def test_plot_type_ncdf_deprecated_alias(self): plt.close("all") +class TestHistogramCompare(unittest.TestCase): + @staticmethod + def _hist(seed, size=(40, 40), planes=None, **kwargs): + rng = np.random.default_rng(seed) + shape = size if planes is None else (*size, planes) + # a different skew for each seed so that the histograms differ + a = (rng.random(shape) ** (1 + seed) * 255).astype(np.uint8) + return Image(a).hist(**kwargs) + + def test_identical(self): + h = self._hist(1) + expect = { + "correlation": 1, + "chisqr": 0, + "intersection": 1, + "bhattacharyya": 0, + "chisqr_alt": 0, + "kl_div": 0, + "emd": 0, + } + for method, value in expect.items(): + with self.subTest(method=method): + self.assertAlmostEqual(h.compare(h, method), value, places=5) + + def test_returns_float(self): + h1, h2 = self._hist(1), self._hist(2) + for method in ("correlation", "chisqr", "intersection", "bhattacharyya", "chisqr_alt", "kl_div", "emd"): + with self.subTest(method=method): + self.assertIsInstance(h1.compare(h2, method), float) + + def test_default_is_correlation(self): + h1, h2 = self._hist(1), self._hist(2) + self.assertEqual(h1.compare(h2), h1.compare(h2, "correlation")) + + def test_emd_is_distance_in_bins(self): + h1 = Image(np.zeros((5, 5), dtype=np.uint8)).hist() + h2 = Image(np.full((5, 5), 3, dtype=np.uint8)).hist() + self.assertAlmostEqual(h1.compare(h2, "emd"), 3.0) + self.assertAlmostEqual(h2.compare(h1, "emd"), 3.0) + self.assertAlmostEqual(h1.compare(h2, "intersection"), 0.0) + + def test_asymmetry(self): + h1, h2 = self._hist(1), self._hist(3) + for method in ("chisqr", "kl_div"): + with self.subTest(method=method): + self.assertNotAlmostEqual(h1.compare(h2, method), h2.compare(h1, method), places=3) + for method in ("correlation", "intersection", "bhattacharyya", "chisqr_alt", "emd"): + with self.subTest(method=method): + self.assertAlmostEqual(h1.compare(h2, method), h2.compare(h1, method), places=5) + + def test_image_size_does_not_matter(self): + small = Image(np.tile(np.arange(256, dtype=np.uint8), (4, 1))) + large = Image(np.tile(np.arange(256, dtype=np.uint8), (16, 1))) + self.assertAlmostEqual(small.hist().compare(large.hist(), "correlation"), 1.0, places=5) + self.assertAlmostEqual(small.hist().compare(large.hist(), "emd"), 0.0, places=5) + + def test_abbreviations(self): + h1, h2 = self._hist(1), self._hist(2) + self.assertEqual(h1.compare(h2, "CORR"), h1.compare(h2, "correlation")) + self.assertEqual(h1.compare(h2, "Inter"), h1.compare(h2, "intersection")) + self.assertEqual(h1.compare(h2, "kl"), h1.compare(h2, "kl_div")) + self.assertEqual(h1.compare(h2, "e"), h1.compare(h2, "emd")) + # both names for the same calculation + self.assertEqual(h1.compare(h2, "b"), h1.compare(h2, "bhattacharyya")) + self.assertEqual(h1.compare(h2, "h"), h1.compare(h2, "bhattacharyya")) + # an exact name wins over a longer name it is the start of + self.assertEqual(h1.compare(h2, "chisqr"), h1.compare(h2, "CHISQR")) + self.assertNotEqual(h1.compare(h2, "chisqr"), h1.compare(h2, "chisqr_alt")) + + def test_bad_method(self): + h1, h2 = self._hist(1), self._hist(2) + with self.assertRaisesRegex(ValueError, "ambiguous"): + h1.compare(h2, "chi") + with self.assertRaisesRegex(ValueError, "ambiguous"): + h1.compare(h2, "c") + with self.assertRaisesRegex(ValueError, "unknown"): + h1.compare(h2, "bogus") + + def test_color_returns_list(self): + h1 = self._hist(1, planes=3) + h2 = self._hist(2, planes=3) + result = h1.compare(h2, "correlation") + self.assertIsInstance(result, list) + self.assertEqual(len(result), 3) + self.assertTrue(all(isinstance(r, float) for r in result)) + for r in h1.compare(h1, "correlation"): + self.assertAlmostEqual(r, 1.0, places=5) + + def test_planes_compared_in_order(self): + # plane k of one against plane k of the other, equal to the greyscale answer + rng = np.random.default_rng(5) + a = rng.integers(0, 256, (30, 30, 3), dtype=np.uint8) + b = rng.integers(0, 128, (30, 30, 3), dtype=np.uint8) + result = Image(a).hist().compare(Image(b).hist(), "emd") + for k in range(3): + single = Image(a[:, :, k]).hist().compare(Image(b[:, :, k]).hist(), "emd") + self.assertAlmostEqual(result[k], single, places=5) + + def test_mismatched_histograms(self): + h1 = self._hist(1) + with self.assertRaisesRegex(ValueError, "bins"): + h1.compare(self._hist(1, nbins=64)) + with self.assertRaisesRegex(ValueError, "planes"): + h1.compare(self._hist(1, planes=3)) + with self.assertRaises(TypeError): + h1.compare(h1.pdf) # type: ignore[arg-type] + + if __name__ == "__main__": unittest.main()