Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(filters): dispatch border_type, padding, behaviour and mode on their lower-case spelling (#5379)

εŒΊζ’“ηc86e922160c3
diff --git a/changelog.d/5379.breaking.md b/changelog.d/5379.breaking.md
new file mode 100644
index 000000000..0eed2312b
--- /dev/null
+++ b/changelog.d/5379.breaking.md
@@ -0,0 +1,5 @@
+`filter2d` and `fft_conv` now pad for `padding='SAME'`, and for every other spelling of `'same'` (#5156), and so do
+`filter2d_separable`, `correlate2d` and `convolve2d`, which pass `padding` to `filter2d`. Previously the padding check
+accepted any spelling but only `'same'` took the padded branch, so `padding='SAME'` silently returned the
+`'valid'`-size output: a 3Γ—3 kernel on a 5Γ—7 image gave 3Γ—5 and now gives 5Γ—7, the output of `padding='same'`.
+`'VALID'` still crops, and lower-case calls are unchanged.
diff --git a/changelog.d/5379.fixed.md b/changelog.d/5379.fixed.md
new file mode 100644
index 000000000..a293f458c
--- /dev/null
+++ b/changelog.d/5379.fixed.md
@@ -0,0 +1,7 @@
+`filter2d`, `filter2d_separable`, `filter3d`, `fft_conv`, `box_blur`, `gaussian_blur2d`, `laplacian`,
+`get_spatial_gradient_kernel2d`, `get_spatial_gradient_kernel3d`, `spatial_gradient` and `spatial_gradient3d`, and the
+functions and modules that pass these options on, now accept the upper- and mixed-case spellings of `border_type` and
+`mode` that their checks already accepted (#5156). Previously `border_type='REFLECT'` passed kornia's check and then
+raised torch's `NotImplementedError: Unrecognised padding mode REFLECT`, and `mode='Sobel'` or `'Diff'` raised
+`NotImplementedError` from the kernel dispatch. Each spelling now takes the same path and gives the same result as its
+lower-case one, a spelling outside the set still raises kornia's error, and lower-case calls are unchanged.
diff --git a/kornia/filters/blur.py b/kornia/filters/blur.py
index 02cba38c1..cc8ac29b1 100644
--- a/kornia/filters/blur.py
+++ b/kornia/filters/blur.py
@@ -88,6 +88,8 @@ def _box_blur_pool(
str(border_type).lower() in {"constant", "reflect", "replicate", "circular"},
f"Invalid border, {border_type}. Expected one of constant, reflect, replicate, circular",
)
+ # the check is case-insensitive, so pad with the lower-case spelling as well
+ border_type = str(border_type).lower()
# A one-dimensional window needs only one pass, even in separable mode.
windows = ((1, kx), (ky, 1)) if separable and ky > 1 and kx > 1 else ((ky, kx),)
diff --git a/kornia/filters/filter.py b/kornia/filters/filter.py
index 17a27ced3..6b20a8bc9 100644
--- a/kornia/filters/filter.py
+++ b/kornia/filters/filter.py
@@ -93,6 +93,8 @@ def filter2d(
raises.
- ``normalized=True`` divides each kernel by the sum of its absolute values, so a zero-sum derivative kernel
keeps its sign.
+ - ``border_type``, ``padding`` and ``behaviour`` are case-insensitive: ``'REFLECT'``, ``'SAME'`` and
+ ``'CONV'`` are ``'reflect'``, ``'same'`` and ``'conv'``.
- The kernel is cast to the input's dtype and device and stays differentiable; the output has the input's
dtype.
- Known defects:
@@ -100,9 +102,6 @@ def filter2d(
- an integer input casts the kernel to its dtype, so a fractional kernel truncates to 0: a uint8 image
filtered with a box kernel comes back as zeros, or the call raises where torch has no integer
convolution (`#5155 <https://github.com/kornia/kornia/issues/5155>`_).
- - ``padding`` and ``border_type`` are checked case-insensitively but used as given: ``padding='SAME'``
- returns the ``'valid'`` output and ``border_type='REFLECT'`` raises
- (`#5156 <https://github.com/kornia/kornia/issues/5156>`_).
Args:
input: the input tensor with shape of
@@ -157,9 +156,12 @@ def filter2d(
str(behaviour).lower() in _VALID_BEHAVIOUR,
f"Invalid padding mode, {behaviour}. Expected one of {_VALID_BEHAVIOUR}",
)
+ # the checks are case-insensitive, so dispatch on the lower-case spelling as well
+ border_type, padding, behaviour = str(border_type).lower(), str(padding).lower(), str(behaviour).lower()
+
# prepare kernel
b, c, h, w = input.shape
- if str(behaviour).lower() == "conv":
+ if behaviour == "conv":
tmp_kernel = kernel.flip((-2, -1))[:, None, ...].to(device=input.device, dtype=input.dtype)
else:
tmp_kernel = kernel[:, None, ...].to(device=input.device, dtype=input.dtype)
@@ -341,10 +343,12 @@ def filter3d(
str(behaviour).lower() in _VALID_BEHAVIOUR,
f"Invalid behaviour mode, gotcha {behaviour}. Expected one of {_VALID_BEHAVIOUR}",
)
+ # the checks are case-insensitive, so dispatch on the lower-case spelling as well
+ border_type, behaviour = str(border_type).lower(), str(behaviour).lower()
# prepare kernel
b, c, d, h, w = input.shape
- if str(behaviour).lower() == "conv":
+ if behaviour == "conv":
tmp_kernel = kernel.flip((-3, -2, -1))[:, None, ...].to(device=input.device, dtype=input.dtype)
else:
tmp_kernel = kernel[:, None, ...].to(device=input.device, dtype=input.dtype)
@@ -475,6 +479,8 @@ def fft_conv(
str(behaviour).lower() in _VALID_BEHAVIOUR,
f"Invalid behaviour mode, {behaviour}. Expected one of {_VALID_BEHAVIOUR}",
)
+ # the checks are case-insensitive, so dispatch on the lower-case spelling as well
+ border_type, padding, behaviour = str(border_type).lower(), str(padding).lower(), str(behaviour).lower()
_, c, h, w = input.shape
kh, kw = kernel.shape[-2:]
@@ -486,7 +492,7 @@ def fft_conv(
" input",
)
- if str(behaviour).lower() == "conv":
+ if behaviour == "conv":
tmp_kernel = kernel.flip((-2, -1))[:, None, ...].to(device=input.device, dtype=input.dtype)
else:
tmp_kernel = kernel[:, None, ...].to(device=input.device, dtype=input.dtype)
diff --git a/kornia/filters/gaussian.py b/kornia/filters/gaussian.py
index c996cd322..25c21c091 100644
--- a/kornia/filters/gaussian.py
+++ b/kornia/filters/gaussian.py
@@ -103,7 +103,7 @@ def gaussian_blur2d(
with shape :math:`(B, 2)`. Values must be positive.
border_type: the padding mode to be applied before convolving.
The expected modes are: ``'constant'``, ``'reflect'``,
- ``'replicate'`` or ``'circular'``. Default: ``'reflect'``.
+ ``'replicate'`` or ``'circular'``, case-insensitive. Default: ``'reflect'``.
separable: run as composition of two 1d-convolutions. Default: ``True``.
Returns:
@@ -165,13 +165,14 @@ def gaussian_blur2d(
bs = sigma.shape[0]
kernel_x = get_gaussian_kernel1d(kx, sigma[:, 1].view(bs, 1))
kernel_y = get_gaussian_kernel1d(ky, sigma[:, 0].view(bs, 1))
+ border = str(border_type).lower()
if (
_gaussian_blur2d_cpu_eligible(input)
and not (torch.is_grad_enabled() and sigma.requires_grad)
and bs in (1, input.shape[0])
- and border_type in ("constant", "reflect", "replicate", "circular")
+ and border in ("constant", "reflect", "replicate", "circular")
):
- out = _gaussian_blur2d_cpu(input, kernel_x, kernel_y, border_type)
+ out = _gaussian_blur2d_cpu(input, kernel_x, kernel_y, border)
else:
out = filter2d_separable(input, kernel_x, kernel_y, border_type)
else:
diff --git a/kornia/filters/kernels.py b/kornia/filters/kernels.py
index 8d31ffda2..075407bc5 100644
--- a/kornia/filters/kernels.py
+++ b/kornia/filters/kernels.py
@@ -653,8 +653,7 @@ def get_spatial_gradient_kernel2d(
- The kernels are raw integer stencils, not derivative estimates. Per unit slope Sobel answers 8 and
``'diff'`` answers 2; per unit second derivative Sobel answers 64 on all three channels, while ``'diff'``
answers 1 on :math:`\partial_{xx}` and :math:`\partial_{yy}` and 4 on :math:`\partial_{xy}`.
- - Known defect: ``mode`` is checked case-insensitively but used as given, so ``'Sobel'`` raises
- (`#5156 <https://github.com/kornia/kornia/issues/5156>`_).
+ - ``mode`` is case-insensitive: ``'Sobel'`` is ``'sobel'``.
Args:
mode: ``'sobel'`` or ``'diff'``.
@@ -669,6 +668,8 @@ def get_spatial_gradient_kernel2d(
"""
KORNIA_CHECK(mode.lower() in {"sobel", "diff"}, f"Mode should be `sobel` or `diff`. Got {mode}")
KORNIA_CHECK(order in {1, 2}, f"Order should be 1 or 2. Got {order}")
+ # the check is case-insensitive, so dispatch on the lower-case spelling as well
+ mode = mode.lower()
if mode == "sobel" and order == 1:
kernel: torch.Tensor = get_sobel_kernel2d(device=device, dtype=dtype)
@@ -697,12 +698,10 @@ def get_spatial_gradient_kernel3d(
singleton second axis that :func:`~kornia.filters.get_spatial_gradient_kernel2d` lacks.
- In a floating ``dtype`` every channel is in derivative units: it answers 1 to a unit slope or a unit
second derivative, unlike the raw 2d stencils.
- - Known defects:
-
- - ``mode`` is checked case-insensitively but used as given, so ``'Diff'`` raises
- (`#5156 <https://github.com/kornia/kornia/issues/5156>`_).
- - a signed integer ``dtype`` truncates the half and quarter taps to 0, so the first-order channels and
- the mixed second-order ones are all zero (`#5155 <https://github.com/kornia/kornia/issues/5155>`_).
+ - ``mode`` is case-insensitive: ``'Diff'`` is ``'diff'``.
+ - Known defect: a signed integer ``dtype`` truncates the half and quarter taps to 0, so the first-order
+ channels and the mixed second-order ones are all zero
+ (`#5155 <https://github.com/kornia/kornia/issues/5155>`_).
Args:
mode: ``'diff'``.
@@ -716,6 +715,8 @@ def get_spatial_gradient_kernel3d(
"""
KORNIA_CHECK(mode.lower() in {"sobel", "diff"}, f"Mode should be `sobel` or `diff`. Got {mode}")
KORNIA_CHECK(order in {1, 2}, f"Order should be 1 or 2. Got {order}")
+ # the check is case-insensitive, so dispatch on the lower-case spelling as well
+ mode = mode.lower()
if mode == "diff" and order == 1:
kernel = get_diff_kernel3d(device=device, dtype=dtype)
diff --git a/kornia/filters/laplacian.py b/kornia/filters/laplacian.py
index 41e9c1286..b489ae713 100644
--- a/kornia/filters/laplacian.py
+++ b/kornia/filters/laplacian.py
@@ -101,6 +101,8 @@ def laplacian(
str(border_type).lower() in {"constant", "reflect", "replicate", "circular"},
f"Invalid border, {border_type}. Expected one of {{'constant', 'reflect', 'replicate', 'circular'}}",
)
+ # the check is case-insensitive, so pad with the lower-case spelling as well
+ border_type = str(border_type).lower()
ky, kx = _check_laplacian_size(kernel_size)
diff --git a/kornia/filters/sobel.py b/kornia/filters/sobel.py
index c3e794512..20c3d2aec 100644
--- a/kornia/filters/sobel.py
+++ b/kornia/filters/sobel.py
@@ -40,7 +40,7 @@ def spatial_gradient(input: torch.Tensor, mode: str = "sobel", order: int = 1, n
Args:
input: input image torch.Tensor with shape :math:`(B, C, H, W)`.
- mode: derivatives modality, can be: `sobel` or `diff`.
+ mode: derivatives modality, can be: `sobel` or `diff`, case-insensitive.
order: the order of the derivatives.
normalized: if ``True``, scale the kernels so that every output channel estimates the derivative
itself, exact on linear surfaces for ``order=1`` and on quadratic surfaces for ``order=2``. If
@@ -68,7 +68,7 @@ def spatial_gradient(input: torch.Tensor, mode: str = "sobel", order: int = 1, n
# of allocating one kernel, transposing it, stacking both directions, and
# normalizing at runtime. Keep the generic construction for integer and
# complex inputs, whose division semantics are part of the public API.
- if mode == "sobel" and order == 1 and input.is_floating_point():
+ if mode.lower() == "sobel" and order == 1 and input.is_floating_point():
if normalized:
kernel = torch.tensor(
[
@@ -109,7 +109,7 @@ def spatial_gradient3d(input: torch.Tensor, mode: str = "diff", order: int = 1)
Args:
input: input features torch.Tensor with shape :math:`(B, C, D, H, W)`.
- mode: derivatives modality, can be: `sobel` or `diff`.
+ mode: derivatives modality, can be: `sobel` or `diff`, case-insensitive.
order: the order of the derivatives.
Return:
@@ -130,7 +130,7 @@ def spatial_gradient3d(input: torch.Tensor, mode: str = "diff", order: int = 1)
b, c, d, h, w = input.shape
dev = input.device
dtype = input.dtype
- if (mode == "diff") and (order == 1):
+ if mode.lower() == "diff" and order == 1:
# we go for the special case implementation due to conv3d bad speed
x: torch.Tensor = F.pad(input, 6 * [1], "replicate")
center = slice(1, -1)
@@ -207,7 +207,7 @@ class SpatialGradient(nn.Module):
r"""Compute the first order image derivative in both x and y using a Sobel operator.
Args:
- mode: derivatives modality, can be: `sobel` or `diff`.
+ mode: derivatives modality, can be: `sobel` or `diff`, case-insensitive.
order: the order of the derivatives.
normalized: whether the output is normalized.
@@ -263,7 +263,7 @@ class SpatialGradient3d(nn.Module):
r"""Compute the first and second order volume derivative in x, y and d using a diff operator.
Args:
- mode: derivatives modality, can be: `sobel` or `diff`.
+ mode: derivatives modality, can be: `sobel` or `diff`, case-insensitive.
order: the order of the derivatives.
Return:
diff --git a/tests/filters/test_filters.py b/tests/filters/test_filters.py
index a16874021..dcee6257e 100644
--- a/tests/filters/test_filters.py
+++ b/tests/filters/test_filters.py
@@ -33,6 +33,7 @@ from kornia.filters import (
filter2d_separable,
filter3d,
gaussian,
+ gaussian_blur2d,
get_binary_kernel2d,
get_box_kernel1d,
get_box_kernel2d,
@@ -51,8 +52,12 @@ from kornia.filters import (
get_sobel_kernel2d,
get_spatial_gradient_kernel2d,
get_spatial_gradient_kernel3d,
+ laplacian,
laplacian_1d,
+ spatial_gradient,
+ spatial_gradient3d,
)
+from kornia.filters.blur import _box_blur_pool
from testing.base import (
BaseTester,
@@ -60,6 +65,7 @@ from testing.base import (
_supports_kernel_probe,
supports_nearest_3d_grid_sample,
supports_reflect_padding,
+ supports_replicate_padding,
)
@@ -1696,32 +1702,103 @@ class TestConventionsFilter2d(BaseTester):
assert out[..., 2, 3].flatten()[0].item() == 0
@pytest.mark.parametrize("name", ["filter2d", "fft_conv"])
- def test_wart_uppercase_padding_returns_the_valid_size_5156(self, name, device, dtype):
- """padding='SAME' passes the case-insensitive check but misses the 'same' branch: valid size (#5156)."""
+ def test_convention_padding_and_behaviour_are_case_insensitive_5156(self, name, device, dtype):
+ """padding='SAME' pads as 'same' does and 'Valid' crops as 'valid', in filter2d and fft_conv (#5156)."""
_fft_guard(name, device, dtype)
+ fn = _FILTER2D_FNS[name]
image = _rand(1, 1, 5, 7, device=device, dtype=dtype)
kernel = _rand(1, 3, 3, device=device, dtype=dtype, seed=1)
- assert _FILTER2D_FNS[name](image, kernel, "constant", padding="SAME").shape == (1, 1, 3, 5)
+ same = fn(image, kernel, "constant", padding="SAME")
+ assert same.shape == (1, 1, 5, 7)
+ assert torch.equal(same, fn(image, kernel, "constant", padding="same"))
+ valid = fn(image, kernel, "constant", padding="Valid")
+ assert valid.shape == (1, 1, 3, 5)
+ assert torch.equal(valid, fn(image, kernel, "constant", padding="valid"))
+ conv = fn(image, kernel, "constant", behaviour="CONV")
+ assert torch.equal(conv, fn(image, kernel, "constant", behaviour="conv"))
+ # a spelling outside the set is still rejected by kornia, and the message keeps it as given
+ with pytest.raises(BaseError, match="Invalid padding mode, Full"):
+ fn(image, kernel, "constant", padding="Full")
@pytest.mark.parametrize(
"case",
- ["filter2d_border_type", "fft_conv_border_type", "filter3d_border_type", "kernel2d_mode", "kernel3d_mode"],
+ [
+ "filter2d",
+ "filter2d_separable",
+ "fft_conv",
+ "filter3d",
+ "box_blur_pool",
+ "laplacian",
+ "gaussian_blur2d",
+ "kernel2d_mode",
+ "kernel3d_mode",
+ "spatial_gradient_order1",
+ "spatial_gradient_order2",
+ "spatial_gradient3d_order1",
+ "spatial_gradient3d_order2",
+ ],
)
- def test_wart_uppercase_border_type_or_mode_passes_validation_then_raises_5156(self, case, device, dtype):
- """'REFLECT', 'Replicate', 'Sobel' and 'Diff' pass the case-insensitive check, then fail to dispatch (#5156)."""
- image = _rand(1, 1, 5, 7, device=device, dtype=dtype)
+ def test_convention_border_type_and_mode_are_case_insensitive_5156(self, case, device, dtype):
+ """'REFLECT', 'Replicate', 'CIRCULAR', 'Sobel' and 'Diff' give their lower-case spelling's result (#5156).
+
+ The ``order=1`` gradients and the large ``gaussian_blur2d`` image take the fast paths, which dispatch on the
+ spelling themselves, so the upper-case call must take the same path and not fall through to the generic one.
+ """
+ _fft_guard(case, device, dtype)
+ if "gradient" in case and not supports_replicate_padding(device, dtype):
+ pytest.skip("spatial_gradient pads with mode='replicate', which this device lacks for this dtype")
+ image = _rand(1, 2, 5, 7, device=device, dtype=dtype)
+ volume = _rand(1, 1, 3, 5, 7, device=device, dtype=dtype)
kernel = _rand(1, 3, 3, device=device, dtype=dtype, seed=1)
+ # 256x256 with 2 channels is the smallest image the CPU fast path of gaussian_blur2d accepts
+ large = _rand(1, 2, 256, 256, device=device, dtype=dtype) if case == "gaussian_blur2d" else image
calls = {
- "filter2d_border_type": lambda: filter2d(image, kernel, border_type="REFLECT"),
- "fft_conv_border_type": lambda: fft_conv(image, kernel, border_type="REFLECT"),
- "filter3d_border_type": lambda: filter3d(image[:, :, None], kernel[:, None], border_type="Replicate"),
- "kernel2d_mode": lambda: get_spatial_gradient_kernel2d("Sobel", 1, device=device, dtype=dtype),
- "kernel3d_mode": lambda: get_spatial_gradient_kernel3d("Diff", 1, device=device, dtype=dtype),
+ "filter2d": lambda spelling: filter2d(image, kernel, border_type=spelling),
+ "filter2d_separable": lambda spelling: filter2d_separable(image, kernel[:, 0], kernel[:, 1], spelling),
+ "fft_conv": lambda spelling: fft_conv(image, kernel, border_type=spelling),
+ "filter3d": lambda spelling: filter3d(volume, kernel[:, None].expand(-1, 3, -1, -1), spelling),
+ "box_blur_pool": lambda spelling: _box_blur_pool(image, (3, 3), spelling, True),
+ "laplacian": lambda spelling: laplacian(image, 3, border_type=spelling),
+ "gaussian_blur2d": lambda spelling: gaussian_blur2d(large, (3, 3), (1.0, 1.0), border_type=spelling),
+ "kernel2d_mode": lambda spelling: get_spatial_gradient_kernel2d(spelling, 1, device=device, dtype=dtype),
+ "kernel3d_mode": lambda spelling: get_spatial_gradient_kernel3d(spelling, 2, device=device, dtype=dtype),
+ "spatial_gradient_order1": lambda spelling: spatial_gradient(image, mode=spelling, order=1),
+ "spatial_gradient_order2": lambda spelling: spatial_gradient(image, mode=spelling, order=2),
+ "spatial_gradient3d_order1": lambda spelling: spatial_gradient3d(volume, mode=spelling, order=1),
+ "spatial_gradient3d_order2": lambda spelling: spatial_gradient3d(volume, mode=spelling, order=2),
}
- # the error comes from past the check (torch's F.pad or the kernel dispatch), not from kornia's validation
- with pytest.raises(Exception) as error:
- calls[case]()
- assert not isinstance(error.value, BaseError)
+ spellings = {
+ "kernel2d_mode": [("Sobel", "sobel"), ("DIFF", "diff")],
+ "kernel3d_mode": [("Diff", "diff")],
+ "spatial_gradient_order1": [("Sobel", "sobel"), ("DIFF", "diff")],
+ "spatial_gradient_order2": [("Sobel", "sobel"), ("DIFF", "diff")],
+ "spatial_gradient3d_order1": [("Diff", "diff")],
+ "spatial_gradient3d_order2": [("Diff", "diff")],
+ }.get(case, [("REFLECT", "reflect"), ("Replicate", "replicate"), ("CIRCULAR", "circular")])
+ for upper, lower in spellings:
+ if lower == "reflect" and not supports_reflect_padding(device, dtype):
+ continue
+ assert torch.equal(calls[case](upper), calls[case](lower))
+ if case == "spatial_gradient3d_order1":
+ # the slicing fast path differences a +-60000 step to inf in float16 while conv3d accumulates it to 60000,
+ # so the two spellings only agree when both take the same path
+ step = torch.full_like(volume, -60000.0)
+ step[..., 4:] = 60000.0
+ assert torch.equal(spatial_gradient3d(step, mode="Diff"), spatial_gradient3d(step, mode="diff"))
+ # a spelling outside the set is still rejected by kornia, and the message keeps it as given
+ bad = "Scharr" if "mode" in case or "gradient" in case else "Mirror"
+ with pytest.raises(BaseError, match=bad):
+ calls[case](bad)
+
+ def test_convention_filter3d_behaviour_is_case_insensitive_5156(self, device, dtype):
+ """filter3d(behaviour='CONV') flips the kernel as 'conv' does, and 'Corr' correlates as 'corr' does (#5156)."""
+ volume = _rand(1, 2, 3, 5, 7, device=device, dtype=dtype)
+ kernel = _rand(1, 3, 3, 3, device=device, dtype=dtype, seed=1)
+ conv = filter3d(volume, kernel, behaviour="conv")
+ corr = filter3d(volume, kernel, behaviour="corr")
+ assert not torch.equal(conv, corr)
+ assert torch.equal(filter3d(volume, kernel, behaviour="CONV"), conv)
+ assert torch.equal(filter3d(volume, kernel, behaviour="Corr"), corr)
@pytest.mark.parametrize("behaviour", ["corr", "conv"])
def test_convention_filter3d_normalized_accepts_a_non_contiguous_kernel_5159(self, behaviour, device, dtype):
diff --git a/tests/filters/test_gaussian_cpu.py b/tests/filters/test_gaussian_cpu.py
index bdb02944c..9ef4c2321 100644
--- a/tests/filters/test_gaussian_cpu.py
+++ b/tests/filters/test_gaussian_cpu.py
@@ -110,6 +110,29 @@ class TestGaussianBlurCpu(BaseTester):
self.assert_close(actual, expected, rtol=tolerance, atol=tolerance)
assert calls == 1
+ def test_convention_upper_case_border_type_takes_the_slice_path_5156(self, monkeypatch, device, dtype):
+ """'REFLECT', 'Replicate', 'CIRCULAR' and 'Constant' take the slice path of the lower-case spelling (#5156)."""
+ _require_native_cpu(device, dtype)
+ _use_native_cpu_path(monkeypatch)
+ image = torch.rand(1, 2, 256, 256, device=device, dtype=dtype)
+ helper = gaussian_module._gaussian_blur2d_cpu
+ borders = []
+
+ def recording_helper(input, kernel_x, kernel_y, border_type):
+ borders.append(border_type)
+ return helper(input, kernel_x, kernel_y, border_type)
+
+ monkeypatch.setattr(gaussian_module, "_gaussian_blur2d_cpu", recording_helper)
+ for upper, lower in [
+ ("REFLECT", "reflect"),
+ ("Replicate", "replicate"),
+ ("CIRCULAR", "circular"),
+ ("Constant", "constant"),
+ ]:
+ expected = gaussian_blur2d(image, (5, 7), (0.9, 1.3), lower)
+ assert torch.equal(gaussian_blur2d(image, (5, 7), (0.9, 1.3), upper), expected)
+ assert borders == [b for b in ("reflect", "replicate", "circular", "constant") for _ in range(2)]
+
def test_public_reverse_mode_gradients_match_convolution(self, monkeypatch, device, dtype):
_require_native_cpu(device, dtype)
_use_native_cpu_path(monkeypatch)
diff --git a/tests/filters/test_sobel.py b/tests/filters/test_sobel.py
index db7022c53..a37653437 100644
--- a/tests/filters/test_sobel.py
+++ b/tests/filters/test_sobel.py
@@ -15,6 +15,8 @@
# limitations under the License.
#
+import importlib
+
import pytest
import torch
import torch.nn.functional as F
@@ -25,6 +27,8 @@ from kornia.filters.kernels import get_spatial_gradient_kernel2d, normalize_kern
from testing.base import BaseTester
+sobel_module = importlib.import_module("kornia.filters.sobel")
+
class TestSpatialGradient(BaseTester):
@pytest.mark.parametrize("batch_size", [1, 2])
@@ -161,6 +165,18 @@ class TestSpatialGradient(BaseTester):
assert torch.equal(torch.isinf(actual), torch.isinf(expected))
self.assert_close(torch.nan_to_num(actual), torch.nan_to_num(expected))
+ @pytest.mark.parametrize("normalized", [True, False])
+ def test_convention_upper_case_sobel_takes_the_fixed_kernel_path_5156(self, normalized, monkeypatch, device, dtype):
+ """mode='Sobel' at order=1 uses the fixed kernel of 'sobel' and does not call the kernel builder (#5156)."""
+
+ def should_not_run(*args, **kwargs):
+ raise AssertionError("order=1 Sobel on a floating input must use the fixed kernel")
+
+ monkeypatch.setattr(sobel_module, "get_spatial_gradient_kernel2d", should_not_run)
+ img = torch.rand(1, 2, 5, 7, device=device, dtype=dtype)
+ expected = spatial_gradient(img, "sobel", 1, normalized)
+ assert torch.equal(spatial_gradient(img, "Sobel", 1, normalized), expected)
+
def test_edges_sep(self, device, dtype):
inp = torch.tensor(
[
@@ -482,6 +498,17 @@ class TestSpatialGradient3d(BaseTester):
actual = spatial_gradient3d(inp, "diff", order=2)[:, 0, :, 1:-1, 1:-1, 1:-1]
self.assert_close(actual, expected[..., None, None, None].expand_as(actual))
+ def test_convention_upper_case_diff_takes_the_slicing_path_5156(self, monkeypatch, device, dtype):
+ """mode='Diff' at order=1 takes the slicing path of 'diff' and does not call the kernel builder (#5156)."""
+
+ def should_not_run(*args, **kwargs):
+ raise AssertionError("order=1 diff must use the slicing path")
+
+ monkeypatch.setattr(sobel_module, "get_spatial_gradient_kernel3d", should_not_run)
+ img = torch.rand(1, 2, 3, 5, 7, device=device, dtype=dtype)
+ expected = spatial_gradient3d(img, "diff", 1)
+ assert torch.equal(spatial_gradient3d(img, "Diff", 1), expected)
+
def test_gradcheck(self, device):
img = torch.rand(1, 1, 1, 3, 4, device=device, dtype=torch.float64)
fast_mode = "cpu" in str(device) # disable fast mode on gpu