Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(filters): add border type to median blur (#4673)

Kakarot28122e77a096de8d
diff --git a/changelog.d/4673.breaking.md b/changelog.d/4673.breaking.md
new file mode 100644
index 000000000..b3356eb09
--- /dev/null
+++ b/changelog.d/4673.breaking.md
@@ -0,0 +1,9 @@
+`median_blur` and `MedianBlur` take a `border_type` (`'constant'`, `'reflect'`, `'replicate'` or `'circular'`) and
+default to `'reflect'`, like `filter2d`, `box_blur` and `gaussian_blur2d` (#4670). Previously the window was
+zero-padded and there was no `border_type`, so a constant image came back 0 in a triangle at each corner (12 of the
+121 pixels of an 11Γ—11 image with a 5Γ—5 kernel). Now a constant image is unchanged. `RandomMedianBlur`, which has no
+`border_type`, follows the new default. Reflect padding needs each side to be longer than the kernel radius, so an
+image with a side of at most `k // 2` pixels, which used to be filtered, now raises: torch's padding error from
+`median_blur`, and a `ValueError` naming the class and the shape from `RandomMedianBlur`. On a torch without a
+float16 CPU reflection-pad kernel, such as 2.5.1, a float16 CPU input now raises, as it does in the other
+reflect-padded filters. `border_type='constant'` reproduces the old output exactly.
diff --git a/kornia/augmentation/_2d/intensity/median_blur.py b/kornia/augmentation/_2d/intensity/median_blur.py
index e932d50f1..6b85e680b 100644
--- a/kornia/augmentation/_2d/intensity/median_blur.py
+++ b/kornia/augmentation/_2d/intensity/median_blur.py
@@ -20,6 +20,7 @@ from typing import Any, Dict, Optional, Tuple
from torch import Tensor
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
+from kornia.augmentation.utils import _check_filter_min_size
from kornia.filters import median_blur
from kornia.filters.kernels import _check_kernel_size, _unpack_2d_ks
@@ -41,10 +42,13 @@ class RandomMedianBlur(IntensityAugmentationBase2D):
Convention:
- ``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``.
+ - the output is not clamped. The window is reflect-padded by :func:`kornia.filters.median_blur` by
+ default under every implementation it selects -- the ``F.conv2d`` window extraction and the selection
+ network it uses instead for a 3x3 or 5x5 inference pass alike.
+ - this class has no ``border_type`` and inherits :func:`kornia.filters.median_blur`'s default
+ ``border_type="reflect"``; like :class:`RandomBoxBlur` and :class:`RandomGaussianBlur`, it raises a
+ ``ValueError`` naming the class and the shape once a spatial axis is no longer than half the kernel's
+ extent along it.
.. note::
This function internally uses :func:`kornia.filters.median_blur`.
@@ -55,10 +59,10 @@ class RandomMedianBlur(IntensityAugmentationBase2D):
>>> out.shape
torch.Size([1, 1, 4, 4])
>>> out
- tensor([[[[0., 1., 1., 0.],
+ tensor([[[[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.],
- [0., 1., 1., 0.]]]])
+ [1., 1., 1., 1.]]]])
To apply the exact augmenation again, you may take the advantage of the previous parameter state:
>>> input = torch.randn(1, 3, 32, 32)
@@ -78,4 +82,5 @@ class RandomMedianBlur(IntensityAugmentationBase2D):
def apply_transform(
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
) -> Tensor:
+ _check_filter_min_size("RandomMedianBlur", input, flags["kernel_size"], border_type="reflect")
return median_blur(input, flags["kernel_size"])
diff --git a/kornia/filters/median.py b/kornia/filters/median.py
index fdbd43f93..2c26c338a 100644
--- a/kornia/filters/median.py
+++ b/kornia/filters/median.py
@@ -21,11 +21,13 @@ import torch
import torch.nn.functional as F
from torch import nn
-from kornia.core.check import KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
from kornia.core.utils import is_autocast_enabled, is_compiling, is_exporting
from .kernels import _check_kernel_size, _unpack_2d_ks, get_binary_kernel2d
+_VALID_BORDERS = {"constant", "reflect", "replicate", "circular"}
+
def _median_network(size: int) -> tuple[tuple[int, int, bool, bool], ...]:
"""Prune Batcher's odd-even mergesort to the middle output wire.
@@ -66,10 +68,10 @@ def _median_network(size: int) -> tuple[tuple[int, int, bool, bool], ...]:
_MEDIAN_NETWORKS = {3: _median_network(9), 5: _median_network(25)}
-def _median_blur_network(input: torch.Tensor, size: int) -> torch.Tensor:
+def _median_blur_network(input: torch.Tensor, size: int, border_type: str = "reflect") -> torch.Tensor:
"""Select a small-window median without materializing patches or sorting them."""
radius = size // 2
- padded = F.pad(input, (radius, radius, radius, radius))
+ padded = F.pad(input, (radius, radius, radius, radius), mode=border_type)
height, width = input.shape[-2:]
values = [padded[..., y : y + height, x : x + width] for y in range(size) for x in range(size)]
for left, right, low, high in _MEDIAN_NETWORKS[size]:
@@ -81,7 +83,8 @@ def _median_blur_network(input: torch.Tensor, size: int) -> torch.Tensor:
# The original one-hot convolution propagates any NaN/Inf in a window to
# every extracted feature (including 0 * Inf). Pool a finite-value mask:
# max-pooling NaNs directly is version- and dtype-dependent on CPU.
- invalid = F.max_pool2d((~torch.isfinite(input)).to(input.dtype), size, stride=1, padding=radius).bool()
+ padded_mask = F.pad((~torch.isfinite(input)).to(input.dtype), (radius, radius, radius, radius), mode=border_type)
+ invalid = F.max_pool2d(padded_mask, size, stride=1, padding=0).bool()
selected = values[size * size // 2]
return torch.where(invalid, torch.full_like(selected, float("nan")), selected).contiguous()
@@ -92,7 +95,7 @@ def _compute_zero_padding(kernel_size: tuple[int, int] | int) -> tuple[int, int]
return (ky - 1) // 2, (kx - 1) // 2
-def median_blur(input: torch.Tensor, kernel_size: tuple[int, int] | int) -> torch.Tensor:
+def median_blur(input: torch.Tensor, kernel_size: tuple[int, int] | int, border_type: str = "reflect") -> torch.Tensor:
r"""Blur an image using the median filter.
.. image:: _static/img/median_blur.png
@@ -100,6 +103,9 @@ 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. Each entry must be a positive odd integer.
+ border_type: the padding mode to be applied before filtering.
+ The expected modes are: `'constant'`, `'reflect'`, `'replicate'` or `'circular'`.
+ Default: `'reflect'`.
Returns:
the blurred input torch.Tensor with shape :math:`(B,C,H,W)`.
@@ -116,8 +122,17 @@ 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"])
+ border_type_lower = str(border_type).lower()
+ KORNIA_CHECK(
+ border_type_lower in _VALID_BORDERS,
+ f"Invalid border, {border_type}. Expected one of {_VALID_BORDERS}",
+ )
+ border_type = border_type_lower
+
ky, kx = _unpack_2d_ks(kernel_size)
_check_kernel_size((ky, kx), min_value=0)
+ if input.shape[1] == 0:
+ return input
# 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
@@ -134,7 +149,7 @@ def median_blur(input: torch.Tensor, kernel_size: tuple[int, int] | int) -> torc
and ky == kx
and ky in _MEDIAN_NETWORKS
):
- return _median_blur_network(input, ky)
+ return _median_blur_network(input, ky, border_type)
padding = _compute_zero_padding(kernel_size)
@@ -143,7 +158,17 @@ def median_blur(input: torch.Tensor, kernel_size: tuple[int, int] | int) -> torc
b, c, h, w = input.shape
# map the local window to single vector
- features: torch.Tensor = F.conv2d(input.reshape(b * c, 1, h, w), kernel, padding=padding, stride=1)
+ if border_type == "constant":
+ features: torch.Tensor = F.conv2d(input.reshape(b * c, 1, h, w), kernel, padding=padding, stride=1)
+ else:
+ padded = F.pad(input, (padding[1], padding[1], padding[0], padding[0]), mode=border_type)
+ features = F.conv2d(
+ padded.reshape(b * c, 1, h + 2 * padding[0], w + 2 * padding[1]),
+ kernel,
+ padding=0,
+ stride=1,
+ )
+
features = features.view(b, c, ky * kx, h, w) # BxCx(K_h * K_w)xHxW
# compute the median along the feature axis
@@ -158,6 +183,9 @@ class MedianBlur(nn.Module):
Args:
kernel_size: the blurring kernel size.
+ border_type: the padding mode to be applied before filtering.
+ The expected modes are: `'constant'`, `'reflect'`, `'replicate'` or `'circular'`.
+ Default: `'reflect'`.
Returns:
the blurred input torch.Tensor.
@@ -175,9 +203,10 @@ class MedianBlur(nn.Module):
"""
- def __init__(self, kernel_size: tuple[int, int] | int) -> None:
+ def __init__(self, kernel_size: tuple[int, int] | int, border_type: str = "reflect") -> None:
super().__init__()
self.kernel_size = kernel_size
+ self.border_type = border_type
def forward(self, input: torch.Tensor) -> torch.Tensor:
"""Replace each pixel with the median value in its local window.
@@ -197,4 +226,4 @@ class MedianBlur(nn.Module):
Tensor with shape :math:`(B, C, H, W)` containing the median-
filtered result for each channel independently.
"""
- return median_blur(input, self.kernel_size)
+ return median_blur(input, self.kernel_size, self.border_type)
diff --git a/tests/augmentation/test_augmentation.py b/tests/augmentation/test_augmentation.py
index 80eb8be8e..784f5937d 100644
--- a/tests/augmentation/test_augmentation.py
+++ b/tests/augmentation/test_augmentation.py
@@ -6076,10 +6076,10 @@ class TestRandomMedianBlur(BaseTester):
[
[
[
- [0.0, 1.0, 1.0, 0.0],
[1.0, 1.0, 1.0, 1.0],
[1.0, 1.0, 1.0, 1.0],
- [0.0, 1.0, 1.0, 0.0],
+ [1.0, 1.0, 1.0, 1.0],
+ [1.0, 1.0, 1.0, 1.0],
]
]
],
diff --git a/tests/augmentation/test_conventions_intensity_ops.py b/tests/augmentation/test_conventions_intensity_ops.py
index 42fdb480e..abd0078b3 100644
--- a/tests/augmentation/test_conventions_intensity_ops.py
+++ b/tests/augmentation/test_conventions_intensity_ops.py
@@ -110,22 +110,19 @@ class TestBlurConventions(BaseTester):
torch.manual_seed(_FORWARD_SEED)
assert _lit_extent(make((1, 5))(transposed)[0, 0]) == ([3], [0, 1, 2, 3, 4])
- def test_convention_median_blur_border_median_is_over_zero_padding(self, device, dtype):
- # A constant-ones image: the 3x3 window at a corner holds 5 zeros and 4 ones, so the corner comes
- # back 0 while an edge pixel (3 zeros, 6 ones) stays 1. Replicate padding would return 1 at both.
- # Snippet used to generate expected:
- # torch.manual_seed(0); y = K.RandomMedianBlur((3, 3), p=1.0)(torch.ones(1, 1, 4, 4)); print(y[0, 0, 0, :2])
- # torch.manual_seed(0); print(K.RandomMedianBlur((5, 5), p=1.0)(torch.ones(1, 1, 6, 6))[0, 0, 0])
+ def test_convention_median_blur_border_median_uses_reflect_padding(self, device, dtype):
+ # A constant-ones image: reflect padding reflects the boundary ones into the padding window,
+ # so corner, edge, and center windows all hold only ones and their medians evaluate to 1.
ones = torch.ones(1, 1, 4, 4, device=device, dtype=dtype)
torch.manual_seed(_FORWARD_SEED)
out = K.RandomMedianBlur((3, 3), p=1.0)(ones)
- assert float(out[0, 0, 0, 0]) == 0.0 and float(out[0, 0, 0, 1]) == 1.0
+ assert float(out[0, 0, 0, 0]) == 1.0 and float(out[0, 0, 0, 1]) == 1.0
assert float(out[0, 0, 1, 1]) == 1.0
- # 5x5 on a 6x6 image: the top row's window holds 3 image rows, so 15 ones at columns 2 and 3
- # (median 1) but 12 at columns 1 and 4 and 9 at the corners (median 0).
+ # 5x5 on a 6x6 image: reflect padding preserves the constant value across the border,
+ # so the top row consists entirely of ones.
torch.manual_seed(_FORWARD_SEED)
wide = K.RandomMedianBlur((5, 5), p=1.0)(torch.ones(1, 1, 6, 6, device=device, dtype=dtype))
- self.assert_close(wide[0, 0, 0], ones.new_tensor([0.0, 0.0, 1.0, 1.0, 0.0, 0.0]))
+ self.assert_close(wide[0, 0, 0], ones.new_tensor([1.0, 1.0, 1.0, 1.0, 1.0, 1.0]))
def test_convention_box_blur_even_kernel_is_accepted_and_off_centre(self, device, dtype):
# Snippet used to generate expected:
@@ -424,8 +421,8 @@ class TestBlurConventions(BaseTester):
# Issue #4559: RandomBoxBlur, RandomGaussianBlur and RandomSharpness raise a kornia `ValueError` naming
# the class, the kernel and the input shape. The two blurs reflect-pad, so an axis must be longer than the
# kernel radius (`k // 2`, one pixel for the 3x3 default); RandomSharpness convolves without padding, so
- # it needs the full 3x3. RandomMedianBlur and, at its default constant border, RandomMotionBlur accept
- # the same degenerate image.
+ # it needs the full 3x3. RandomMedianBlur reflect-pads as well and raises the same error, while
+ # RandomMotionBlur, at its default constant border, accepts the degenerate image.
# Snippet used to generate expected:
# for shape in ((2, 3, 1, 8), (2, 3, 2, 2), (2, 3, 3, 3)):
# x = torch.rand(*shape)
@@ -474,11 +471,16 @@ class TestBlurConventions(BaseTester):
_sync(K.RandomSharpness(1.0, p=1.0)(small).device)
torch.manual_seed(_FORWARD_SEED)
assert K.RandomSharpness(1.0, p=1.0)(square).shape == square.shape
- # The two rank/kernel-rotation filters accept the same one-row image, so the failure is not
- # a package-wide "kernel larger than image" rule.
- for make in (lambda: K.RandomMedianBlur(p=1.0), lambda: K.RandomMotionBlur(3, (45.0, 45.0), (0.0, 0.0), p=1.0)):
+ # RandomMedianBlur reflect-pads, so it refuses the one-row image with the same named error, before the
+ # filter runs; RandomMotionBlur, at its default constant border, still accepts it.
+ torch.manual_seed(_FORWARD_SEED)
+ with pytest.raises(ValueError, match="RandomMedianBlur cannot filter an image this small"):
+ _sync(K.RandomMedianBlur(p=1.0)(thin).device)
+ if reflect_ok:
torch.manual_seed(_FORWARD_SEED)
- assert make()(thin).shape == thin.shape
+ assert K.RandomMedianBlur(p=1.0)(small).shape == small.shape
+ torch.manual_seed(_FORWARD_SEED)
+ assert K.RandomMotionBlur(3, (45.0, 45.0), (0.0, 0.0), p=1.0)(thin).shape == thin.shape
# ``border_type="circular"`` needs each axis at least the kernel radius (``k // 2``): the two padding
# blurs raise kornia's named error below it, while ``"constant"`` and ``"replicate"`` run there.
diff --git a/tests/filters/test_median.py b/tests/filters/test_median.py
index b9d632b35..559b1cb27 100644
--- a/tests/filters/test_median.py
+++ b/tests/filters/test_median.py
@@ -45,7 +45,7 @@ class TestMedianBlur(BaseTester):
assert actual.shape == (batch_size, channels, 4, 4)
def test_exception(self, device, dtype):
- from kornia.core.exceptions import ShapeError, TypeCheckError
+ from kornia.core.exceptions import BaseError, ShapeError, TypeCheckError
with pytest.raises(TypeCheckError) as errinfo:
median_blur(1, 1)
@@ -55,6 +55,10 @@ 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)
+ with pytest.raises(BaseError) as errinfo:
+ median_blur(torch.ones(1, 1, 3, 3, device=device, dtype=dtype), 3, border_type="invalid")
+ assert "Invalid border, invalid. Expected one of" 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):
@@ -70,6 +74,49 @@ class TestMedianBlur(BaseTester):
ky, kx = (int(k) for k in kernel_size)
self.assert_close(median_blur(img, kernel_size), median_blur(img, (ky, kx)))
+ def test_default_border_type(self, device, dtype):
+ inp = torch.rand(1, 1, 5, 5, device=device, dtype=dtype)
+ actual_default = median_blur(inp, 3)
+ actual_reflect = median_blur(inp, 3, "reflect")
+ self.assert_close(actual_default, actual_reflect)
+
+ module_default = MedianBlur(3)
+ module_reflect = MedianBlur(3, "reflect")
+ self.assert_close(module_default(inp), module_reflect(inp))
+ self.assert_close(actual_default, module_default(inp))
+
+ @pytest.mark.parametrize("kernel_size", [3, 5, (3, 1), (1, 3)])
+ def test_thin_input(self, kernel_size, device, dtype):
+ inp = torch.rand(1, 1, 1, 8, device=device, dtype=dtype)
+ actual_constant = median_blur(inp, kernel_size, "constant")
+ assert actual_constant.shape == inp.shape
+
+ actual_module_constant = MedianBlur(kernel_size, "constant")(inp)
+ self.assert_close(actual_constant, actual_module_constant)
+
+ ky = kernel_size if isinstance(kernel_size, int) else kernel_size[0]
+ kx = kernel_size if isinstance(kernel_size, int) else kernel_size[1]
+ pad_y = (ky - 1) // 2
+ pad_x = (kx - 1) // 2
+ if pad_y >= inp.shape[-2] or pad_x >= inp.shape[-1]:
+ with pytest.raises(RuntimeError, match="Padding size should be less"):
+ median_blur(inp, kernel_size)
+ else:
+ actual_default = median_blur(inp, kernel_size)
+ actual_reflect = median_blur(inp, kernel_size, "reflect")
+ self.assert_close(actual_default, actual_reflect)
+
+ @pytest.mark.parametrize("border_type", ["constant", "reflect", "replicate", "circular"])
+ def test_border_type(self, border_type, device, dtype):
+ inp = torch.rand(1, 1, 5, 5, device=device, dtype=dtype)
+ actual = median_blur(inp, 3, border_type)
+ assert isinstance(actual, torch.Tensor)
+ assert actual.shape == inp.shape
+
+ # Case normalization works, e.g. "REFLECT" produces the same result as "reflect"
+ actual_upper = median_blur(inp, 3, border_type.upper())
+ self.assert_close(actual_upper, actual)
+
def test_kernel_3x3(self, device, dtype):
inp = torch.tensor(
[
@@ -124,9 +171,10 @@ class TestMedianBlur(BaseTester):
actual = median_blur(inp, kernel_size)
assert actual.is_contiguous()
+ @pytest.mark.parametrize("border_type", ["constant", "reflect", "replicate", "circular"])
@pytest.mark.parametrize("kernel_size", [3, 5])
@pytest.mark.parametrize("layout", ["contiguous", "transposed", "channels_last"])
- def test_selection_matches_convolution(self, kernel_size, layout, device, dtype):
+ def test_selection_matches_convolution(self, border_type, kernel_size, layout, device, dtype):
# Quantized signed values exercise ties and padding; the extra channel
# has random values so both branches also see distinct order statistics.
inp = torch.randint(-4, 5, (2, 3, 7, 9), device=device).to(dtype)
@@ -136,43 +184,78 @@ class TestMedianBlur(BaseTester):
elif layout == "channels_last":
inp = inp.contiguous(memory_format=torch.channels_last)
b, c, h, w = inp.shape
+ pad = kernel_size // 2
+ padded = torch.nn.functional.pad(inp, (pad, pad, pad, pad), mode=border_type)
weights = get_binary_kernel2d(kernel_size, device=device, dtype=dtype)
- features = torch.nn.functional.conv2d(inp.reshape(b * c, 1, h, w), weights, padding=kernel_size // 2)
+ features = torch.nn.functional.conv2d(padded.reshape(b * c, 1, h + 2 * pad, w + 2 * pad), weights, padding=0)
expected = features.reshape(b, c, kernel_size**2, h, w).median(2).values
- actual = median_blur(inp, kernel_size)
+ actual = median_blur(inp, kernel_size, border_type)
self.assert_close(actual, expected)
assert actual.is_contiguous()
+ @pytest.mark.parametrize("border_type", ["constant", "reflect", "replicate", "circular"])
@pytest.mark.parametrize("kernel_size", [3, 5])
@pytest.mark.parametrize("invalid", [float("nan"), float("inf"), -float("inf")])
- def test_selection_nonfinite(self, kernel_size, invalid, device, dtype):
+ def test_selection_nonfinite(self, border_type, kernel_size, invalid, device, dtype):
inp = torch.ones(1, 1, 7, 9, device=device, dtype=dtype)
inp[..., 3, 4] = invalid
# Pin the window-local contract independently of convolution: CPU bf16
# convolution on the EPYC CI runner can spread NaNs outside the window.
- # Finite windows contain only ones and zero padding, so their median is
- # one exactly when a majority of the window lies inside the image.
+ # With constant padding a finite window holds ones and zeros, so its median is
+ # one exactly when a majority of the window lies inside the image; the other
+ # modes pad a ones image with ones.
radius = kernel_size // 2
expected = torch.ones_like(inp)
- for y in range(7):
- for x in range(9):
- rows = min(7, y + radius + 1) - max(0, y - radius)
- cols = min(9, x + radius + 1) - max(0, x - radius)
- expected[..., y, x] = float(rows * cols > kernel_size**2 // 2)
+ if border_type == "constant":
+ for y in range(7):
+ for x in range(9):
+ rows = min(7, y + radius + 1) - max(0, y - radius)
+ cols = min(9, x + radius + 1) - max(0, x - radius)
+ expected[..., y, x] = float(rows * cols > kernel_size**2 // 2)
expected[..., 3 - radius : 4 + radius, 4 - radius : 5 + radius] = float("nan")
- actual = median_blur(inp, kernel_size)
+ actual = median_blur(inp, kernel_size, border_type)
+ self.assert_close(actual.isnan(), expected.isnan())
+ self.assert_close(actual.nan_to_num(), expected.nan_to_num())
+
+ @pytest.mark.parametrize("border_type", ["constant", "reflect", "replicate", "circular"])
+ @pytest.mark.parametrize("kernel_size", [3, 5])
+ @pytest.mark.parametrize("invalid", [float("nan"), float("inf"), -float("inf")])
+ def test_selection_nonfinite_border(self, border_type, kernel_size, invalid, device, dtype):
+ inp = torch.ones(1, 1, 7, 9, device=device, dtype=dtype)
+ inp[..., 0, 0] = invalid
+ radius = kernel_size // 2
+ expected = torch.ones_like(inp)
+ if border_type == "constant":
+ for y in range(7):
+ for x in range(9):
+ rows = min(7, y + radius + 1) - max(0, y - radius)
+ cols = min(9, x + radius + 1) - max(0, x - radius)
+ expected[..., y, x] = float(rows * cols > kernel_size**2 // 2)
+ expected[..., : radius + 1, : radius + 1] = float("nan")
+ if border_type == "circular":
+ expected[..., : radius + 1, -radius:] = float("nan")
+ expected[..., -radius:, : radius + 1] = float("nan")
+ expected[..., -radius:, -radius:] = float("nan")
+ actual = median_blur(inp, kernel_size, border_type)
self.assert_close(actual.isnan(), expected.isnan())
self.assert_close(actual.nan_to_num(), expected.nan_to_num())
+ @pytest.mark.parametrize("border_type", ["constant", "reflect", "replicate", "circular"])
@pytest.mark.parametrize("kernel_size", [3, 5])
@pytest.mark.parametrize("invalid", [float("nan"), float("inf"), -float("inf")])
- def test_nonfinite_autograd_fallback(self, kernel_size, invalid, device, dtype):
+ def test_nonfinite_autograd_fallback(self, border_type, kernel_size, invalid, device, dtype):
inp = torch.ones(1, 1, 7, 9, device=device, dtype=dtype)
inp[..., 3, 4] = invalid
inp.requires_grad_()
+ radius = kernel_size // 2
+ padded = torch.nn.functional.pad(
+ inp,
+ (radius, radius, radius, radius),
+ mode=border_type,
+ )
weights = get_binary_kernel2d(kernel_size, device=device, dtype=dtype)
- expected = torch.nn.functional.conv2d(inp, weights, padding=kernel_size // 2).median(1).values[:, None]
- actual = median_blur(inp, kernel_size)
+ expected = torch.nn.functional.conv2d(padded, weights, padding=0).median(1).values[:, None]
+ actual = median_blur(inp, kernel_size, border_type)
self.assert_close(actual.isnan(), expected.isnan())
self.assert_close(actual.nan_to_num(), expected.nan_to_num())
@@ -197,8 +280,14 @@ class TestMedianBlur(BaseTester):
@pytest.mark.parametrize("kernel_size", [3, 5])
def test_tied_gradients_unchanged(self, kernel_size, device, dtype):
inp = torch.randint(-2, 3, (1, 1, 7, 9), device=device).to(dtype).requires_grad_()
+ radius = kernel_size // 2
+ padded = torch.nn.functional.pad(
+ inp,
+ (radius, radius, radius, radius),
+ mode="reflect",
+ )
weights = get_binary_kernel2d(kernel_size, device=device, dtype=dtype)
- expected = torch.nn.functional.conv2d(inp, weights, padding=kernel_size // 2).median(1).values[:, None]
+ expected = torch.nn.functional.conv2d(padded, weights, padding=0).median(1).values[:, None]
expected_grad = torch.autograd.grad(expected.sum(), inp)[0]
actual = median_blur(inp, kernel_size)
self.assert_close(torch.autograd.grad(actual.sum(), inp)[0], expected_grad, atol=0, rtol=0)
@@ -210,7 +299,9 @@ class TestMedianBlur(BaseTester):
weights = get_binary_kernel2d(kernel_size, device=device, dtype=dtype)
def reference(value):
- return torch.nn.functional.conv2d(value, weights, padding=kernel_size // 2).median(1).values[:, None]
+ radius = kernel_size // 2
+ padded = torch.nn.functional.pad(value, (radius, radius, radius, radius), mode="reflect")
+ return torch.nn.functional.conv2d(padded, weights, padding=0).median(1).values[:, None]
expected, expected_jvp = torch.func.jvp(reference, (inp,), (tangent,))
actual, actual_jvp = torch.func.jvp(lambda value: median_blur(value, kernel_size), (inp,), (tangent,))
@@ -224,7 +315,9 @@ class TestMedianBlur(BaseTester):
inp = torch.rand(1, 1, 7, 9, dtype=torch.float32)
weights = get_binary_kernel2d(3, dtype=torch.float32)
with torch.autocast("cpu", dtype=autocast_dtype):
- expected = torch.nn.functional.conv2d(inp, weights, padding=1).median(1).values[:, None]
+ radius = 1
+ padded = torch.nn.functional.pad(inp, (radius, radius, radius, radius), mode="reflect")
+ expected = torch.nn.functional.conv2d(padded, weights, padding=0).median(1).values[:, None]
actual = median_blur(inp, 3)
assert actual.dtype == expected.dtype == autocast_dtype
self.assert_close(actual, expected)
@@ -234,13 +327,14 @@ class TestMedianBlur(BaseTester):
img = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)
self.gradcheck(median_blur, (img, (5, 3)))
- def test_module(self, device, dtype):
+ @pytest.mark.parametrize("border_type", ["constant", "reflect", "replicate", "circular"])
+ def test_module(self, border_type, device, dtype):
kernel_size = (3, 5)
img = torch.rand(2, 3, 4, 5, device=device, dtype=dtype)
op = median_blur
- op_module = MedianBlur((3, 5))
+ op_module = MedianBlur(kernel_size, border_type=border_type)
actual = op_module(img)
- expected = op(img, kernel_size)
+ expected = op(img, kernel_size, border_type=border_type)
self.assert_close(actual, expected)
@pytest.mark.parametrize("kernel_size", [3, 5, (5, 7)])