Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Reject even kernel_size in median_blur (#5007)

niukanen1cd5b58a7b4a1
diff --git a/changelog.d/5007.breaking.md b/changelog.d/5007.breaking.md
new file mode 100644
index 000000000..4261b8531
--- /dev/null
+++ b/changelog.d/5007.breaking.md
@@ -0,0 +1 @@
+`kornia.filters.median_blur`, `MedianBlur` and `RandomMedianBlur` now reject an even or non-positive `kernel_size` entry with kornia's `BaseError` ("Kernel size must be an odd integer bigger than 0"), and `RandomMedianBlur` does so at construction. Previously `RandomMedianBlur` accepted such a kernel at construction, and the call failed with a raw torch `RuntimeError` from a reshape, a pad or a convolution, which `except RuntimeError` no longer catches. The one input that used to pass was an even kernel on an empty batch or an image with zero channels, which returned an empty tensor and now raises too. Integral floats and numpy integers such as `(3.0, 3.0)` are still accepted.
diff --git a/kornia/augmentation/_2d/intensity/median_blur.py b/kornia/augmentation/_2d/intensity/median_blur.py
index d2db8cc9d..e932d50f1 100644
--- a/kornia/augmentation/_2d/intensity/median_blur.py
+++ b/kornia/augmentation/_2d/intensity/median_blur.py
@@ -21,6 +21,7 @@ from torch import Tensor
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
from kornia.filters import median_blur
+from kornia.filters.kernels import _check_kernel_size, _unpack_2d_ks
class RandomMedianBlur(IntensityAugmentationBase2D):
@@ -38,16 +39,13 @@ class RandomMedianBlur(IntensityAugmentationBase2D):
to the batch form (False).
Convention:
- - ``kernel_size`` is ``(kH, kW)``: rows, then columns, as in :func:`kornia.filters.median_blur`.
+ - ``kernel_size`` is ``(kH, kW)``: rows, then columns, as in :func:`kornia.filters.median_blur`. An
+ even entry is rejected at construction with that function's odd-size error.
- the output is not clamped. The window is zero-padded, so a border median is taken over zeros as well
as image values, and a border pixel can come back as ``0`` even when no input value is near it.
- this class has no ``border_type``, and with an odd ``kernel_size`` an image smaller than the kernel is
accepted, down to ``1 x 1``.
- .. warning::
- An even entry in ``kernel_size`` is accepted at construction and then fails on the forward pass with a raw
- torch error rather than a named one. Tracked in `#4781 <https://github.com/kornia/kornia/issues/4781>`_.
-
.. note::
This function internally uses :func:`kornia.filters.median_blur`.
@@ -74,6 +72,7 @@ class RandomMedianBlur(IntensityAugmentationBase2D):
self, kernel_size: Tuple[int, int] = (3, 3), same_on_batch: bool = False, p: float = 0.5, keepdim: bool = False
) -> None:
super().__init__(p=p, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim)
+ _check_kernel_size(_unpack_2d_ks(kernel_size), 0)
self.flags = {"kernel_size": kernel_size}
def apply_transform(
diff --git a/kornia/filters/median.py b/kornia/filters/median.py
index 6af203bbe..fdbd43f93 100644
--- a/kornia/filters/median.py
+++ b/kornia/filters/median.py
@@ -24,7 +24,7 @@ from torch import nn
from kornia.core.check import KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
from kornia.core.utils import is_autocast_enabled, is_compiling, is_exporting
-from .kernels import _unpack_2d_ks, get_binary_kernel2d
+from .kernels import _check_kernel_size, _unpack_2d_ks, get_binary_kernel2d
def _median_network(size: int) -> tuple[tuple[int, int, bool, bool], ...]:
@@ -99,7 +99,7 @@ def median_blur(input: torch.Tensor, kernel_size: tuple[int, int] | int) -> torc
Args:
input: the input image with shape :math:`(B,C,H,W)`.
- kernel_size: the blurring kernel size.
+ kernel_size: the blurring kernel size. Each entry must be a positive odd integer.
Returns:
the blurred input torch.Tensor with shape :math:`(B,C,H,W)`.
@@ -116,8 +116,8 @@ def median_blur(input: torch.Tensor, kernel_size: tuple[int, int] | int) -> torc
"""
KORNIA_CHECK_IS_TENSOR(input)
KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])
-
ky, kx = _unpack_2d_ks(kernel_size)
+ _check_kernel_size((ky, kx), min_value=0)
# ATen's per-pixel median reduction dominates inference for small windows.
# A fixed selection network avoids it. Inductor fuses the network into one
# CUDA kernel; eager CUDA launches one kernel per comparator, which only pays
diff --git a/tests/augmentation/test_augmentation.py b/tests/augmentation/test_augmentation.py
index 6e571e6cb..eeae2485d 100644
--- a/tests/augmentation/test_augmentation.py
+++ b/tests/augmentation/test_augmentation.py
@@ -6040,6 +6040,15 @@ class TestRandomMedianBlur(BaseTester):
self.assert_close(out, expected)
+ def test_exception(self):
+ with pytest.raises(Exception) as errinfo:
+ RandomMedianBlur((4, 4), p=1.0)
+ assert "Kernel size must be an odd integer" in str(errinfo.value)
+
+ with pytest.raises(Exception) as errinfo:
+ RandomMedianBlur((3, 4), p=1.0)
+ assert "Kernel size must be an odd integer" in str(errinfo.value)
+
class TestRandomRain(BaseTester):
torch.manual_seed(0) # for random reproductibility
diff --git a/tests/augmentation/test_conventions_intensity_ops.py b/tests/augmentation/test_conventions_intensity_ops.py
index d0ae8942b..eaf9cd74b 100644
--- a/tests/augmentation/test_conventions_intensity_ops.py
+++ b/tests/augmentation/test_conventions_intensity_ops.py
@@ -176,18 +176,14 @@ class TestBlurConventions(BaseTester):
torch.manual_seed(_FORWARD_SEED)
self.assert_close(K.RandomMedianBlur((1, 5), p=1.0)(transposed)[0, 0].sum(-2), transposed.new_zeros(7))
- # Wart (#4781, https://github.com/kornia/kornia/issues/4781): an even entry is constructed and then fails on
- # every image size with a raw torch error, not a kornia one. Rejecting it with a kornia error or
- # supporting it flips this pin.
- @pytest.mark.parametrize("shape", [(2, 3, 32, 32), (2, 3, 1, 1)])
- def test_wart_random_median_blur_even_kernel_raises_a_raw_torch_error_4781(self, device, dtype, shape):
- torch.manual_seed(_FIXTURE_SEED)
- image = torch.rand(*shape).to(device=device, dtype=dtype)
- torch.manual_seed(_FORWARD_SEED)
- even = K.RandomMedianBlur((4, 4), p=1.0)
- with pytest.raises(RuntimeError) as raised:
- _sync(even(image).device)
- assert type(raised.value) is RuntimeError
+ # Fixed (#4781, https://github.com/kornia/kornia/issues/4781): an even entry used to be accepted at
+ # construction and then fail on every image size with a raw torch error. It is now rejected at
+ # construction with kornia's odd-size error.
+ @pytest.mark.parametrize("kernel_size", [(4, 4), (3, 4)])
+ def test_convention_random_median_blur_even_kernel_is_rejected_4781(self, kernel_size):
+ with pytest.raises(BaseError) as raised:
+ K.RandomMedianBlur(kernel_size, p=1.0)
+ assert "Kernel size must be an odd integer" in str(raised.value)
# ``normalized`` is forwarded as box_blur's ``separable``; both branches are means and agree to rounding.
# Snippet used to generate expected:
diff --git a/tests/filters/test_median.py b/tests/filters/test_median.py
index 4eb9f4e1a..b9d632b35 100644
--- a/tests/filters/test_median.py
+++ b/tests/filters/test_median.py
@@ -17,9 +17,11 @@
import importlib
+import numpy as np
import pytest
import torch
+from kornia.core.exceptions import BaseError
from kornia.filters import MedianBlur, median_blur
from kornia.filters.kernels import get_binary_kernel2d
@@ -53,6 +55,21 @@ class TestMedianBlur(BaseTester):
median_blur(torch.ones(1, 1, device=device, dtype=dtype), 1)
assert "Shape dimension mismatch" in str(errinfo.value) or "Expected shape" in str(errinfo.value)
+ @pytest.mark.parametrize("kernel_size", [4, (3, 4), (4, 3), 0, (3, -1)])
+ @pytest.mark.parametrize("shape", [(1, 1, 4, 4), (0, 1, 4, 4)])
+ def test_exception_kernel_size(self, kernel_size, shape, device, dtype):
+ # (#4781) an even or non-positive entry has no centred window; it is named, not left to torch's reshape.
+ with pytest.raises(BaseError) as errinfo:
+ median_blur(torch.ones(*shape, device=device, dtype=dtype), kernel_size)
+ assert "Kernel size must be an odd integer" in str(errinfo.value)
+
+ @pytest.mark.parametrize("kernel_size", [(3.0, 3.0), (np.int64(3), np.int64(5))])
+ def test_kernel_size_entries_are_cast_to_int(self, kernel_size, device, dtype):
+ # The odd-size check runs on the int-cast entries, so integral floats and numpy ints keep working.
+ img = torch.arange(35, device=device, dtype=dtype).reshape(1, 1, 5, 7)
+ ky, kx = (int(k) for k in kernel_size)
+ self.assert_close(median_blur(img, kernel_size), median_blur(img, (ky, kx)))
+
def test_kernel_3x3(self, device, dtype):
inp = torch.tensor(
[