Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(filters): keep one pixel of a tied canny ridge and accept thresholds above 1 (#5275)

Dmytro Mishkinf2bf0ac9ff00
diff --git a/benchmarks/filters/flagship.py b/benchmarks/filters/flagship.py
index c50d63b4e..3296242c3 100644
--- a/benchmarks/filters/flagship.py
+++ b/benchmarks/filters/flagship.py
@@ -47,8 +47,8 @@ calls run independently per channel. PIL uses ``BoxBlur(2)``
``GaussianBlur(radius=1.5)`` approximates a true Gaussian with repeated box passes, so the sigma is
matched in spirit only.
Canny thresholds are each library's standard
-defaults β€” kornia 0.1/0.2 on normalized float gradients, OpenCV 100/200 on uint8 gradients β€” the
-domains differ, so that row compares regimes, not identical outputs. kornia's canny converts to
+defaults β€” kornia 0.1/0.2 on the unnormalised Sobel magnitude of [0, 1] floats, OpenCV 100/200 on uint8
+gradients β€” the domains differ, so that row compares regimes, not identical outputs. kornia's canny converts to
grayscale internally per its definition; the OpenCV canny loop therefore includes ``cv2.cvtColor``
(sobel runs per-channel in both). Throughput is img/s.
diff --git a/changelog.d/5275.fixed.md b/changelog.d/5275.fixed.md
new file mode 100644
index 000000000..95ae93688
--- /dev/null
+++ b/changelog.d/5275.fixed.md
@@ -0,0 +1,14 @@
+`canny` and `Canny` no longer drop both pixels of an equal-magnitude pair in non-maximum suppression. A step between
+two flat regions puts the edge between two pixels of equal magnitude, and the strict comparison on both sides
+suppressed both, so a clean step gave no edge at all. As in OpenCV's `cv2.Canny`, a pixel now has to be strictly
+greater than its left (upper) neighbour and greater than or equal to its right (lower) one along a horizontal
+(vertical) gradient, so the step keeps its left (upper) pixel and gives a one-pixel-wide edge; diagonal comparisons
+stay strict. Edge maps and the returned magnitude change only at such exact ties, and at pixels of the flat magnitude
+`sqrt(eps)` whose two neighbours along the gradient both lie outside the image: every zero-gradient pixel of an image
+one pixel wide and, where a rounding residue in the gradient sets the direction, pixels of an image one pixel high or
+at an image corner. These were kept with magnitude `sqrt(eps)` and now are not. The neighbours are now compared
+exactly: on float32 the convolution used before could return a rounding residue instead of zero for a tie. The
+thresholds are no longer limited to `(0, 1)`: they are compared with the unnormalised Sobel magnitude, eight times
+what `sobel()` returns by default, which reaches 4 for a unit step in a `[0, 1]` image, so any
+`0 < low_threshold <= high_threshold` is accepted. An input whose channel count is not 1 or 3 raises an `ImageError`
+instead of a raw convolution error.
diff --git a/kornia/filters/canny.py b/kornia/filters/canny.py
index facecd745..b8d07ebfd 100644
--- a/kornia/filters/canny.py
+++ b/kornia/filters/canny.py
@@ -24,13 +24,39 @@ import torch.nn.functional as F
from torch import nn
from kornia.color import rgb_to_grayscale
-from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
+from kornia.core.check import (
+ KORNIA_CHECK,
+ KORNIA_CHECK_IS_COLOR_OR_GRAY,
+ KORNIA_CHECK_IS_TENSOR,
+ KORNIA_CHECK_SHAPE,
+)
from .gaussian import gaussian_blur2d
-from .kernels import get_canny_nms_kernel, get_hysteresis_kernel
+from .kernels import get_hysteresis_kernel
from .sobel import spatial_gradient
+def _check_thresholds(low_threshold: float, high_threshold: float) -> None:
+ # The thresholds are in the units of the unnormalised Sobel magnitude, which has no upper bound.
+ KORNIA_CHECK(
+ low_threshold <= high_threshold,
+ "Invalid input thresholds. low_threshold should be smaller than or equal to the high_threshold. Got: "
+ f"{low_threshold}>{high_threshold}",
+ )
+ KORNIA_CHECK(0 < low_threshold, f"Invalid low threshold. Should be positive. Got: {low_threshold}")
+
+
+# (dy, dx) of the neighbour in direction k = 0..7, counted from +x (right) towards +y (down) in steps of 45 degrees,
+# followed by the pixel itself at index 8.
+_WINDOW_OFFSETS = ((0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1), (-1, 0), (-1, 1), (0, 0))
+
+
+def _beats(magnitude: torch.Tensor, neighbour: torch.Tensor, direction: torch.Tensor) -> torch.Tensor:
+ # Directions 0 (right) and 2 (down) accept a tie; the other six need a strictly larger magnitude.
+ accepts_tie = (direction == 0) | (direction == 2)
+ return (magnitude > neighbour) | (accepts_tie & (magnitude == neighbour))
+
+
def canny(
input: torch.Tensor,
low_threshold: float = 0.1,
@@ -44,10 +70,26 @@ def canny(
.. image:: _static/img/canny.png
+ The thresholds are compared with the magnitude :math:`\sqrt{g_x^2 + g_y^2 + \epsilon}` of the **unnormalised**
+ Sobel gradient of the blurred grayscale image, ``sobel(blurred, normalized=False, eps=eps)``. That is eight times
+ what :func:`~kornia.filters.sobel` returns with its default ``normalized=True``, up to the ``eps`` inside the square
+ root, so on an image in :math:`[0, 1]` it is not bounded by 1: a unit step reaches 4 without the blur
+ (``kernel_size=1``) and about 2.59 with the default one.
+ In float16 the squared gradient overflows past 65504, which a step of 64 already reaches without the blur, so
+ keep a float16 image in :math:`[0, 1]` rather than scaling it and the thresholds up.
+
+ Non-maximum suppression compares each pixel with its two neighbours along the gradient direction, rounded to a
+ multiple of 45 degrees. As in OpenCV's ``cv2.Canny``, along a horizontal (vertical) gradient a pixel must be
+ strictly greater than its left (upper) neighbour and greater than or equal to its right (lower) one, so of two
+ pixels of equal magnitude across a step edge the left (upper) one is kept. Along a diagonal it must be strictly
+ greater than both. A pixel with zero gradient is never kept.
+
Args:
- input: input image torch.Tensor with shape :math:`(B,C,H,W)`.
- low_threshold: lower threshold for the hysteresis procedure.
- high_threshold: upper threshold for the hysteresis procedure.
+ input: input image torch.Tensor with shape :math:`(B,C,H,W)`, with :math:`C` equal to 1, or to 3 for an RGB
+ image, which is converted to grayscale.
+ low_threshold: lower threshold for the hysteresis procedure, in the units of the magnitude above. It must be
+ positive and at most ``high_threshold``.
+ high_threshold: upper threshold for the hysteresis procedure, in the same units. It has no upper bound.
kernel_size: the size of the kernel for the gaussian blur.
sigma: the standard deviation of the kernel for the gaussian blur.
hysteresis: if True, applies the hysteresis edge tracking.
@@ -72,13 +114,8 @@ def canny(
"""
KORNIA_CHECK_IS_TENSOR(input)
KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])
- KORNIA_CHECK(
- low_threshold <= high_threshold,
- "Invalid input thresholds. low_threshold should be smaller than the high_threshold. Got: "
- f"{low_threshold}>{high_threshold}",
- )
- KORNIA_CHECK(0 < low_threshold < 1, f"Invalid low threshold. Should be in range (0, 1). Got: {low_threshold}")
- KORNIA_CHECK(0 < high_threshold < 1, f"Invalid high threshold. Should be in range (0, 1). Got: {high_threshold}")
+ KORNIA_CHECK_IS_COLOR_OR_GRAY(input, f"canny expects 1 or 3 channels. Got: {input.shape[1]}")
+ _check_thresholds(low_threshold, high_threshold)
device = input.device
dtype = input.dtype
@@ -97,18 +134,28 @@ def canny(
gx: torch.Tensor = gradients[:, :, 0]
gy: torch.Tensor = gradients[:, :, 1]
- # Compute gradient magnitude and angle
- magnitude: torch.Tensor = torch.sqrt(gx * gx + gy * gy + eps)
- angle: torch.Tensor = torch.atan2(gy, gx)
+ # Compute gradient magnitude and angle. The magnitude is computed one pixel beyond the image, where there is no
+ # gradient: the border then has the magnitude sqrt(eps) of a flat pixel, so a flat pixel never beats it.
+ gx_padded: torch.Tensor = F.pad(gx, (1, 1, 1, 1))
+ gy_padded: torch.Tensor = F.pad(gy, (1, 1, 1, 1))
+ padded: torch.Tensor = torch.sqrt(gx_padded * gx_padded + gy_padded * gy_padded + eps)
+ # The legacy ONNX exporter's atan2 returns NaN at (0, 0), which casts to an out-of-range index on x86-64.
+ angle: torch.Tensor = torch.nan_to_num(torch.atan2(gy, gx))
# Radians to degrees and round to nearest 45 degree
# degrees = angle * (180.0 / math.pi)
# angle = torch.round(degrees / 45) * 45
angle_45 = (angle * (4 / math.pi)).round()
- # Non-maximal suppression
- nms_kernels: torch.Tensor = get_canny_nms_kernel(device, dtype)
- nms_magnitude: torch.Tensor = F.conv2d(magnitude, nms_kernels, padding=nms_kernels.shape[-1] // 2)
+ # Non-maximal suppression: entry k < 8 along dimension 2 of window is the magnitude of the neighbour in direction k
+ # and entry 8 that of the pixel itself. Slicing copies the values, so a tie compares exactly equal, which a
+ # convolution does not guarantee, and reading the pixel and its neighbours from one tensor keeps them in the same
+ # precision under torch.compile.
+ height, width = gx.shape[-2:]
+ window: torch.Tensor = torch.stack(
+ [padded[..., 1 + dy : 1 + dy + height, 1 + dx : 1 + dx + width] for dy, dx in _WINDOW_OFFSETS], 2
+ )
+ magnitude: torch.Tensor = window[:, :, 8]
# Get the indices for both directions
positive_idx: torch.Tensor = angle_45 % 8
@@ -117,15 +164,22 @@ def canny(
negative_idx: torch.Tensor = (angle_45 + 4) % 8
negative_idx = negative_idx.long()
- # Apply the non-maximum suppression to the different directions
- channel_select_filtered_positive: torch.Tensor = torch.gather(nms_magnitude, 1, positive_idx)
- channel_select_filtered_negative: torch.Tensor = torch.gather(nms_magnitude, 1, negative_idx)
-
- channel_select_filtered: torch.Tensor = torch.stack(
- [channel_select_filtered_positive, channel_select_filtered_negative], 1
+ # The two neighbours along the gradient direction, read with one gather per channel
+ neighbour_both: torch.Tensor = torch.gather(window, 2, torch.stack([positive_idx, negative_idx], 2))
+ neighbour_positive: torch.Tensor = neighbour_both[:, :, 0]
+ neighbour_negative: torch.Tensor = neighbour_both[:, :, 1]
+
+ # As in OpenCV's Canny, a pixel must be strictly greater than its left (upper) neighbour but only greater than or
+ # equal to its right (lower) one along a horizontal (vertical) gradient, so of two equal pixels across a step the
+ # left (upper) one is kept. Along a diagonal both comparisons are strict: the neighbours along it are two lines
+ # apart, and the line between a tied pair carries the edge.
+ is_max: torch.Tensor = _beats(magnitude, neighbour_positive, positive_idx) & _beats(
+ magnitude, neighbour_negative, negative_idx
)
- is_max: torch.Tensor = channel_select_filtered.min(dim=1)[0] > 0.0
+ # A pixel no larger than the border, which has no gradient, is never kept. The comparisons above already exclude it,
+ # since one of them is strict for every direction; this states the rule independently of the angle.
+ is_max = is_max & (magnitude > padded[..., :1, :1])
magnitude = magnitude * is_max
@@ -164,10 +218,12 @@ def canny(
class Canny(nn.Module):
r"""nn.Module that finds edges of the input image and filters them using the Canny algorithm.
+ See :func:`~kornia.filters.canny` for the units of the thresholds and the non-maximum suppression.
+
Args:
- input: input image torch.Tensor with shape :math:`(B,C,H,W)`.
- low_threshold: lower threshold for the hysteresis procedure.
- high_threshold: upper threshold for the hysteresis procedure.
+ low_threshold: lower threshold for the hysteresis procedure, in the units of the unnormalised Sobel
+ magnitude. It must be positive and at most ``high_threshold``.
+ high_threshold: upper threshold for the hysteresis procedure, in the same units. It has no upper bound.
kernel_size: the size of the kernel for the gaussian blur.
sigma: the standard deviation of the kernel for the gaussian blur.
hysteresis: if True, applies the hysteresis edge tracking.
@@ -202,15 +258,7 @@ class Canny(nn.Module):
) -> None:
super().__init__()
- KORNIA_CHECK(
- low_threshold <= high_threshold,
- "Invalid input thresholds. low_threshold should be smaller than the high_threshold. Got: "
- f"{low_threshold}>{high_threshold}",
- )
- KORNIA_CHECK(0 < low_threshold < 1, f"Invalid low threshold. Should be in range (0, 1). Got: {low_threshold}")
- KORNIA_CHECK(
- 0 < high_threshold < 1, f"Invalid high threshold. Should be in range (0, 1). Got: {high_threshold}"
- )
+ _check_thresholds(low_threshold, high_threshold)
# Gaussian blur parameters
self.kernel_size = kernel_size
@@ -249,8 +297,8 @@ class Canny(nn.Module):
input: Image tensor with shape :math:`(B, C, H, W)`, where
:math:`B` is the batch size, :math:`C` is the number of
channels, :math:`H` is the image height, and :math:`W` is the
- image width. Multi-channel inputs are handled by the underlying
- functional implementation.
+ image width. :math:`C` must be 1, or 3 for an RGB image, which is
+ converted to grayscale.
Returns:
Tuple ``(magnitude, edges)``. ``magnitude`` contains the gradient
diff --git a/kornia/filters/kernels.py b/kornia/filters/kernels.py
index 37a98dfcd..6c3b84ea5 100644
--- a/kornia/filters/kernels.py
+++ b/kornia/filters/kernels.py
@@ -1013,7 +1013,10 @@ def get_pascal_kernel_1d(
def get_canny_nms_kernel(device: Optional[torch.device] = None, dtype: Optional[torch.dtype] = None) -> torch.Tensor:
- """Return 3x3 kernels for the Canny Non-maximal suppression."""
+ """Return 3x3 kernels for the Canny Non-maximal suppression.
+
+ Not used by :func:`~kornia.filters.canny`, which compares the neighbours by slicing, so that ties compare exactly.
+ """
return torch.tensor(
[
[[[0.0, 0.0, 0.0], [0.0, 1.0, -1.0], [0.0, 0.0, 0.0]]],
diff --git a/tests/filters/test_canny.py b/tests/filters/test_canny.py
index 4240a4b55..6ff8fcd01 100644
--- a/tests/filters/test_canny.py
+++ b/tests/filters/test_canny.py
@@ -15,13 +15,18 @@
# limitations under the License.
#
+import io
+import warnings
+from typing import Any
+
import pytest
import torch
-from kornia.core._compat import torch_version
-from kornia.filters import Canny, canny
+from kornia.core._compat import torch_version, torch_version_ge
+from kornia.core.exceptions import ImageError
+from kornia.filters import Canny, canny, sobel
-from testing.base import BaseTester
+from testing.base import BaseTester, supports_reflect_padding, supports_replicate_padding
class TestCanny(BaseTester):
@@ -87,15 +92,15 @@ class TestCanny(BaseTester):
with pytest.raises(BaseError) as errinfo:
Canny(0.3, 0.2)
- assert "low_threshold should be smaller than the high_threshold" in str(errinfo.value)
+ assert "low_threshold should be smaller than or equal to the high_threshold" in str(errinfo.value)
with pytest.raises(BaseError) as errinfo:
Canny(-2, 0.3)
assert "Invalid low threshold." in str(errinfo.value)
with pytest.raises(BaseError) as errinfo:
- Canny(0.1, 3)
- assert "Invalid high threshold." in str(errinfo.value)
+ Canny(0, 3)
+ assert "Invalid low threshold." in str(errinfo.value)
with pytest.raises(TypeCheckError) as errinfo:
canny(1)
@@ -366,3 +371,202 @@ class TestCanny(BaseTester):
self.assert_close(actual_magnitude, expected_magnitude)
self.assert_close(actual_edges, expected_edges)
+
+ @pytest.mark.parametrize("hysteresis", [False, True])
+ @pytest.mark.parametrize("image", ["random", "rectangle"])
+ def test_dynamo_on_edges(self, image, hysteresis, device, dtype, torch_optimizer):
+ self._require_padding(device, dtype)
+ if dtype in (torch.float16, torch.bfloat16) and image == "random":
+ pytest.skip("the compiled graph computes in float32 and rounds once, so near-ties may resolve differently")
+ # test_dynamo's constant image has no edge. A random image, blurred, has no exact tie; a rectangle with an inner
+ # step, unblurred, has exact ties that compiled and eager arithmetic resolve alike, in every dtype. Both
+ # exercise the suppression and the hysteresis in the compiled graph
+ if image == "random":
+ generator = torch.Generator().manual_seed(0)
+ img = torch.rand(1, 3, 40, 48, generator=generator).to(device=device, dtype=dtype)
+ op = Canny(hysteresis=hysteresis)
+ else:
+ img = torch.zeros(1, 3, 40, 48, device=device, dtype=dtype)
+ img[..., 8:32, 10:38] = 1.0
+ img[..., 16:24, 18:30] = 0.5
+ op = Canny(kernel_size=1, hysteresis=hysteresis)
+ expected_magnitude, expected_edges = op(img)
+ actual_magnitude, actual_edges = torch_optimizer(op)(img)
+ assert expected_edges.sum().item() > 0
+ self.assert_close(actual_edges, expected_edges)
+ self.assert_close(actual_magnitude, expected_magnitude)
+
+ @staticmethod
+ def _require_padding(device, dtype):
+ # gaussian_blur2d pads by reflection and spatial_gradient by replication, even with kernel_size=1
+ if not (supports_reflect_padding(device, dtype) and supports_replicate_padding(device, dtype)):
+ pytest.skip("torch has no reflect or replicate padding kernel for this device and dtype")
+
+ @staticmethod
+ def _ramped_step(device, dtype):
+ # 0 | 0.6 | 1 across x = 6..8 of a 9x14 image; with no blur the raw Sobel |gx| is 2.4, 4, 1.6 at x = 6, 7, 8,
+ # so the ridge at x = 7 is a strict maximum
+ img = torch.zeros(1, 1, 9, 14, device=device, dtype=dtype)
+ img[..., 7] = 0.6
+ img[..., 8:] = 1.0
+ return img
+
+ @staticmethod
+ def _diagonal_lines(device):
+ # u = x + y on a 12x17 grid: the lines u = const run at 45 degrees and the gradient across them along (1, 1)
+ ys, xs = torch.meshgrid(torch.arange(12, device=device), torch.arange(17, device=device), indexing="ij")
+ return xs + ys
+
+ @pytest.mark.parametrize("transpose", [False, True])
+ @pytest.mark.parametrize("dark_to_bright", [True, False])
+ def test_two_level_step_keeps_one_pixel_of_the_tie(self, transpose, dark_to_bright, device, dtype):
+ self._require_padding(device, dtype)
+ # a step between x = 6 and x = 7 of a 9x14 image, no blur: the raw Sobel magnitudes of x = 6 and x = 7 are
+ # both 4. As in OpenCV's Canny, a pixel must be strictly greater than its left (upper) neighbour and greater
+ # than or equal to its right (lower) one, so the left (upper) pixel of the tie is kept, for either polarity
+ img = torch.zeros(1, 1, 9, 14, device=device, dtype=dtype)
+ img[..., 7:] = 1.0
+ if not dark_to_bright:
+ img = 1.0 - img
+ expected = torch.zeros_like(img)
+ expected[..., 6] = 1.0
+ if transpose:
+ img, expected = img.transpose(-1, -2), expected.transpose(-1, -2)
+ magnitude, edges = canny(img, kernel_size=1)
+ self.assert_close(edges, expected)
+ self.assert_close(magnitude, 4.0 * expected)
+
+ def test_square_without_blur_matches_opencv(self, device, dtype):
+ self._require_padding(device, dtype)
+ # a 10x10 square at rows and columns 10..19 of a 40x40 image, no blur: every side is a two-level step whose
+ # tied pair keeps its left or upper pixel, outside the square on the left and top, inside on the right and
+ # bottom. The suppression compares magnitudes exactly, so no rounding decides a tie. OpenCV 5.0.0 gives the same
+ # map: cv2.Canny((255 * img).astype(np.uint8), 25.5, 51, L2gradient=True)
+ img = torch.zeros(1, 1, 40, 40, device=device, dtype=dtype)
+ img[..., 10:20, 10:20] = 1.0
+ expected = torch.zeros_like(img)
+ expected[..., 9, 11:19] = 1.0 # top
+ expected[..., 19, 10:20] = 1.0 # bottom
+ expected[..., 11:19, 9] = 1.0 # left
+ expected[..., 10:19, 19] = 1.0 # right
+ expected[..., 10, 10] = 1.0 # top-left corner
+ _, edges = canny(img, kernel_size=1)
+ self.assert_close(edges, expected)
+
+ def test_square_contour_is_closed(self, device, dtype):
+ self._require_padding(device, dtype)
+ # a 10x10 square at rows and columns 25..34 of a 100x100 image, default arguments: after the 5x5 blur the two
+ # pixels across each side tie in exact arithmetic and rounding decides which one is larger. Exactly one of the
+ # pair survives either way, so every row and column along a side holds one edge pixel on each side of the square
+ img = torch.zeros(1, 1, 100, 100, device=device, dtype=dtype)
+ img[..., 25:35, 25:35] = 1.0
+ _, edges = canny(img)
+ on = edges[0, 0] > 0
+ for k in range(27, 33):
+ for line in (on[k], on[:, k]):
+ assert line[23:27].sum().item() == 1
+ assert line[33:37].sum().item() == 1
+ assert line.sum().item() == 2
+
+ @pytest.mark.parametrize("mirror", [False, True])
+ def test_two_level_diagonal_step_is_one_pixel_wide_along_the_gradient(self, mirror, device, dtype):
+ self._require_padding(device, dtype)
+ # guard: holds on main too; fails if the diagonal neighbours are taken along another direction
+ # 0 | 1 across x + y = 12.5 of a 12x17 image, no blur: the raw Sobel components are 1, 3, 3, 1 on the lines
+ # x + y = 11..14. The tied lines 12 and 13 are 4-neighbours across the gradient, not neighbours along it; along
+ # (1, 1) each pixel is compared with the lines two steps away, so both survive, as in OpenCV, and every line
+ # along the gradient crosses the edge once. Mirrored in x, the same holds along (-1, 1)
+ u = self._diagonal_lines(device)
+ img = (u >= 13).to(dtype)[None, None]
+ expected = ((u == 12) | (u == 13)).to(dtype)[None, None]
+ if mirror:
+ img, expected = img.flip(-1), expected.flip(-1)
+ _, edges = canny(img, kernel_size=1)
+ # rows 1..10: the replicated top and bottom borders change the gradient on rows 0 and 11
+ self.assert_close(edges[..., 1:-1, :], expected[..., 1:-1, :])
+
+ @pytest.mark.parametrize("mirror", [False, True])
+ def test_diagonal_tie_keeps_the_pixel_between(self, mirror, device, dtype):
+ self._require_padding(device, dtype)
+ # guard: holds on main too; fails if a diagonal comparison accepts a tie
+ # 0 | 0.5 | 1 on x + y < 13, = 13, > 13, no blur: the raw Sobel components are 2, 3, 2 on the lines 12, 13, 14,
+ # so the lines 12 and 14 tie as neighbours along the (1, 1) gradient. Along a diagonal both comparisons stay
+ # strict, as in OpenCV: the tie keeps neither, and the line 13 between them carries a one-pixel-wide edge
+ u = self._diagonal_lines(device)
+ img = torch.where(u < 13, 0.0, torch.where(u == 13, 0.5, 1.0)).to(dtype)[None, None]
+ expected = (u == 13).to(dtype)[None, None]
+ if mirror:
+ img, expected = img.flip(-1), expected.flip(-1)
+ _, edges = canny(img, kernel_size=1)
+ self.assert_close(edges[..., 1:-1, :], expected[..., 1:-1, :])
+
+ @pytest.mark.parametrize("transpose", [False, True])
+ def test_ridge_without_tie_keeps_its_maximum(self, transpose, device, dtype):
+ self._require_padding(device, dtype)
+ # guard: holds on main too; fails if the suppression reads a zero border instead of a flat one
+ # the strict maximum at x = 7 is the edge; the flat regions have no gradient and are never edges, also at the
+ # image border
+ img = self._ramped_step(device, dtype)
+ expected = torch.zeros_like(img)
+ expected[..., 7] = 1.0
+ if transpose:
+ img, expected = img.transpose(-1, -2), expected.transpose(-1, -2)
+ magnitude, edges = canny(img, kernel_size=1)
+ self.assert_close(edges, expected)
+ self.assert_close(magnitude, 4.0 * expected)
+
+ def test_flat_image_has_no_edges_at_any_threshold(self, device, dtype):
+ self._require_padding(device, dtype)
+ # guard: holds on main too; fails if the suppression reads a zero border instead of a flat one
+ # a flat region has magnitude sqrt(eps) = 1e-3, above a threshold of 1e-4, but it ties with its neighbours and
+ # with the image border, which has no gradient either, so no pixel of it is a maximum
+ img = torch.full((1, 1, 9, 14), 0.3, device=device, dtype=dtype)
+ magnitude, edges = canny(img, 1e-4, 2e-4, kernel_size=1)
+ self.assert_close(magnitude, torch.zeros_like(img))
+ self.assert_close(edges, torch.zeros_like(img))
+
+ def test_thresholds_are_in_unnormalized_sobel_units(self, device, dtype):
+ self._require_padding(device, dtype)
+ # the ridge at x = 7 has magnitude 4, eight times what sobel() returns by default, and the thresholds compare
+ # against it, so values above 1 are meaningful
+ img = self._ramped_step(device, dtype)
+ self.assert_close(sobel(img)[..., 7], torch.full((1, 1, 9), 0.5, device=device, dtype=dtype))
+ ridge = torch.zeros_like(img)
+ ridge[..., 7] = 1.0
+ for low, high, expected in ((3.0, 3.5, ridge), (3.0, 4.5, 0.5 * ridge), (4.5, 5.0, 0.0 * ridge)):
+ _, edges = canny(img, low, high, kernel_size=1, hysteresis=False)
+ self.assert_close(edges, expected)
+ _, edges = Canny(low, high, kernel_size=1, hysteresis=False)(img)
+ self.assert_close(edges, expected)
+
+ @pytest.mark.device_agnostic
+ def test_onnx_export_legacy_matches_eager(self, dtype):
+ if dtype != torch.float32:
+ pytest.skip("the exported graph is checked once, in float32")
+ pytest.importorskip("onnx")
+ ort = pytest.importorskip("onnxruntime")
+ # the legacy exporter's atan2 is NaN at (0, 0); cast to an index, NaN gives 0 on arm64 but an out-of-range
+ # value on x86-64, where GatherElements raises. The flat image and the step's flat columns have zero gradient,
+ # and they must run and not be maxima, while the step keeps its left pixel
+ step = torch.zeros(1, 1, 9, 14, dtype=dtype)
+ step[..., 7:] = 1.0
+ flat = torch.full_like(step, 0.3)
+ model = Canny(kernel_size=1, hysteresis=False)
+ buffer = io.BytesIO()
+ export_kwargs: dict[str, Any] = {"input_names": ["input"], "opset_version": 17}
+ if torch_version_ge(2, 5, 0):
+ export_kwargs["dynamo"] = False
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore")
+ torch.onnx.export(model, step, buffer, **export_kwargs)
+ session = ort.InferenceSession(buffer.getvalue(), providers=["CPUExecutionProvider"])
+ for img in (step, flat):
+ magnitude, edges = (torch.from_numpy(out) for out in session.run(None, {"input": img.numpy()}))
+ expected_magnitude, expected_edges = model(img)
+ self.assert_close(magnitude, expected_magnitude)
+ self.assert_close(edges, expected_edges)
+
+ @pytest.mark.parametrize("channels", [2, 4])
+ def test_unsupported_channel_count_raises(self, channels, device, dtype):
+ with pytest.raises(ImageError, match="1 or 3 channels"):
+ canny(torch.zeros(1, channels, 12, 13, device=device, dtype=dtype))