Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(morphology): anchor the reflected dilation kernel at its origin (#4737)

Dmytro Mishkind299ed3c1322
diff --git a/changelog.d/4737.breaking.md b/changelog.d/4737.breaking.md
new file mode 100644
index 000000000..9f1a6e79b
--- /dev/null
+++ b/changelog.d/4737.breaking.md
@@ -0,0 +1,6 @@
+`kornia.morphology.dilation` (and `closing`, `gradient`, `top_hat`, `bottom_hat`, `opening`, which call it) now
+anchors the reflected structuring element at `origin`. It used to reflect the kernel values but pad with the
+unreflected origin, so an even-sized kernel (for example `torch.ones(2, 2)`) shifted the result by one pixel
+toward the bottom-right relative to `scipy.ndimage.grey_dilation` and `skimage.morphology.dilation`, and a custom
+`origin` moved the window in the opposite direction to the one `erosion` uses. Odd kernels with the default origin
+are unchanged.
diff --git a/kornia/morphology/morphology.py b/kornia/morphology/morphology.py
index f98904f39..4a52d8b54 100644
--- a/kornia/morphology/morphology.py
+++ b/kornia/morphology/morphology.py
@@ -197,7 +197,8 @@ def dilation(
origin = [se_h // 2, se_w // 2]
# pad
- pad_e: List[int] = [origin[1], se_w - origin[1] - 1, origin[0], se_h - origin[0] - 1]
+ # The kernel is reflected below (Minkowski dilation), so the window is anchored at the reflected origin.
+ pad_e: List[int] = [se_w - origin[1] - 1, origin[1], se_h - origin[0] - 1, origin[0]]
if border_type == "geodesic":
border_value = -max_val
border_type = "constant"
diff --git a/tests/morphology/test_closing.py b/tests/morphology/test_closing.py
index 1e8135a67..afe8c1f97 100644
--- a/tests/morphology/test_closing.py
+++ b/tests/morphology/test_closing.py
@@ -122,3 +122,21 @@ class TestClosing(BaseTester):
expected = op(tensor, kernel)
assert_close(actual, expected)
+
+ def test_closing_custom_origin_is_extensive_and_idempotent(self, device, dtype):
+ # closing = erosion(dilation(x)) must stay extensive (closing(x) >= x) and idempotent
+ # (closing(closing(x)) == closing(x)) under a custom origin too, not just the default
+ # centred one. `dilation`'s origin bug broke both for origin=[0, 0]. Mirrors
+ # TestOpening.test_opening_custom_origin_is_anti_extensive_and_idempotent. The `>=` on
+ # the rand fixture never needs a tolerance (selection only, no interpolation), and
+ # repeating `closing` on its own (already-closed) output is likewise exact, so
+ # `torch.equal` is fine.
+ # Generated with:
+ # torch.rand(1, 1, 7, 10, generator=torch.Generator().manual_seed(0))
+ # A local `torch.Generator` avoids touching the process-global (and any device) RNG state.
+ tensor = torch.rand(1, 1, 7, 10, generator=torch.Generator().manual_seed(0)).to(device=device, dtype=dtype)
+ kernel = torch.ones(3, 3, device=device, dtype=dtype)
+
+ closed = closing(tensor, kernel, origin=[0, 0])
+ assert (closed >= tensor).all()
+ assert torch.equal(closing(closed, kernel, origin=[0, 0]), closed)
diff --git a/tests/morphology/test_dilation.py b/tests/morphology/test_dilation.py
index 534d2aa40..24e5baf9b 100644
--- a/tests/morphology/test_dilation.py
+++ b/tests/morphology/test_dilation.py
@@ -18,7 +18,7 @@
import pytest
import torch
-from kornia.morphology import dilation
+from kornia.morphology import dilation, erosion
from kornia.morphology import morphology as morphology_module
from kornia.morphology.morphology import _records_grad, _resolve_engine
@@ -352,8 +352,8 @@ class TestDilate(BaseTester):
tensor = torch.tensor([[[[-1.0, -0.0], [0.0, -0.0]]]], device=device)
kernel = torch.ones(2, 2, device=device)
- expected = dilation(tensor, kernel, origin=[0, 0], engine="unfold")
- actual = dilation(tensor, kernel, origin=[0, 0], engine="shift")
+ expected = dilation(tensor, kernel, origin=[1, 1], engine="unfold")
+ actual = dilation(tensor, kernel, origin=[1, 1], engine="shift")
assert torch.equal(actual, expected)
assert torch.equal(actual, torch.zeros_like(actual))
@@ -382,3 +382,130 @@ class TestDilate(BaseTester):
kernel = torch.ones(3, 3, device=device, dtype=dtype)
assert torch.equal(op_script(tensor, kernel, engine="shift"), dilation(tensor, kernel, engine="shift"))
+
+ def test_even_kernel_centre(self, device, dtype):
+ # `dilation` reflects the kernel contents but padded with the unreflected origin, so an
+ # even-sized kernel's default-origin window was anchored one pixel toward the top-left of
+ # where the Minkowski dilation ``out(p) = max_{q: kernel[q] != 0} x(p - (q - origin))``
+ # anchors it. 0/1 fixtures are exact in every dtype (no arithmetic rounding), so this
+ # compares with `torch.equal`.
+ # Generated with:
+ # x = torch.zeros(1, 1, 6, 7); x[..., 2, 3] = 1
+ # dilation(x, torch.ones(2, 2))
+ # scipy 1.17.1 `ndi.grey_dilation(x, footprint=np.ones((2, 2), bool))` and skimage 0.26.0
+ # `sm.dilation(x, np.ones((2, 2)))` both give this (fixed) set; OpenCV 5.0.0 `cv2.dilate`
+ # does not reflect the kernel and gives {(2, 3), (2, 4), (3, 3), (3, 4)} instead.
+ tensor = torch.zeros(1, 1, 6, 7, device=device, dtype=dtype)
+ tensor[..., 2, 3] = 1.0
+ kernel = torch.ones(2, 2, device=device, dtype=dtype)
+
+ expected = torch.zeros(1, 1, 6, 7, device=device, dtype=dtype)
+ expected[..., 1, 2] = 1.0
+ expected[..., 1, 3] = 1.0
+ expected[..., 2, 2] = 1.0
+ expected[..., 2, 3] = 1.0
+
+ assert torch.equal(dilation(tensor, kernel), expected)
+
+ def test_custom_origin_direction(self, device, dtype):
+ # With an origin index `o`, dilation collects `x(p - (q - origin))`, so `origin=[0, 0]`
+ # must spread the window toward +rows/+cols -- the same direction `erosion(...,
+ # origin=[0, 0])` already uses (erosion at `p` reads rows/cols `p..p+k-1`). Pre-fix,
+ # `dilation` spread it toward -rows/-cols instead. 0/1 fixtures are exact in every dtype,
+ # so this compares with `torch.equal`.
+ # Generated with:
+ # x = torch.zeros(1, 1, 6, 7); x[..., 2, 3] = 1
+ # dilation(x, torch.ones(3, 3), origin=[0, 0])
+ tensor = torch.zeros(1, 1, 6, 7, device=device, dtype=dtype)
+ tensor[..., 2, 3] = 1.0
+ kernel = torch.ones(3, 3, device=device, dtype=dtype)
+
+ expected = torch.zeros(1, 1, 6, 7, device=device, dtype=dtype)
+ expected[..., 2:5, 3:6] = 1.0
+
+ assert torch.equal(dilation(tensor, kernel, origin=[0, 0]), expected)
+
+ def test_erosion_duality_custom_origin(self, device, dtype):
+ # erosion(x, B, origin=o) == -dilation(-x, B.flip((0, 1)), origin=[k_h-1-o0, k_w-1-o1])
+ # must hold exactly for every origin, not just an odd kernel's centre. Both sides only
+ # ever select an already-present value of `x` (max/min, never interpolation), and
+ # negation is exact in every dtype, so `torch.equal` is fine here too. Pre-fix, this held
+ # only for an odd kernel's centre origin and failed for every other origin.
+ # Generated with:
+ # torch.rand(1, 1, 7, 10, generator=torch.Generator().manual_seed(0))
+ # L = torch.tensor([[0., 0., 0.], [0., 1., 1.], [0., 1., 0.]])
+ # A local `torch.Generator` avoids touching the process-global (and any device) RNG state.
+ tensor = torch.rand(1, 1, 7, 10, generator=torch.Generator().manual_seed(0)).to(device=device, dtype=dtype)
+ l_kernel = torch.tensor([[0.0, 0.0, 0.0], [0.0, 1.0, 1.0], [0.0, 1.0, 0.0]], device=device, dtype=dtype)
+ square_kernel = torch.ones(2, 2, device=device, dtype=dtype)
+
+ for kernel in (l_kernel, square_kernel):
+ k_h, k_w = kernel.shape
+ flipped = kernel.flip((0, 1))
+ for o0 in range(k_h):
+ for o1 in range(k_w):
+ origin = [o0, o1]
+ dual_origin = [k_h - 1 - o0, k_w - 1 - o1]
+ lhs = erosion(tensor, kernel, origin=origin)
+ rhs = -dilation(-tensor, flipped, origin=dual_origin)
+ assert torch.equal(lhs, rhs), (tuple(kernel.shape), origin)
+
+ def test_odd_kernel_default_origin_unchanged(self, device, dtype):
+ # An odd kernel with the default (centred) origin pads symmetrically either way
+ # (`se_w - origin[1] - 1 == origin[1]` when `origin[1] == (se_w - 1) // 2`), so the fix
+ # must leave this case bitwise unchanged. This literal was captured from `dilation` on
+ # unmodified `main` (commit 0e8cf3b57), before the pad-line fix was applied, so it also
+ # pins the pre-fix value. 0/1 fixtures are exact in every dtype, so this compares with
+ # `torch.equal`.
+ # Generated with:
+ # L = torch.tensor([[0., 0., 0.], [0., 1., 1.], [0., 1., 0.]])
+ # x = torch.zeros(1, 1, 6, 7); x[..., 2, 3] = 1
+ # dilation(x, L)
+ tensor = torch.zeros(1, 1, 6, 7, device=device, dtype=dtype)
+ tensor[..., 2, 3] = 1.0
+ l_kernel = torch.tensor([[0.0, 0.0, 0.0], [0.0, 1.0, 1.0], [0.0, 1.0, 0.0]], device=device, dtype=dtype)
+
+ expected = torch.zeros(1, 1, 6, 7, device=device, dtype=dtype)
+ expected[..., 2, 3] = 1.0
+ expected[..., 2, 4] = 1.0
+ expected[..., 3, 3] = 1.0
+
+ assert torch.equal(dilation(tensor, l_kernel), expected)
+
+ @pytest.mark.parametrize("engine", ["unfold", "convolution"])
+ def test_even_kernel_centre_non_square(self, device, dtype, engine):
+ # A rectangular kernel's rows and columns must each be padded with their OWN axis's
+ # reflected origin: `se_h`/`origin[0]` (rows) must never leak into the width pad slot, or
+ # `se_w`/`origin[1]` (cols) into the height pad slot. `ones(2, 2)`, `ones(3, 3)` and the L
+ # kernel used elsewhere in this file are square (or symmetric enough) that a pad list with
+ # rows and columns swapped still reproduces every one of their pins; only a genuinely
+ # rectangular kernel with an off-centre hot pixel catches a row/col swap.
+ # Derived from the Minkowski rule with the default origin [k_h // 2, k_w // 2]:
+ # out(p) = max_{q in kernel} x(p - (q - origin))
+ # so the nonzero set is {p0 + q - origin : q in kernel}, clipped to the image bounds.
+ # Confirmed against the fixed library. Generated with:
+ # x = torch.zeros(1, 1, 6, 7); x[..., 1, 4] = 1
+ # dilation(x, torch.ones(1, 4)) -> row 1, cols 2..5 (origin=[0, 2])
+ # dilation(x, torch.ones(4, 1)) -> rows 0..2, col 4 (origin=[2, 0]; row -1 clipped)
+ tensor = torch.zeros(1, 1, 6, 7, device=device, dtype=dtype)
+ tensor[..., 1, 4] = 1.0
+
+ wide_kernel = torch.ones(1, 4, device=device, dtype=dtype)
+ wide_nonzero = [[1, 2], [1, 3], [1, 4], [1, 5]]
+ tall_kernel = torch.ones(4, 1, device=device, dtype=dtype)
+ tall_nonzero = [[0, 4], [1, 4], [2, 4]]
+
+ for kernel, expected_nonzero in ((wide_kernel, wide_nonzero), (tall_kernel, tall_nonzero)):
+ actual = dilation(tensor, kernel, engine=engine)
+ expected = torch.zeros(1, 1, 6, 7, device=device, dtype=dtype)
+ for row, col in expected_nonzero:
+ expected[..., row, col] = 1.0
+
+ if engine == "convolution":
+ # See test_kernel: the convolution engine can carry tiny floating noise on some
+ # backends even for 0/1 inputs, so compare the full tensor at the harness's
+ # default per-dtype tolerance instead of a strict nonzero() index list; the
+ # fixture is 0/1 so this is exact anyway.
+ self.assert_close(actual, expected)
+ else:
+ assert sorted(actual.nonzero()[:, 2:].tolist()) == expected_nonzero
diff --git a/tests/morphology/test_opening.py b/tests/morphology/test_opening.py
index 84eb0e72c..18439181b 100644
--- a/tests/morphology/test_opening.py
+++ b/tests/morphology/test_opening.py
@@ -122,3 +122,26 @@ class TestOpening(BaseTester):
expected = op(tensor, kernel)
assert_close(actual, expected)
+
+ def test_opening_custom_origin_is_anti_extensive_and_idempotent(self, device, dtype):
+ # opening = dilation(erosion(x)) must stay anti-extensive (opening(x) <= x) and
+ # idempotent (opening(opening(x)) == opening(x)) under a custom origin too, not just the
+ # default centred one. `dilation`'s origin bug broke both for origin=[0, 0]. `block`
+ # already equals its own opening under `ones(3, 3)`, so the equality check also exercises
+ # idempotency; 0/1 fixtures compare exactly with `torch.equal`, the `<=` on the rand
+ # fixture never needs a tolerance (selection only, no interpolation), and repeating
+ # `opening` on its own (already-open) output is likewise exact.
+ # Generated with:
+ # block = torch.zeros(1, 1, 7, 10); block[..., 2:5, 3:7] = 1
+ # torch.rand(1, 1, 7, 10, generator=torch.Generator().manual_seed(0))
+ # A local `torch.Generator` avoids touching the process-global (and any device) RNG state.
+ block = torch.zeros(1, 1, 7, 10, device=device, dtype=dtype)
+ block[..., 2:5, 3:7] = 1.0
+ kernel = torch.ones(3, 3, device=device, dtype=dtype)
+
+ assert torch.equal(opening(block, kernel, origin=[0, 0]), block)
+
+ tensor = torch.rand(1, 1, 7, 10, generator=torch.Generator().manual_seed(0)).to(device=device, dtype=dtype)
+ opened = opening(tensor, kernel, origin=[0, 0])
+ assert (opened <= tensor).all()
+ assert torch.equal(opening(opened, kernel, origin=[0, 0]), opened)