Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(filters): check the sigma batch, sigma_color, motion kernel_size and edge_threshold at the blur entries (#5387)

εŒΊζ’“ηf3e8ad12c502
diff --git a/changelog.d/5387.breaking.md b/changelog.d/5387.breaking.md
new file mode 100644
index 000000000..6261948ff
--- /dev/null
+++ b/changelog.d/5387.breaking.md
@@ -0,0 +1,7 @@
+`bilateral_blur`, `joint_bilateral_blur`, `BilateralBlur` and `JointBilateralBlur` now raise a kornia error for a
+`sigma_color` that is not positive, and `edge_aware_blur_pool2d` and `EdgeAwareBlurPool2D` now require an
+`edge_threshold` greater than 1 (#5169). Previously a tensor `sigma_color` of zeros returned an all-NaN image and a
+negative `sigma_color` blurred exactly like its absolute value. An `edge_threshold` below 1 marked every pixel as an
+edge and returned the input unchanged, and exactly 1 counted any difference between pixels 4 apart as an edge. Under
+`torch.compile` a tensor `sigma_color` is not checked, like the tensor `sigma` of `gaussian_blur2d`. Positive
+`sigma_color` values and thresholds above 1, including the default 1.25, are unchanged.
diff --git a/changelog.d/5387.fixed.md b/changelog.d/5387.fixed.md
new file mode 100644
index 000000000..a73680c72
--- /dev/null
+++ b/changelog.d/5387.fixed.md
@@ -0,0 +1,6 @@
+`gaussian_blur2d` now rejects a tensor `sigma` whose batch is neither 1 nor the input batch at its entry with an error
+that names `sigma`, before any kernel is built (#5169). Previously the mismatch surfaced from the kernel batch check of
+`filter2d_separable`, or of `filter2d` with `separable=False`, with a message about the kernel. `bilateral_blur` and
+`joint_bilateral_blur` now raise a kornia error for a float `sigma_color` of 0 instead of Python's `ZeroDivisionError`,
+and `motion_blur`, `motion_blur3d`, `get_motion_kernel2d` and `get_motion_kernel3d` now raise a kornia error for a
+`kernel_size` that is not an `int` instead of a `TypeError`.
diff --git a/kornia/filters/bilateral.py b/kornia/filters/bilateral.py
index 2248fe4dd..527c1d911 100644
--- a/kornia/filters/bilateral.py
+++ b/kornia/filters/bilateral.py
@@ -24,6 +24,7 @@ import torch.nn.functional as F
from torch import nn
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
+from kornia.core.utils import is_compiling
from .kernels import _check_kernel_size, _unpack_2d_ks, get_gaussian_kernel2d
from .median import _compute_zero_padding
@@ -52,7 +53,12 @@ def _bilateral_blur(
if isinstance(sigma_color, torch.Tensor):
KORNIA_CHECK_SHAPE(sigma_color, ["B"])
+ # `bool()` on a tensor is untraceable by dynamo; skip the data-dependent check under compile.
+ if not is_compiling() and not bool((sigma_color > 0).all()):
+ KORNIA_CHECK(False, f"sigma_color must be positive. Got {sigma_color}")
sigma_color = sigma_color.to(device=input.device, dtype=input.dtype).view(-1, 1, 1, 1, 1, 1)
+ elif not sigma_color > 0:
+ KORNIA_CHECK(False, f"sigma_color must be positive. Got {sigma_color}")
ky, kx = _unpack_2d_ks(kernel_size)
_check_kernel_size((ky, kx))
@@ -105,7 +111,7 @@ def bilateral_blur(
input: the input torch.Tensor with shape :math:`(B,C,H,W)`.
kernel_size: the size of the kernel. Each entry must be a positive odd integer.
sigma_color: the standard deviation for intensity/color Gaussian kernel.
- Smaller values preserve more edges.
+ Smaller values preserve more edges. It must be positive.
sigma_space: the standard deviation for spatial Gaussian kernel.
This is similar to ``sigma`` in :func:`gaussian_blur2d()`.
border_type: the padding mode to be applied before convolving.
@@ -121,6 +127,7 @@ def bilateral_blur(
Raises:
BaseError: if an entry of ``kernel_size`` is even or not positive.
+ BaseError: if ``sigma_color`` is not positive.
Examples:
>>> input = torch.rand(2, 4, 5, 5)
@@ -154,7 +161,7 @@ def joint_bilateral_blur(
guidance: the guidance torch.Tensor with shape :math:`(B,C,H,W)`.
kernel_size: the size of the kernel. Each entry must be a positive odd integer.
sigma_color: the standard deviation for intensity/color Gaussian kernel.
- Smaller values preserve more edges.
+ Smaller values preserve more edges. It must be positive.
sigma_space: the standard deviation for spatial Gaussian kernel.
This is similar to ``sigma`` in :func:`gaussian_blur2d()`.
border_type: the padding mode to be applied before convolving.
@@ -169,6 +176,7 @@ def joint_bilateral_blur(
Raises:
BaseError: if an entry of ``kernel_size`` is even or not positive.
+ BaseError: if ``sigma_color`` is not positive.
Examples:
>>> input = torch.rand(2, 4, 5, 5)
@@ -220,7 +228,7 @@ class BilateralBlur(_BilateralBlur):
Arguments:
kernel_size: the size of the kernel. Each entry must be a positive odd integer.
sigma_color: the standard deviation for intensity/color Gaussian kernel.
- Smaller values preserve more edges.
+ Smaller values preserve more edges. It must be positive.
sigma_space: the standard deviation for spatial Gaussian kernel.
This is similar to ``sigma`` in :func:`gaussian_blur2d()`.
border_type: the padding mode to be applied before convolving.
@@ -240,6 +248,7 @@ class BilateralBlur(_BilateralBlur):
Raises:
BaseError: if an entry of ``kernel_size`` is even or not positive; raised from the constructor.
+ BaseError: if ``sigma_color`` is not positive; raised from ``forward``.
Examples:
>>> input = torch.rand(2, 4, 5, 5)
@@ -287,7 +296,7 @@ class JointBilateralBlur(_BilateralBlur):
Arguments:
kernel_size: the size of the kernel. Each entry must be a positive odd integer.
sigma_color: the standard deviation for intensity/color Gaussian kernel.
- Smaller values preserve more edges.
+ Smaller values preserve more edges. It must be positive.
sigma_space: the standard deviation for spatial Gaussian kernel.
This is similar to ``sigma`` in :func:`gaussian_blur2d()`.
border_type: the padding mode to be applied before convolving.
@@ -306,6 +315,7 @@ class JointBilateralBlur(_BilateralBlur):
Raises:
BaseError: if an entry of ``kernel_size`` is even or not positive; raised from the constructor.
+ BaseError: if ``sigma_color`` is not positive; raised from ``forward``.
Examples:
>>> input = torch.rand(2, 4, 5, 5)
diff --git a/kornia/filters/blur_pool.py b/kornia/filters/blur_pool.py
index c7f9ca283..da34d6af0 100644
--- a/kornia/filters/blur_pool.py
+++ b/kornia/filters/blur_pool.py
@@ -176,7 +176,8 @@ class EdgeAwareBlurPool2D(nn.Module):
Args:
kernel_size: The size of the Gaussian blur kernel.
- edge_threshold: The threshold for detecting edges. Default: 1.25.
+ edge_threshold: The intensity ratio between pixels 4 apart above which a pixel counts as an edge and keeps
+ its value. It must be greater than 1. Default: 1.25.
edge_dilation_kernel_size: The kernel size for dilating the edge map. It must be an odd positive integer.
Default: 3.
"""
@@ -361,7 +362,8 @@ def edge_aware_blur_pool2d(
Args:
input: the input image to blur with shape :math:`(B, C, H, W)`.
kernel_size: the kernel size for max pooling.
- edge_threshold: positive threshold for the edge decision rule; edge/non-edge.
+ edge_threshold: intensity ratio between pixels 4 apart above which a pixel counts as an edge and keeps its
+ value. It must be greater than 1.
edge_dilation_kernel_size: the kernel size for dilating the edges. It must be an odd positive integer.
epsilon: for numerical stability.
@@ -372,7 +374,7 @@ def edge_aware_blur_pool2d(
KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])
edge_dilation_kernel_size = operator.index(edge_dilation_kernel_size)
_check_kernel_size(edge_dilation_kernel_size)
- KORNIA_CHECK(edge_threshold > 0.0, f"edge threshold should be positive, but got '{edge_threshold}'")
+ KORNIA_CHECK(edge_threshold > 1.0, f"edge_threshold must be greater than 1. Got {edge_threshold}")
# Keep the edge comparison's fixed 2-pixel halo separate from the blur halo. The
# blur_pool2d convolution zero-pads by its kernel radius, so reflect-padding by at
diff --git a/kornia/filters/gaussian.py b/kornia/filters/gaussian.py
index 25c21c091..c20c0e168 100644
--- a/kornia/filters/gaussian.py
+++ b/kornia/filters/gaussian.py
@@ -100,7 +100,8 @@ def gaussian_blur2d(
input: the input torch.Tensor with shape :math:`(B,C,H,W)`.
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 torch.Tensor
- with shape :math:`(B, 2)`. Values must be positive.
+ with shape :math:`(1, 2)`, shared by the batch, or :math:`(B, 2)`, one row per sample.
+ Values must be positive.
border_type: the padding mode to be applied before convolving.
The expected modes are: ``'constant'``, ``'reflect'``,
``'replicate'`` or ``'circular'``, case-insensitive. Default: ``'reflect'``.
@@ -112,6 +113,7 @@ def gaussian_blur2d(
Raises:
RuntimeError: if input is not a 4D torch.Tensor.
RuntimeError: if sigma values are not positive.
+ BaseError: if the ``sigma`` batch is neither 1 nor the input batch.
RuntimeError: if kernel_size is not a positive odd integer.
.. note::
@@ -152,6 +154,13 @@ def gaussian_blur2d(
sigma = sigma.to(device=input.device, dtype=input.dtype)
KORNIA_CHECK_SHAPE(sigma, ["B", "2"])
+ # Format the sizes only on failure: an f-string evaluated on every call makes Dynamo specialize the batch size.
+ if sigma.shape[0] not in (1, input.shape[0]):
+ KORNIA_CHECK(
+ False,
+ "sigma must have a batch of 1 or the input batch. "
+ f"Got a sigma batch of {sigma.shape[0]} for an input batch of {input.shape[0]}",
+ )
# `bool()` on a tensor is untraceable by dynamo; skip the data-dependent check under compile.
if not is_compiling():
# Only interpolate `sigma` into the message when the check actually fails: a plain
diff --git a/kornia/filters/kernels_geometry.py b/kornia/filters/kernels_geometry.py
index a537a0f2a..3b217882f 100644
--- a/kornia/filters/kernels_geometry.py
+++ b/kornia/filters/kernels_geometry.py
@@ -82,6 +82,7 @@ def get_motion_kernel2d(
[angle if isinstance(angle, torch.Tensor) else None, direction if isinstance(direction, torch.Tensor) else None]
)
+ KORNIA_CHECK(isinstance(kernel_size, int), f"kernel_size must be an int. Got {type(kernel_size).__name__}")
# TODO: add support to kernel_size as tuple or integer
kernel_tuple = _unpack_2d_ks(kernel_size)
_check_kernel_size(kernel_size, 2)
@@ -189,6 +190,7 @@ def get_motion_kernel3d(
[angle if isinstance(angle, torch.Tensor) else None, direction if isinstance(direction, torch.Tensor) else None]
)
+ KORNIA_CHECK(isinstance(kernel_size, int), f"kernel_size must be an int. Got {type(kernel_size).__name__}")
# TODO: add support to kernel_size as tuple or integer
kernel_tuple = _unpack_3d_ks(kernel_size)
_check_kernel_size(kernel_size, 2)
diff --git a/tests/filters/test_bilateral.py b/tests/filters/test_bilateral.py
index 0f78fc87c..b0b52a2cd 100644
--- a/tests/filters/test_bilateral.py
+++ b/tests/filters/test_bilateral.py
@@ -81,6 +81,30 @@ class TestBilateralBlur(BaseTester):
with pytest.raises(BaseError, match="Kernel size must be an odd integer bigger than 0"):
call()
+ @pytest.mark.parametrize(
+ "sigma_color",
+ [0.0, 0, -0.1, [0.0, 0.0], [0.1, 0.0], [-0.1, 0.1]],
+ ids=["float_zero", "int_zero", "negative_float", "zero_tensor", "one_zero_row", "negative_row"],
+ )
+ def test_convention_sigma_color_must_be_positive_5169(self, sigma_color, device, dtype):
+ # The colour kernel divides by sigma_color squared, so a zero entry divides by zero and the sign of a negative
+ # one is lost: every entry must be positive. The check names the argument, runs before any padding and covers
+ # the joint filter and the modules.
+ from kornia.core.exceptions import BaseError
+
+ image = torch.rand(2, 3, 8, 9, device=device, dtype=dtype)
+ if isinstance(sigma_color, list):
+ sigma_color = torch.tensor(sigma_color, device=device, dtype=dtype)
+ calls = (
+ lambda: bilateral_blur(image, 3, sigma_color, (1.0, 1.0)),
+ lambda: joint_bilateral_blur(image, image, 3, sigma_color, (1.0, 1.0)),
+ lambda: BilateralBlur(3, sigma_color, (1.0, 1.0))(image),
+ lambda: JointBilateralBlur(3, sigma_color, (1.0, 1.0))(image, image),
+ )
+ for call in calls:
+ with pytest.raises(BaseError, match="sigma_color must be positive"):
+ call()
+
def test_noncontiguous(self, device, dtype):
batch_size = 3
inp = torch.rand(3, 5, 5, device=device, dtype=dtype).expand(batch_size, -1, -1, -1)
@@ -127,6 +151,13 @@ class TestBilateralBlur(BaseTester):
self.assert_close(op(data), op_optimized(data))
+ def test_dynamo_tensor_sigma_color_fullgraph_5169(self, device, dtype, torch_optimizer):
+ """The data-dependent sigma_color check is skipped under compile, so a tensor sigma_color stays one graph."""
+ data = torch.rand(2, 3, 8, 8, device=device, dtype=dtype)
+ op = BilateralBlur(3, torch.tensor([0.3, 0.7], device=device, dtype=dtype), (1.0, 1.0))
+ op_optimized = torch_optimizer(op, fullgraph=True)
+ self.assert_close(op_optimized(data), op(data))
+
def test_opencv_grayscale(self, device, dtype):
img = [[95, 130, 108, 228], [98, 142, 187, 166], [114, 166, 190, 141], [150, 83, 174, 216]]
img = torch.tensor(img, device=device, dtype=dtype).view(1, 1, 4, 4) / 255
diff --git a/tests/filters/test_blur_pool.py b/tests/filters/test_blur_pool.py
index 8f7de4171..1a47a631c 100644
--- a/tests/filters/test_blur_pool.py
+++ b/tests/filters/test_blur_pool.py
@@ -268,7 +268,19 @@ class TestEdgeAwareBlurPool(BaseTester):
data = torch.rand(1, 1, 3, 3)
with pytest.raises(BaseError) as errinfo:
edge_aware_blur_pool2d(data, 3, edge_threshold=-1)
- assert "edge threshold should be positive, but got" in str(errinfo.value)
+ assert "edge_threshold must be greater than 1. Got -1" in str(errinfo.value)
+
+ @pytest.mark.parametrize("edge_threshold", [0.5, 1, 1.0], ids=["half", "int_one", "float_one"])
+ def test_convention_edge_threshold_must_be_greater_than_1_5169(self, edge_threshold, device, dtype):
+ # The threshold is an intensity ratio compared through log2: below 1 every pixel is an edge and the blur never
+ # runs, and at 1 any difference between pixels 4 apart is an edge. The function and the module reject both,
+ # and the bound is strict.
+ data = torch.rand(1, 3, 8, 8, device=device, dtype=dtype)
+ with pytest.raises(BaseError, match=f"edge_threshold must be greater than 1. Got {edge_threshold}"):
+ edge_aware_blur_pool2d(data, 3, edge_threshold=edge_threshold)
+ with pytest.raises(BaseError, match=f"edge_threshold must be greater than 1. Got {edge_threshold}"):
+ EdgeAwareBlurPool2D(3, edge_threshold=edge_threshold)(data)
+ assert edge_aware_blur_pool2d(data, 3, edge_threshold=1.0001).shape == data.shape
@pytest.mark.parametrize("batch_size", [1, 2])
def test_noncontiguous(self, batch_size, device, dtype):
diff --git a/tests/filters/test_gaussian.py b/tests/filters/test_gaussian.py
index ccbd8277d..e60581143 100644
--- a/tests/filters/test_gaussian.py
+++ b/tests/filters/test_gaussian.py
@@ -496,6 +496,23 @@ class TestGaussianBlur2d(BaseTester):
self.assert_close(op(data), op_optimized(data))
+ @pytest.mark.parametrize("per_sample", [False, True], ids=["shared_sigma", "per_sample_sigma"])
+ def test_dynamo_sigma_batch_check_is_dynamic_5169(self, per_sample, device, dtype, torch_optimizer):
+ """The sigma batch check does not specialize the batch: one dynamic graph serves every batch (#5169)."""
+ from torch._dynamo.testing import CompileCounter
+
+ def op(x, sigma):
+ return gaussian_blur2d(x, (3, 3), sigma, "constant")
+
+ counter = CompileCounter()
+ compiled = torch_optimizer(op, backend=counter, fullgraph=True, dynamic=True)
+ # no batch equals another axis, including sigma's 2 columns, so duck sizing cannot tie the batch to it
+ for batch in (4, 5, 6):
+ image = torch.rand(batch, 3, 7, 9, device=device, dtype=dtype)
+ sigma = torch.rand(batch if per_sample else 1, 2, device=device, dtype=dtype) + 0.5
+ self.assert_close(compiled(image, sigma), op(image, sigma))
+ assert counter.frame_count == 1
+
@pytest.mark.device_agnostic
def test_onnx_export_legacy(self, dtype):
"""Test that GaussianBlur2d can be exported through the legacy ONNX exporter."""
@@ -622,21 +639,23 @@ class TestGaussianBlur2d(BaseTester):
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):
- """A sigma batch that is neither 1 nor the input batch raises through the kernel batch check (#5154).
+ @pytest.mark.parametrize("separable", [True, False])
+ def test_batched_sigma_mismatched_batch_size(self, separable, device, dtype):
+ """A sigma batch that is neither 1 nor the input batch raises at the entry with a message naming sigma (#5169).
- A check of the sigma shape at the entry of gaussian_blur2d is #5169.
+ The check runs before any kernel is built, so both the separable and the dense path raise the same error.
"""
sample = torch.rand(4, 3, 8, 8, device=device, dtype=dtype)
- # 2 rows divide the 4 samples and 3 do not: both raise the kornia error, not a torch reshape error
+ # 2 rows divide the 4 samples and 3 do not: both raise the sigma check, not the kernel batch check (#5154) or
+ # a torch reshape error
for rows in (2, 3):
sigma = torch.full((rows, 2), 1.5, device=device, dtype=dtype)
- with pytest.raises(BaseError, match=f"kernel batch of {rows} for an input batch of 4"):
- gaussian_blur2d(sample, (3, 3), sigma)
+ with pytest.raises(BaseError, match=f"sigma batch of {rows} for an input batch of 4"):
+ gaussian_blur2d(sample, (3, 3), sigma, separable=separable)
# one row for the whole batch and one row per sample run
for rows in (1, 4):
sigma = torch.full((rows, 2), 1.5, device=device, dtype=dtype)
- assert gaussian_blur2d(sample, (3, 3), sigma).shape == sample.shape
+ assert gaussian_blur2d(sample, (3, 3), sigma, separable=separable).shape == sample.shape
def test_all_border_types(self, device, dtype):
"""Test that all supported border types work."""
diff --git a/tests/filters/test_motion.py b/tests/filters/test_motion.py
index 5b742a824..ecd1dd38e 100644
--- a/tests/filters/test_motion.py
+++ b/tests/filters/test_motion.py
@@ -137,6 +137,22 @@ class TestMotionBlur(BaseTester):
with pytest.raises(Exception, match=r"direction and angle must have the same length. Got 2 and 3."):
get_motion_kernel2d(3, angle, direction)
+ @pytest.mark.parametrize("kernel_size", [(5, 5), [5, 5], 5.0], ids=["tuple", "list", "float"])
+ def test_convention_kernel_size_must_be_an_int_5169(self, kernel_size, device, dtype):
+ # The motion kernel is square, so kernel_size is a single int. Anything else raises a kornia error that names
+ # the argument, from the kernel builder, the function and the module alike.
+ image = torch.rand(1, 1, 8, 9, device=device, dtype=dtype)
+ angle = torch.tensor([30.0], device=device, dtype=dtype)
+ direction = torch.tensor([0.5], device=device, dtype=dtype)
+ calls = (
+ lambda: get_motion_kernel2d(kernel_size, angle, direction),
+ lambda: motion_blur(image, kernel_size, 30.0, 0.5),
+ lambda: MotionBlur(kernel_size, 30.0, 0.5)(image),
+ )
+ for call in calls:
+ with pytest.raises(BaseError, match=f"kernel_size must be an int. Got {type(kernel_size).__name__}"):
+ call()
+
def test_noncontiguous(self, device, dtype):
if not supports_reflect_padding(device, dtype):
pytest.skip("reflection_pad2d is unavailable for this device/dtype")
@@ -336,6 +352,22 @@ class TestMotionBlur3D(BaseTester):
assert actual.shape == (batch_size, ksize, ksize, ksize)
self.assert_close(actual.sum(), expected.sum())
+ @pytest.mark.parametrize("kernel_size", [(5, 5, 5), [5, 5, 5], 5.0], ids=["tuple", "list", "float"])
+ def test_convention_kernel_size_must_be_an_int_5169(self, kernel_size, device, dtype):
+ # The motion kernel is cubic, so kernel_size is a single int. Anything else raises a kornia error that names
+ # the argument, from the kernel builder, the function and the module alike.
+ volume = torch.rand(1, 1, 6, 8, 9, device=device, dtype=dtype)
+ angle = torch.tensor([[0.0, 90.0, 90.0]], device=device, dtype=dtype)
+ direction = torch.tensor([0.5], device=device, dtype=dtype)
+ calls = (
+ lambda: get_motion_kernel3d(kernel_size, angle, direction),
+ lambda: motion_blur3d(volume, kernel_size, (0.0, 90.0, 90.0), 0.5),
+ lambda: MotionBlur3D(kernel_size, (0.0, 90.0, 90.0), 0.5)(volume),
+ )
+ for call in calls:
+ with pytest.raises(BaseError, match=f"kernel_size must be an int. Got {type(kernel_size).__name__}"):
+ call()
+
def test_noncontiguous(self, device, dtype):
if not supports_replicate_padding_3d(device, dtype):
pytest.skip("replication_pad3d is unavailable for this device/dtype")