π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(filters): reject a 1x1 kernel_size in laplacian and the Laplacian kernel builders (#5256)
Dmytro Mishkin9b366a352a17
diff --git a/changelog.d/5256.fixed.md b/changelog.d/5256.fixed.mdnew file mode 100644index 000000000..2bc0b5d5e--- /dev/null+++ b/changelog.d/5256.fixed.md@@ -0,0 +1 @@+`laplacian`, `Laplacian`, `get_laplacian_kernel2d` and `get_laplacian_kernel1d` now reject a kernel size of 1 (`1`, or `(1, 1)` for the 2D forms) with an error that says why. A 1x1 Laplacian kernel is `[[0.0]]`, so the default `normalized=True` divided by zero and returned an all-NaN image, and `get_laplacian_kernel2d(1)` and `get_laplacian_kernel1d(1)` returned the all-zero kernel. Sizes such as `(1, 3)` and `(3, 1)`, which are a 1-D second difference, still work. `Laplacian` now validates `kernel_size` when it is constructed (odd, positive, the right length, not 1x1), so an invalid size such as `Laplacian(2)` raises there instead of at the first `forward` call.diff --git a/kornia/filters/kernels.py b/kornia/filters/kernels.pyindex 2e09ba973..37a98dfcd 100644--- a/kornia/filters/kernels.py+++ b/kornia/filters/kernels.py@@ -38,6 +38,19 @@ def _check_kernel_size(kernel_size: tuple[int, ...] | int, min_value: int = 0, a)+def _check_laplacian_kernel_size(kernel_size: tuple[int, ...] | int) -> None:+ # The Laplacian centre is 1 - prod(kernel_size), so a single tap is the all-zero kernel (0 / 0 once normalized).+ if isinstance(kernel_size, int):+ sizes: tuple[int, ...] = (kernel_size,)+ else:+ sizes = kernel_size++ KORNIA_CHECK(+ any(size != 1 for size in sizes),+ f"A Laplacian kernel needs a size of at least 3 along one axis: a single tap is all zeros. Got {kernel_size}",+ )++def _unpack_2d_ks(kernel_size: tuple[int, int] | int) -> tuple[int, int]:if isinstance(kernel_size, int):ky = kx = kernel_size@@ -831,13 +844,16 @@ def get_laplacian_kernel1d(r"""Return the coefficients of a 1D Laplacian filter.Args:- kernel_size: filter size. It should be odd and positive.+ kernel_size: filter size. It should be odd and at least 3.device: tensor device desired to create the kerneldtype: tensor dtype desired to create the kernelReturns:1D tensor with laplacian filter coefficients.+ Raises:+ BaseError: if ``kernel_size`` is even, not positive, or ``1``: a single tap is the all-zero kernel.+Shape:- Output: math:`(\text{kernel_size})`@@ -851,6 +867,7 @@ def get_laplacian_kernel1d(# TODO: add default dtype as None when kornia relies on torch > 1.12_check_kernel_size(kernel_size)+ _check_laplacian_kernel_size(kernel_size)return laplacian_1d(kernel_size, device=device, dtype=dtype)@@ -861,13 +878,17 @@ def get_laplacian_kernel2d(r"""Return Gaussian filter matrix coefficients.Args:- kernel_size: filter size should be odd.+ kernel_size: filter size should be odd, and at least 3 along one axis.device: tensor device desired to create the kerneldtype: tensor dtype desired to create the kernelReturns:2D tensor with laplacian filter matrix coefficients.+ Raises:+ BaseError: if a size is even or not positive, if ``kernel_size`` is a sequence of other than 2 sizes, or if+ it is ``1`` or ``(1, 1)``: a :math:`1 \times 1` kernel is the all-zero kernel.+Shape:- Output: :math:`(\text{kernel_size}_x, \text{kernel_size}_y)`@@ -888,6 +909,7 @@ def get_laplacian_kernel2d(ky, kx = _unpack_2d_ks(kernel_size)_check_kernel_size((ky, kx))+ _check_laplacian_kernel_size((ky, kx))kernel = torch.ones((ky, kx), device=device, dtype=dtype)mid_x = kx // 2diff --git a/kornia/filters/laplacian.py b/kornia/filters/laplacian.pyindex e62e34ca7..41e9c1286 100644--- a/kornia/filters/laplacian.py+++ b/kornia/filters/laplacian.py@@ -26,7 +26,13 @@ from kornia.core.utils import is_autocast_enabled, is_compilingfrom .blur import _HAS_MKLDNN, _ONEDNN_LARGE_INPUT, _needs_convolution_for_extreme_cpu_valuesfrom .filter import filter2d-from .kernels import _check_kernel_size, _unpack_2d_ks, get_laplacian_kernel2d, normalize_kernel2d+from .kernels import (+ _check_kernel_size,+ _check_laplacian_kernel_size,+ _unpack_2d_ks,+ get_laplacian_kernel2d,+ normalize_kernel2d,+)def _laplacian_slices_eligible(input: torch.Tensor) -> bool:@@ -42,6 +48,14 @@ def _laplacian_slices_eligible(input: torch.Tensor) -> bool:return input.device.type == "cuda" and is_compiling()+def _check_laplacian_size(kernel_size: tuple[int, int] | int) -> tuple[int, int]:+ """Unpack ``kernel_size`` and reject what no Laplacian kernel can have: even, non-positive or 1x1 sizes."""+ ky, kx = _unpack_2d_ks(kernel_size)+ _check_kernel_size((ky, kx))+ _check_laplacian_kernel_size((ky, kx))+ return ky, kx++def laplacian(input: torch.Tensor, kernel_size: tuple[int, int] | int, border_type: str = "reflect", normalized: bool = True) -> torch.Tensor:@@ -54,7 +68,7 @@ def laplacian(Args:input: the input image tensor with shape :math:`(B, C, H, W)`.- kernel_size: the size of the kernel.+ kernel_size: the size of the kernel. It should be odd and positive, and at least 3 along one axis.border_type: the padding mode to be applied before convolving.The expected modes are: ``'constant'``, ``'reflect'``,``'replicate'`` or ``'circular'``.@@ -67,6 +81,10 @@ def laplacian(Return:the blurred image with shape :math:`(B, C, H, W)`.+ Raises:+ BaseError: if a size is even or not positive, if ``kernel_size`` is a sequence of other than 2 sizes, or if+ it is ``1`` or ``(1, 1)``: a :math:`1 \times 1` kernel is all zeros, and its normalized form is ``0 / 0``.+.. note::See a working example `here <https://www.kornia.org/tutorials/nbs/filtering_edges.html>`__.@@ -84,8 +102,7 @@ def laplacian(f"Invalid border, {border_type}. Expected one of {{'constant', 'reflect', 'replicate', 'circular'}}",)- ky, kx = _unpack_2d_ks(kernel_size)- _check_kernel_size((ky, kx))+ ky, kx = _check_laplacian_size(kernel_size)if not _laplacian_slices_eligible(input) or _needs_convolution_for_extreme_cpu_values(input, ky * kx):kernel = get_laplacian_kernel2d((ky, kx), device=input.device, dtype=input.dtype)[None]@@ -125,12 +142,17 @@ class Laplacian(nn.Module):it to each channel. It supports batched operation.Args:- kernel_size: the size of the kernel.+ kernel_size: the size of the kernel. It should be odd and positive, and at least 3 along one axis.border_type: the padding mode to be applied before convolving.The expected modes are: ``'constant'``, ``'reflect'``,``'replicate'`` or ``'circular'``.normalized: if True, L1 norm of the kernel is set to 1.+ Raises:+ BaseError: if a size is even or not positive, if ``kernel_size`` is a sequence of other than 2 sizes, or if+ it is ``1`` or ``(1, 1)``. The size is checked when the module is built, as+ :func:`~kornia.filters.laplacian` checks it when called.+Shape:- Input: :math:`(B, C, H, W)`- Output: :math:`(B, C, H, W)`@@ -152,6 +174,8 @@ class Laplacian(nn.Module):self.border_type: str = border_typeself.normalized: bool = normalized+ _check_laplacian_size(kernel_size)+def __repr__(self) -> str:return (f"{self.__class__.__name__}"diff --git a/tests/filters/test_laplacian.py b/tests/filters/test_laplacian.pyindex 987127e59..0d3a97fc9 100644--- a/tests/filters/test_laplacian.py+++ b/tests/filters/test_laplacian.py@@ -20,6 +20,7 @@ import importlibimport pytestimport torch+from kornia.core.exceptions import BaseErrorfrom kornia.filters import Laplacian, filter2d, get_laplacian_kernel1d, get_laplacian_kernel2d, laplacianfrom kornia.filters.kernels import normalize_kernel2d@@ -71,8 +72,32 @@ def test_get_laplacian_kernel2d_exact(device, dtype):assert_close(expected, actual)+def test_get_laplacian_kernel1d_rejects_a_single_tap(device, dtype):+ # A single tap is the all-zero kernel [0.0]: its centre is 1 - 1. The 1-D builder does not normalize, so the+ # message must not talk about it, and it reports the size as given.+ with pytest.raises(BaseError, match="size of at least 3 along one axis") as error:+ get_laplacian_kernel1d(1, device=device, dtype=dtype)+ assert "normaliz" not in str(error.value)+ assert str(error.value).endswith("Got 1")++[email protected]("kernel_size", [1, (1, 1), [1, 1]])+def test_get_laplacian_kernel2d_rejects_a_single_tap(kernel_size, device, dtype):+ # A 1x1 kernel is the all-zero kernel [[0.0]]: its centre is 1 - 1 * 1.+ with pytest.raises(BaseError, match="size of at least 3 along one axis"):+ get_laplacian_kernel2d(kernel_size, device=device, dtype=dtype)+++def test_get_laplacian_kernel2d_accepts_a_single_tap_along_one_axis(device, dtype):+ # (1, 3) and (3, 1) are the meaningful 1-D second difference, not the degenerate 1x1 kernel.+ actual = get_laplacian_kernel2d((1, 3), device=device, dtype=dtype)+ assert_close(actual, torch.tensor([[1.0, -2.0, 1.0]], device=device, dtype=dtype))+ actual = get_laplacian_kernel2d((3, 1), device=device, dtype=dtype)+ assert_close(actual, torch.tensor([[1.0], [-2.0], [1.0]], device=device, dtype=dtype))++class TestLaplacian(BaseTester):- @pytest.mark.parametrize("kernel_size", [3, 5, (5, 7)])+ @pytest.mark.parametrize("kernel_size", [3, 5, (5, 7), (1, 3), (3, 1)])@pytest.mark.parametrize("border_type", ["constant", "reflect", "replicate", "circular"])@pytest.mark.parametrize("normalized", [True, False])def test_matches_dense_kernel(self, kernel_size, border_type, normalized, device, dtype):@@ -127,15 +152,56 @@ class TestLaplacian(BaseTester):actual = torch.vmap(lambda image: laplacian(image, 3))(data)self.assert_close(actual, expected)+ @pytest.mark.parametrize("slices", [True, False])+ @pytest.mark.parametrize("kernel_size", [1, (1, 1), [1, 1]])@pytest.mark.parametrize("normalized", [True, False])- def test_kernel_size_one(self, normalized, device, dtype):+ def test_kernel_size_one_is_rejected(self, monkeypatch, kernel_size, normalized, slices, device, dtype):+ # The 1x1 Laplacian is the all-zero kernel: zeros unnormalized, 0 / 0 = NaN normalized. The size is rejected+ # up front, whichever of the slice and convolution paths would have run.+ monkeypatch.setattr(laplacian_module, "_laplacian_slices_eligible", lambda _input: slices)data = torch.rand(1, 1, 3, 5, device=device, dtype=dtype)- actual = laplacian(data, 1, normalized=normalized)+ with pytest.raises(BaseError, match="size of at least 3 along one axis"):+ laplacian(data, kernel_size, normalized=normalized)- if normalized:- assert torch.isnan(actual).all()+ @pytest.mark.parametrize("kernel_size", [1, (1, 1), [1, 1]])+ def test_module_rejects_kernel_size_one(self, kernel_size):+ with pytest.raises(BaseError, match="size of at least 3 along one axis"):+ Laplacian(kernel_size)++ @pytest.mark.parametrize(+ "kernel_size, message",+ [+ (2, "Kernel size must be an odd integer bigger than 0"),+ (0, "Kernel size must be an odd integer bigger than 0"),+ ((2, 2), "Kernel size must be an odd integer bigger than 0"),+ ((1, 2), "Kernel size must be an odd integer bigger than 0"),+ ((-1, 1), "Kernel size must be an odd integer bigger than 0"),+ ((3, 3, 3), "2D Kernel size should have a length of 2"),+ ],+ )+ def test_module_rejects_invalid_kernel_size_at_construction(self, kernel_size, message):+ # The module validates the whole size when it is built, as laplacian() does when it is called.+ with pytest.raises(BaseError, match=message):+ Laplacian(kernel_size)+ data = torch.rand(1, 1, 5, 5)+ with pytest.raises(BaseError, match=message):+ laplacian(data, kernel_size)++ @pytest.mark.parametrize("kernel_size", [(1, 3), (3, 1)])+ @pytest.mark.parametrize("normalized", [True, False])+ def test_kernel_size_one_along_one_axis_is_a_second_difference(self, kernel_size, normalized, device, dtype):+ # Squares have the constant second difference 2, except at the reflected last sample: 2 * 16 - 50 = -18.+ row = torch.tensor([0.0, 1.0, 4.0, 9.0, 16.0, 25.0], device=device, dtype=dtype)+ expected = torch.tensor([2.0, 2.0, 2.0, 2.0, 2.0, -18.0], device=device, dtype=dtype)+ data = row.view(1, 1, 1, 6)+ if kernel_size == (3, 1):+ data = data.view(1, 1, 6, 1)+ expected = expected.view(1, 1, 6, 1)else:- self.assert_close(actual, torch.zeros_like(actual))+ expected = expected.view(1, 1, 1, 6)+ if normalized:+ expected = expected / 4.0 # the kernel [1, -2, 1] has an absolute sum of 4+ self.assert_close(laplacian(data, kernel_size, normalized=normalized), expected)@pytest.mark.parametrize("shape", [(1, 4, 8, 15), (2, 3, 11, 7)])@pytest.mark.parametrize("kernel_size", [5, (11, 7), (3, 3)])