π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(filters): reject a kernel larger than the input in fft_conv with padding='valid' (#5302)
εΊζ’η4a39eb387d37
diff --git a/changelog.d/5302.fixed.md b/changelog.d/5302.fixed.mdnew file mode 100644index 000000000..e6c3b71bf--- /dev/null+++ b/changelog.d/5302.fixed.md@@ -0,0 +1,4 @@+`fft_conv` with `padding='valid'` now raises a `BaseError` for a kernel taller or wider than the input, as `filter2d`+does (#5285). Previously the kernel was truncated to the input size in the frequency domain and the crop read its+negative size from the end of the tensor, so on a 5 x 6 image a 7 x 3 kernel returned a 4 x 4 tensor and a 6 x 3+kernel an empty one. A kernel as large as the input still gives one output pixel, and `padding='same'` is unchanged.diff --git a/kornia/filters/filter.py b/kornia/filters/filter.pyindex 68b4f50c3..f09cfd1f3 100644--- a/kornia/filters/filter.py+++ b/kornia/filters/filter.py@@ -394,8 +394,6 @@ def fft_conv(- an integer input truncates a fractional kernel to 0, as in :func:`~kornia.filters.filter2d`, and theresult is in torch's default floating dtype (float32) instead of the input's(`#5155 <https://github.com/kornia/kornia/issues/5155>`_).- - with ``padding='valid'`` and a kernel taller or wider than the input, it returns a wrongly sized tensor- where :func:`~kornia.filters.filter2d` raises (`#5285 <https://github.com/kornia/kornia/issues/5285>`_).Args:input: Input tensor of shape :math:`(B, C, H, W)`.@@ -467,9 +465,16 @@ def fft_conv(f"Invalid behaviour mode, {behaviour}. Expected one of {_VALID_BEHAVIOUR}",)- _, c, _, _ = input.shape+ _, c, h, w = input.shapekh, kw = kernel.shape[-2:]+ # without padding the kernel has to fit inside the input, as F.conv2d requires in filter2d+ KORNIA_CHECK(+ padding == "same" or (kh <= h and kw <= w),+ f"With padding='valid' the kernel must not be larger than the input. Got a {kh} x {kw} kernel for a {h} x {w}"+ " input",+ )+if str(behaviour).lower() == "conv":tmp_kernel = kernel.flip((-2, -1))[:, None, ...].to(device=input.device, dtype=input.dtype)else:diff --git a/tests/filters/test_filters.py b/tests/filters/test_filters.pyindex 8621e15a7..b197f4f2f 100644--- a/tests/filters/test_filters.py+++ b/tests/filters/test_filters.py@@ -1659,14 +1659,21 @@ class TestConventionsFilter2d(BaseTester):out = filter3d(volume, kernel, "constant", normalized=True, behaviour=behaviour)assert torch.equal(out, expected)- def test_wart_fft_conv_valid_padding_with_a_kernel_larger_than_the_input_5285(self, device, dtype):- """With padding='valid', a 7 x 3 kernel on a 5 x 6 image gives fft_conv a 4 x 4 output (#5285)."""- _fft_guard("fft_conv", device, dtype)+ @pytest.mark.parametrize("name", ["filter2d", "fft_conv"])+ def test_convention_filter2d_valid_padding_rejects_a_kernel_larger_than_the_input_5285(self, name, device, dtype):+ """With padding='valid', a kernel taller or wider than the input raises, in fft_conv as in filter2d (#5285)."""+ _fft_guard(name, device, dtype)+ fn = _FILTER2D_FNS[name]image = _rand(1, 1, 5, 6, device=device, dtype=dtype)- kernel = _rand(1, 7, 3, device=device, dtype=dtype, seed=1)- with pytest.raises((RuntimeError, BaseError)):- filter2d(image, kernel, "constant", padding="valid")- assert fft_conv(image, kernel, "constant", padding="valid").shape == (1, 1, 4, 4)+ # a kernel as large as the input gives one output pixel; one row or one column more raises+ kernel = _rand(1, 5, 6, device=device, dtype=dtype, seed=1)+ assert fn(image, kernel, "constant", padding="valid").shape == (1, 1, 1, 1)+ for kh, kw in [(6, 3), (7, 3), (3, 7), (5, 7), (6, 6)]:+ kernel = _rand(1, kh, kw, device=device, dtype=dtype, seed=1)+ with pytest.raises(BaseError if name == "fft_conv" else RuntimeError):+ fn(image, kernel, "constant", padding="valid")+ # 'same' pads first, so the same kernel is accepted+ assert fn(image, kernel, "constant", padding="same").shape == (1, 1, 5, 6)# (name, factory(device, dtype), shape) for non-square sizes, so every axis order is visible