diff --git a/src/machinevisiontoolbox/ImageSpatial.py b/src/machinevisiontoolbox/ImageSpatial.py index 09cf220a..23a98018 100644 --- a/src/machinevisiontoolbox/ImageSpatial.py +++ b/src/machinevisiontoolbox/ImageSpatial.py @@ -3,7 +3,7 @@ """ import warnings -from typing import TYPE_CHECKING, Any, Callable +from typing import TYPE_CHECKING, Any, Callable, Literal, overload import cv2 import numpy as np @@ -14,7 +14,7 @@ from machinevisiontoolbox.Kernel import Kernel if TYPE_CHECKING: - pass + from machinevisiontoolbox.ImageWholeFeatures import CannyHistogram class ImageSpatialMixin(ImageMixinBase): @@ -713,90 +713,163 @@ def pyramid( pyrimlist = [self.__class__(p) for p in pyr] return pyrimlist + @overload def canny( self, - sigma: int | float = 1, - th0: float | int | None = None, - th1: float | int | None = None, + sigma: float | None = ..., + th0: float | None = ..., + th1: float | None = ..., + percentile: float = ..., + k: float = ..., + hist: Literal[False] = ..., ) -> Any: - """ + ... + + @overload + def canny( + self, + sigma: float | None = ..., + th0: float | None = ..., + th1: float | None = ..., + percentile: float = ..., + k: float = ..., + *, + hist: Literal[True], + ) -> "tuple[Any, CannyHistogram]": + ... + + def canny( + self, + sigma: float | None = None, + th0: float | None = None, + th1: float | None = None, + percentile: float = 90, + k: float = 0.5, + hist: bool = False, + ) -> Any: + r""" Canny edge detection - :param sigma: standard deviation for Gaussian kernel smoothing, defaults to 1 - :type sigma: float, optional - :param th0: lower threshold - :type th0: float - :param th1: upper threshold - :type th1: float - :return: edge image - :rtype: :class:`Image` instance + :param sigma: standard deviation of a Gaussian used to smooth the image + before edge detection, defaults to None (no smoothing) + :param th0: lower hysteresis threshold, defaults to None + :param th1: upper hysteresis threshold, defaults to None + :param percentile: percentile of the gradient magnitude used as the upper + threshold when no threshold is given, defaults to 90 + :param k: ratio of the lower threshold to the upper threshold, defaults to 0.5 + :param hist: also return a histogram of the gradient magnitude, defaults to False + :raises ValueError: a threshold is given as well as a non-default ``percentile`` + :return: edge image, or edge image and gradient histogram if ``hist`` is True Computes an edge image obtained using the Canny edge detector algorithm. Hysteresis filtering is applied to the gradient image: edge pixels > ``th1`` are connected to adjacent pixels > ``th0``, those below ``th0`` are set to zero. - Example: + The thresholds apply to the gradient magnitude computed by OpenCV, which + is :math:`|G_x| + |G_y|` where :math:`G_x` and :math:`G_y` are the + outputs of the 3x3 Sobel kernels applied to the image after conversion + to ``uint8``. This is not normalized, so a step of height 255 gives a + gradient of 1020. + + The thresholds are set in one of two ways: + + 1. Explicitly. ``th0`` and ``th1`` are passed to OpenCV. If only one is + given the other is set using ``k``: ``th0 = k * th1`` or + ``th1 = th0 / k``. + 2. Automatically, if neither is given. The upper threshold is the + ``percentile`` of the gradient magnitude of the (optionally smoothed) + image, and the lower threshold is ``k`` times that. A percentile + of 80 to 90 is typical. + + With ``hist=True`` the gradient magnitude, which is the quantity that + is thresholded, is also returned as a :class:`CannyHistogram`. Its + attributes ``th0`` and ``th1`` are the thresholds that were used, and + its ``plot`` method shows them on the histogram. This helps in + choosing thresholds. + + .. rubric:: Examples .. runblock:: pycon >>> from machinevisiontoolbox import Image >>> img = Image.Read('monalisa.png') >>> edges = img.canny() + >>> edges = img.canny(sigma=2, percentile=80) + >>> edges = img.canny(th0=100, th1=300) + >>> edges, h = img.canny(hist=True) + >>> h.th0, h.th1 .. note:: - Produces a zero image with single pixel wide edges having non-zero values. - - Larger values correspond to stronger edges. - - If ``th1`` is zero then no hysteresis filtering is performed. - A color image is automatically converted to greyscale first. + .. versionchanged:: 2.5.0 + ``sigma``, ``th0`` and ``th1`` now take effect. Previously they + were ignored and the thresholds were always set from the mean of + the image. ``sigma`` now defaults to None, no smoothing. The + automatic thresholds are now set from the ``percentile`` of the + gradient magnitude and ``k``. The arguments ``percentile``, + ``k`` and ``hist`` are new. + :references: - "A Computational Approach To Edge Detection", J. Canny, IEEE Trans. Pattern Analysis and Machine Intelligence, 8(6):679–698, 1986. - |RVC3|, Section 11.5.1.3. + .. seealso:: :meth:`smooth` :meth:`~machinevisiontoolbox.ImageWholeFeatures.Histogram` """ - - # convert to greyscale: + if not 0 < percentile < 100: + raise ValueError("percentile must be in the range (0, 100)") + if not 0 < k <= 1: + raise ValueError("k must be in the range (0, 1]") + explicit = th0 is not None or th1 is not None + if explicit and percentile != 90: + raise ValueError("percentile cannot be used when a threshold is given") + + # convert to greyscale, and smooth if requested img = self.mono() - - # set defaults (eg thresholds, eg one as a function of the other) - if th0 is None: - if np.issubdtype(th0, np.floating): - th0 = 0.1 - else: - # isint - th0 = np.round(0.1 * np.iinfo(img.dtype).max) - if th1 is None: - th1 = 1.5 * th0 - - # compute gradients Ix, Iy using gaussian kernel - dg = Kernel.DGauss(sigma) - - sigma = 0.3333 - - Ix = self.convolve(dg.K) - Iy = self.convolve(dg.K.T) - - # Ix, Iy must be 16-bit input image - Ix = np.array(Ix._A, dtype=np.int16) - Iy = np.array(Iy._A, dtype=np.int16) - - v = np.mean(self._A) - # apply automatic Canny edge detection using the computed median - lower = max(0, (1.0 - sigma) * v) - upper = min(1, (1.0 + sigma) * v) + if sigma is not None and sigma > 0: + img = img.smooth(sigma=sigma) + gray = img.array_as("uint8") + + # We call cv2.Sobel rather than gradients() deliberately. The thresholds + # are compared by cv2.Canny with its own gradient magnitude, which is the + # unnormalized 3x3 Sobel with the L1 norm |Gx| + |Gy| (apertureSize=3, + # L2gradient=False), 8 times the gain of Kernel.Sobel(). Using the same + # calculation means that a percentile of this gradient, and the + # thresholds shown in the histogram, are exactly the values that Canny + # applies. gradients() would differ in scale, in border handling + # (reflect versus OpenCV's reflect_101), and on a uint8 image in its + # output type. + gx = cv2.Sobel(gray, cv2.CV_32F, 1, 0, ksize=3) + gy = cv2.Sobel(gray, cv2.CV_32F, 0, 1, ksize=3) + grad = np.abs(gx) + np.abs(gy) + + if explicit: + if th0 is None: + th0 = k * th1 # type: ignore[operator] + elif th1 is None: + th1 = th0 / k + else: + th1 = float(np.percentile(grad, percentile)) + th0 = k * th1 out = cv2.Canny( - image=self.array_as("uint8"), - threshold1=lower, - threshold2=upper, + image=gray, + threshold1=float(th0), + threshold2=float(th1), # type: ignore[arg-type] L2gradient=False, ) + edges = self.__class__(out) - return self.__class__(out) + if hist: + from machinevisiontoolbox.ImageWholeFeatures import CannyHistogram + + return edges, CannyHistogram(self.__class__(grad), float(th0), float(th1)) # type: ignore[arg-type] + return edges def rankfilter( self, diff --git a/src/machinevisiontoolbox/ImageWholeFeatures.py b/src/machinevisiontoolbox/ImageWholeFeatures.py index 2618ae34..cb20ecaf 100644 --- a/src/machinevisiontoolbox/ImageWholeFeatures.py +++ b/src/machinevisiontoolbox/ImageWholeFeatures.py @@ -1936,6 +1936,60 @@ def peaks(self, **kwargs: Any) -> np.ndarray | list[np.ndarray]: # # plt.show() +class CannyHistogram(Histogram): + """ + Histogram of the gradient magnitude used by Canny edge detection + + :param image: gradient magnitude image + :param th0: lower hysteresis threshold that was used + :param th1: upper hysteresis threshold that was used + :param nbins: number of histogram bins, defaults to 256 + + This is a :class:`Histogram` of the gradient magnitude, with the lower and + upper hysteresis thresholds that :meth:`~machinevisiontoolbox.ImageSpatial.ImageSpatialMixin.canny` + applied, as attributes ``th0`` and ``th1``. The :meth:`plot` method draws + them as vertical lines. + + .. seealso:: :meth:`~machinevisiontoolbox.ImageSpatial.ImageSpatialMixin.canny` + """ + + th0: float + th1: float + + def __init__( + self, + image: ImageWholeFeaturesMixin, + th0: float, + th1: float, + nbins: int = 256, + ) -> None: + super().__init__( + image, + nbins=nbins, + span=(0.0, max(float(np.max(image._A)), float(th1), 1.0)), + ) + self.th0 = th0 + self.th1 = th1 + + def plot( # type: ignore[override] + self, type: Any = "frequency", block: bool = False, **kwargs: Any + ) -> None: + """ + Plot the histogram, with the thresholds marked + + The arguments are those of :meth:`Histogram.plot`. The lower and upper + thresholds are drawn as vertical lines. + """ + ax = kwargs.get("ax") + super().plot(type, False, **kwargs) + if ax is None: + ax = plt.gca() + ax.axvline(self.th0, color="k", linestyle=":", label=f"th0 = {self.th0:.4g}") + ax.axvline(self.th1, color="k", linestyle="--", label=f"th1 = {self.th1:.4g}") + ax.legend(loc="best") + safe_plt_show(block=block) + + if __name__ == "__main__": from pathlib import Path diff --git a/tests/test_image_spatial_extra.py b/tests/test_image_spatial_extra.py index 8fe2f89b..d7ff5395 100644 --- a/tests/test_image_spatial_extra.py +++ b/tests/test_image_spatial_extra.py @@ -221,15 +221,98 @@ def test_finds_the_edges_of_a_square(self, square): def test_flat_image_has_no_edges(self): assert Image(np.full((20, 20), 80, dtype=np.uint8)).canny().array.max() == 0 - @pytest.mark.xfail( - strict=True, - reason="canny() computes its thresholds from the mean of the image and " - "ignores sigma, th0 and th1", - ) def test_thresholds_have_an_effect(self, square): default = (square.canny().array > 0).sum() - strict = (square.canny(th0=250, th1=255).array > 0).sum() - assert strict < default + strict = (square.canny(th0=5000, th1=6000).array > 0).sum() + assert default > 0 + assert strict == 0 + + def test_thresholds_are_on_the_sobel_gradient(self, square): + # the step is 255 high so the Sobel gradient on an edge is 1020, and 0 + # elsewhere + assert (square.canny(th0=900, th1=1000).array > 0).sum() > 0 + assert (square.canny(th0=1100, th1=1200).array > 0).sum() == 0 + + def test_only_one_threshold_given(self, square): + # the other is set from k = 0.5, and the gradient on an edge is 1020 + assert (square.canny(th0=400).array > 0).sum() > 0 # th1 = 800 + assert (square.canny(th0=600).array > 0).sum() == 0 # th1 = 1200 + assert (square.canny(th1=1000).array > 0).sum() > 0 # th0 = 500 + assert (square.canny(th1=1200).array > 0).sum() == 0 + assert (square.canny(th1=1000, k=0.9).array > 0).sum() > 0 + + def test_percentile_sets_the_automatic_thresholds(self): + rng = np.random.default_rng(1) + im = Image(rng.integers(0, 255, (64, 64), dtype=np.uint8)) + _, h80 = im.canny(percentile=80, hist=True) + _, h95 = im.canny(percentile=95, hist=True) + assert h95.th1 > h80.th1 + nt.assert_allclose(h80.th0, 0.5 * h80.th1) + _, hk = im.canny(percentile=80, k=0.25, hist=True) + nt.assert_allclose(hk.th0, 0.25 * hk.th1) + + def test_automatic_thresholds_are_the_percentile_of_the_gradient(self): + import cv2 + + rng = np.random.default_rng(2) + arr = rng.integers(0, 255, (64, 64), dtype=np.uint8) + gx = cv2.Sobel(arr, cv2.CV_32F, 1, 0, ksize=3) + gy = cv2.Sobel(arr, cv2.CV_32F, 0, 1, ksize=3) + _, h = Image(arr).canny(percentile=85, hist=True) + nt.assert_allclose(h.th1, np.percentile(np.abs(gx) + np.abs(gy), 85), rtol=1e-6) + + def test_threshold_with_percentile_is_an_error(self, square): + with pytest.raises(ValueError, match="percentile"): + square.canny(th0=100, percentile=80) + with pytest.raises(ValueError, match="percentile"): + square.canny(th1=100, percentile=80) + + def test_bad_percentile_and_k(self, square): + for bad in (0, 100, -5): + with pytest.raises(ValueError, match="percentile"): + square.canny(percentile=bad) + for bad in (0, 1.5): + with pytest.raises(ValueError, match="k must"): + square.canny(k=bad) + + def test_hist_returns_the_edges_and_a_histogram(self, square): + from machinevisiontoolbox import Histogram + + edges, h = square.canny(th0=300, th1=800, hist=True) + assert isinstance(h, Histogram) + assert h.th0 == 300 and h.th1 == 800 + nt.assert_array_equal(edges.array, square.canny(th0=300, th1=800).array) + # histogram counts every pixel, and spans 0 to at least the thresholds + assert h.h.sum() == square.width * square.height + assert h.x[-1] >= 1020 + + def test_hist_plot_marks_the_thresholds(self, square): + import matplotlib + + matplotlib.use("Agg") + import matplotlib.pyplot as plt + + _, h = square.canny(th0=300, th1=800, hist=True) + h.plot() + ax = plt.gcf().axes[0] + xs = sorted(l.get_xdata()[0] for l in ax.lines if len(set(l.get_xdata())) == 1) + assert 300 in xs and 800 in xs + plt.close("all") + + def test_sigma_smooths_the_image(self): + rng = np.random.default_rng(0) + arr = np.full((40, 40), 60, dtype=np.uint8) + arr[10:30, 10:30] = 180 + noisy = Image( + np.clip(arr + rng.normal(0, 12, arr.shape), 0, 255).astype(np.uint8) + ) + raw = (noisy.canny().array > 0).sum() + smooth = (noisy.canny(sigma=2).array > 0).sum() + assert smooth < raw + + def test_no_smoothing_by_default(self, square): + nt.assert_array_equal(square.canny().array, square.canny(sigma=None).array) + nt.assert_array_equal(square.canny().array, square.canny(sigma=0).array) # --------------------------------------------------------------------------- #