Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(filters): validate positive sigma values in gaussian_blur2d (#3397)

Mekala jaya nanda prabhasd5e46fc428ad
diff --git a/kornia/filters/gaussian.py b/kornia/filters/gaussian.py
index 5e849a0c9..85789ff3a 100644
--- a/kornia/filters/gaussian.py
+++ b/kornia/filters/gaussian.py
@@ -21,11 +21,11 @@ from typing import Any
from kornia.core import ImageModule as Module
from kornia.core import Tensor, tensor
-from kornia.core.check import KORNIA_CHECK_IS_TENSOR
+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
from kornia.utils import deprecated
from .filter import filter2d, filter2d_separable
-from .kernels import _unpack_2d_ks, get_gaussian_kernel1d, get_gaussian_kernel2d
+from .kernels import _check_kernel_size, _unpack_2d_ks, get_gaussian_kernel1d, get_gaussian_kernel2d
def gaussian_blur2d(
@@ -44,31 +44,52 @@ def gaussian_blur2d(
Arguments:
input: the input tensor with shape :math:`(B,C,H,W)`.
- kernel_size: the size of the kernel.
- sigma: the standard deviation of the kernel.
+ kernel_size: the size of the kernel. Can be an integer or tuple of two integers (height, width).
+ sigma: the standard deviation of the kernel. Can be a tuple of two floats or a tensor 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'``.
- separable: run as composition of two 1d-convolutions.
+ separable: run as composition of two 1d-convolutions. Default: ``True``.
Returns:
the blurred tensor with shape :math:`(B, C, H, W)`.
+ Raises:
+ RuntimeError: if input is not a 4D tensor.
+ RuntimeError: if sigma values are not positive.
+ RuntimeError: if kernel_size is not a positive odd integer.
+
.. note::
See a working example `here <https://kornia.github.io/tutorials/nbs/gaussian_blur.html>`__.
Examples:
+ >>> import torch
>>> input = torch.rand(2, 4, 5, 5)
>>> output = gaussian_blur2d(input, (3, 3), (1.5, 1.5))
>>> output.shape
torch.Size([2, 4, 5, 5])
+ >>> # Single kernel size applies to both dimensions
+ >>> output = gaussian_blur2d(input, 3, (1.5, 1.5))
+ >>> output.shape
+ torch.Size([2, 4, 5, 5])
+
+ >>> # Using batched sigma (different sigma per batch element)
+ >>> sigma_batch = torch.tensor([[1.5, 1.5], [2.0, 2.0]])
+ >>> output = gaussian_blur2d(input[:2], (3, 3), sigma_batch)
+ >>> output.shape
+ torch.Size([2, 4, 5, 5])
+
+ >>> # Using tensor sigma
>>> output = gaussian_blur2d(input, (3, 3), torch.tensor([[1.5, 1.5]]))
>>> output.shape
torch.Size([2, 4, 5, 5])
"""
KORNIA_CHECK_IS_TENSOR(input)
+ KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])
+ _check_kernel_size(kernel_size, min_value=0)
if isinstance(sigma, tuple):
sigma = tensor([sigma], device=input.device, dtype=input.dtype)
@@ -76,6 +97,10 @@ def gaussian_blur2d(
KORNIA_CHECK_IS_TENSOR(sigma)
sigma = sigma.to(device=input.device, dtype=input.dtype)
+ # Validate sigma values are positive
+ KORNIA_CHECK_SHAPE(sigma, ["B", "2"])
+ KORNIA_CHECK(bool((sigma > 0).all()), f"sigma must be positive, got {sigma}")
+
if separable:
ky, kx = _unpack_2d_ks(kernel_size)
bs = sigma.shape[0]
diff --git a/tests/filters/test_gaussian.py b/tests/filters/test_gaussian.py
index 61ddc866d..82f0fe556 100644
--- a/tests/filters/test_gaussian.py
+++ b/tests/filters/test_gaussian.py
@@ -300,3 +300,167 @@ class TestGaussianBlur2d(BaseTester):
op_optimized = torch_optimizer(op)
self.assert_close(op(data), op_optimized(data))
+
+ @pytest.mark.parametrize("kernel_size", [3, (5, 5)])
+ @pytest.mark.parametrize("sigma", [(1.5, 2.1), (0.5, 0.5)])
+ def test_dynamo_functional(self, kernel_size, sigma, device, dtype, torch_optimizer):
+ """Test that functional gaussian_blur2d works with torch.compile / torch._dynamo."""
+ data = torch.ones(1, 3, 5, 5, device=device, dtype=dtype)
+
+ # Test functional form
+ # Test functional form
+ def op(x):
+ return gaussian_blur2d(x, kernel_size, sigma, "reflect", separable=True)
+
+ op_optimized = torch_optimizer(op)
+
+ self.assert_close(op(data), op_optimized(data))
+
+ def test_onnx_export(self, device, dtype):
+ """Test that GaussianBlur2d can be exported via torch.onnx.export."""
+ kernel_size = (3, 3)
+ sigma = (1.5, 1.5)
+
+ # Create model and sample input
+ model = GaussianBlur2d(kernel_size, sigma)
+ sample_input = torch.ones(1, 3, 8, 8, device=device, dtype=dtype)
+
+ # Test ONNX export - just ensure it doesn't error
+ # TODO: think of an absctraction
+ try:
+ import os
+ import tempfile
+
+ with tempfile.TemporaryDirectory() as tmpdir:
+ onnx_path = os.path.join(tmpdir, "gaussian_blur2d.onnx")
+ torch.onnx.export(
+ model,
+ sample_input,
+ onnx_path,
+ input_names=["input"],
+ output_names=["output"],
+ opset_version=17,
+ )
+ # Verify the file was created
+ assert os.path.exists(onnx_path)
+ except Exception as e:
+ pytest.skip(f"ONNX export not supported: {e}")
+
+ def test_sigma_negative_raises_exception(self, device, dtype):
+ """Test that negative sigma raises an exception."""
+ sample = torch.rand(1, 3, 5, 5, device=device, dtype=dtype)
+ with pytest.raises(Exception) as errinfo:
+ gaussian_blur2d(sample, (3, 3), (-1.5, 1.5))
+ assert "sigma must be positive" in str(errinfo.value)
+
+ def test_sigma_zero_raises_exception(self, device, dtype):
+ """Test that zero sigma raises an exception."""
+ sample = torch.rand(1, 3, 5, 5, device=device, dtype=dtype)
+ with pytest.raises(Exception) as errinfo:
+ gaussian_blur2d(sample, (3, 3), (0.0, 1.5))
+ assert "sigma must be positive" in str(errinfo.value)
+
+ def test_sigma_tensor_negative_raises_exception(self, device, dtype):
+ """Test that negative sigma tensor raises an exception."""
+ sample = torch.rand(2, 3, 5, 5, device=device, dtype=dtype)
+ sigma = torch.tensor([[-1.5, 1.5], [1.5, 1.5]], device=device, dtype=dtype)
+ with pytest.raises(Exception) as errinfo:
+ gaussian_blur2d(sample, (3, 3), sigma)
+ assert "sigma must be positive" in str(errinfo.value)
+
+ def test_kernel_size_even_raises_exception(self, device, dtype):
+ """Test that even kernel size raises an exception."""
+ sample = torch.rand(1, 3, 5, 5, device=device, dtype=dtype)
+ with pytest.raises(Exception) as errinfo:
+ gaussian_blur2d(sample, 4, (1.5, 1.5))
+ assert "Kernel size must be" in str(errinfo.value)
+
+ def test_kernel_size_zero_raises_exception(self, device, dtype):
+ """Test that zero kernel size raises an exception."""
+ sample = torch.rand(1, 3, 5, 5, device=device, dtype=dtype)
+ with pytest.raises(Exception) as errinfo:
+ gaussian_blur2d(sample, 0, (1.5, 1.5))
+ assert "Kernel size must be" in str(errinfo.value)
+
+ def test_very_small_sigma(self, device, dtype):
+ """Test with very small positive sigma values (should not raise)."""
+ sample = torch.rand(1, 3, 5, 5, device=device, dtype=dtype)
+ # Should not raise - any positive value is valid
+ output = gaussian_blur2d(sample, (3, 3), (0.01, 0.01))
+ assert output.shape == sample.shape
+
+ def test_very_large_sigma(self, device, dtype):
+ """Test with very large sigma values (should not raise)."""
+ sample = torch.rand(1, 3, 5, 5, device=device, dtype=dtype)
+ # Should not raise - large sigma just blurs more
+ output = gaussian_blur2d(sample, (3, 3), (100.0, 100.0))
+ assert output.shape == sample.shape
+
+ @pytest.mark.parametrize("sigma_value", [0.1, 1.0, 5.0, 10.0])
+ def test_sigma_range(self, sigma_value, device, dtype):
+ """Test various sigma values across a reasonable range."""
+ sample = torch.rand(1, 3, 8, 8, device=device, dtype=dtype)
+ output = gaussian_blur2d(sample, (5, 5), (sigma_value, sigma_value))
+ assert output.shape == sample.shape
+
+ def test_single_pixel_image(self, device, dtype):
+ """Test with minimal spatial dimensions (3x3 - smallest for 3x3 kernel)."""
+ sample = torch.rand(1, 3, 3, 3, device=device, dtype=dtype)
+ output = gaussian_blur2d(sample, 3, (1.5, 1.5))
+ assert output.shape == sample.shape
+
+ def test_large_batch_size(self, device, dtype):
+ """Test with large batch size."""
+ sample = torch.rand(32, 3, 8, 8, device=device, dtype=dtype)
+ output = gaussian_blur2d(sample, (3, 3), (1.5, 1.5))
+ assert output.shape == sample.shape
+
+ def test_many_channels(self, device, dtype):
+ """Test with many channels (e.g., video or multi-spectral)."""
+ sample = torch.rand(1, 64, 8, 8, device=device, dtype=dtype)
+ output = gaussian_blur2d(sample, (3, 3), (1.5, 1.5))
+ assert output.shape == sample.shape
+
+ def test_batched_sigma_mismatched_batch_size(self, device, dtype):
+ """Test that batched sigma uses first batch element when shapes don't match."""
+ # Note: The function broadcasts sigma, so mismatched batch size is allowed
+ # but only the first sigma in the batch is used for all input samples
+ sample = torch.rand(4, 3, 8, 8, device=device, dtype=dtype)
+ sigma = torch.tensor([[1.5, 1.5], [2.0, 2.0]], device=device, dtype=dtype)
+ # Should not raise - will use broadcasting behavior
+ output = gaussian_blur2d(sample, (3, 3), sigma)
+ assert output.shape == sample.shape
+
+ def test_all_border_types(self, device, dtype):
+ """Test that all supported border types work."""
+ sample = torch.rand(1, 3, 8, 8, device=device, dtype=dtype)
+ for border_type in ["constant", "reflect", "replicate", "circular"]:
+ output = gaussian_blur2d(sample, (3, 3), (1.5, 1.5), border_type=border_type)
+ assert output.shape == sample.shape
+
+ def test_separable_vs_non_separable_small_kernel(self, device, dtype):
+ """Test that separable and non-separable modes produce similar results."""
+ sample = torch.rand(1, 3, 16, 16, device=device, dtype=dtype)
+ sigma = (1.5, 1.5)
+ output_sep = gaussian_blur2d(sample, (3, 3), sigma, separable=True)
+ output_non_sep = gaussian_blur2d(sample, (3, 3), sigma, separable=False)
+ assert_close(output_sep, output_non_sep, atol=1e-4, rtol=1e-4)
+
+ def test_different_kernel_sizes(self, device, dtype):
+ """Test with various kernel sizes."""
+ sample = torch.rand(1, 3, 16, 16, device=device, dtype=dtype)
+ for ksize in [3, 5, 7, 11, (3, 5), (5, 7)]:
+ output = gaussian_blur2d(sample, ksize, (1.5, 1.5))
+ assert output.shape == sample.shape
+
+ def test_output_dtype_preserved(self, dtype, device):
+ """Test that output dtype matches input dtype."""
+ sample = torch.rand(1, 3, 8, 8, device=device, dtype=dtype)
+ output = gaussian_blur2d(sample, (3, 3), (1.5, 1.5))
+ assert output.dtype == dtype
+
+ def test_output_device_preserved(self, device, dtype):
+ """Test that output device matches input device."""
+ sample = torch.rand(1, 3, 8, 8, device=device, dtype=dtype)
+ output = gaussian_blur2d(sample, (3, 3), (1.5, 1.5))
+ assert output.device.type == sample.device.type
diff --git a/tests/filters/test_unsharp_mask.py b/tests/filters/test_unsharp_mask.py
index 1399f462c..c57db8278 100644
--- a/tests/filters/test_unsharp_mask.py
+++ b/tests/filters/test_unsharp_mask.py
@@ -26,7 +26,7 @@ from testing.base import BaseTester
class Testunsharp(BaseTester):
@pytest.mark.parametrize("shape", [(1, 4, 8, 15), (2, 3, 11, 7)])
@pytest.mark.parametrize("kernel_size", [3, (5, 3)])
- @pytest.mark.parametrize("sigma", [(3.0, 1.0), (0.5, -0.1)])
+ @pytest.mark.parametrize("sigma", [(3.0, 1.0), (0.5, 0.1)])
@pytest.mark.parametrize("params_as_tensor", [True, False])
def test_smoke(self, shape, kernel_size, sigma, params_as_tensor, device, dtype):
if params_as_tensor is True:
@@ -76,7 +76,7 @@ class Testunsharp(BaseTester):
img = torch.ones(1, 3, 5, 5, device=device, dtype=dtype)
self.assert_close(op(img, *params), op_module(img))
- @pytest.mark.parametrize("sigma", [(3.0, 1.0), (0.5, -0.1)])
+ @pytest.mark.parametrize("sigma", [(3.0, 1.0), (0.5, 0.1)])
@pytest.mark.parametrize("params_as_tensor", [True, False])
def test_dynamo(self, sigma, params_as_tensor, device, dtype, torch_optimizer):
if params_as_tensor is True: