Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(filters): accept integer sigma in 1-D Gaussian kernels (#5396)

Luozhang XU1e3053bbe2e8
diff --git a/changelog.d/5396.fixed.md b/changelog.d/5396.fixed.md
new file mode 100644
index 000000000..da3fdb6d7
--- /dev/null
+++ b/changelog.d/5396.fixed.md
@@ -0,0 +1,4 @@
+`get_gaussian_kernel1d`, `get_gaussian_erf_kernel1d`, `get_gaussian_discrete_kernel1d` and `gaussian` now accept a
+Python `int` `sigma`, and `gaussian` an `int` `mean`, and return the same kernel as for the equal `float`; they
+used to raise a `TypeCheckError` or an `AttributeError`. With no `dtype` the kernel has the default floating-point
+dtype, as for a `float` `sigma`.
diff --git a/kornia/filters/kernels.py b/kornia/filters/kernels.py
index 8f5de4fbc..8d31ffda2 100644
--- a/kornia/filters/kernels.py
+++ b/kornia/filters/kernels.py
@@ -127,10 +127,10 @@ def gaussian(
window_size: the size which drives the filter amount.
sigma: gaussian standard deviation. If a tensor, should be in a shape :math:`(B, 1)`.
mean: Mean of the Gaussian function (center); see the Convention block for an even
- ``window_size``. If not provided, it defaults to ``window_size // 2``. If a tensor,
- should be in a shape :math:`(B, 1)`.
- device: This value will be used if sigma is a float. Device desired to compute.
- dtype: This value will be used if sigma is a float. Dtype desired for compute.
+ ``window_size``. If not provided, it defaults to ``window_size // 2``. A Python ``int`` is
+ treated as its ``float``. If a tensor, should be in a shape :math:`(B, 1)`.
+ device: This value will be used if sigma is an int or float. Device desired to compute.
+ dtype: This value will be used if sigma is an int or float. Dtype desired for compute.
Returns:
A tensor with shape :math:`(B, \text{kernel_size})`, with Gaussian values.
@@ -142,16 +142,16 @@ def gaussian(
gradient with respect to ``sigma`` is zero there, matching the continuous limit.
"""
- if isinstance(sigma, float):
- sigma = torch.tensor([[sigma]], device=device, dtype=dtype)
+ if isinstance(sigma, (int, float)):
+ sigma = torch.tensor([[float(sigma)]], device=device, dtype=dtype)
KORNIA_CHECK_IS_TENSOR(sigma)
KORNIA_CHECK_SHAPE(sigma, ["B", "1"])
batch_size = sigma.shape[0]
mean = float(window_size // 2) if mean is None else mean
- if isinstance(mean, float):
- mean = torch.tensor([[mean]], device=sigma.device, dtype=sigma.dtype)
+ if isinstance(mean, (int, float)):
+ mean = torch.tensor([[float(mean)]], device=sigma.device, dtype=sigma.dtype)
KORNIA_CHECK_IS_TENSOR(mean)
KORNIA_CHECK_SHAPE(mean, ["B", "1"])
@@ -196,16 +196,16 @@ def gaussian_discrete_erf(
Args:
window_size: the size which drives the filter amount.
sigma: gaussian standard deviation. If a tensor, should be in a shape :math:`(B, 1)`
- device: This value will be used if sigma is a float. Device desired to compute.
- dtype: This value will be used if sigma is a float. Dtype desired for compute.
+ device: This value will be used if sigma is an int or float. Device desired to compute.
+ dtype: This value will be used if sigma is an int or float. Dtype desired for compute.
Returns:
A tensor withshape :math:`(B, \text{kernel_size})`, with discrete Gaussian values computed by approximation of
the error function.
"""
- if isinstance(sigma, float):
- sigma = torch.tensor([[sigma]], device=device, dtype=dtype)
+ if isinstance(sigma, (int, float)):
+ sigma = torch.tensor([[float(sigma)]], device=device, dtype=dtype)
KORNIA_CHECK_SHAPE(sigma, ["B", "1"])
batch_size = sigma.shape[0]
@@ -339,16 +339,16 @@ def gaussian_discrete(
Args:
window_size: the size which drives the filter amount.
sigma: gaussian standard deviation. If a tensor, should be in a shape :math:`(B, 1)`
- device: This value will be used if sigma is a float. Device desired to compute.
- dtype: This value will be used if sigma is a float. Dtype desired for compute.
+ device: This value will be used if sigma is an int or float. Device desired to compute.
+ dtype: This value will be used if sigma is an int or float. Dtype desired for compute.
Returns:
A tensor withshape :math:`(B, \text{kernel_size})`, with discrete Gaussian values computed by modified Bessel
function.
"""
- if isinstance(sigma, float):
- sigma = torch.tensor([[sigma]], device=device, dtype=dtype)
+ if isinstance(sigma, (int, float)):
+ sigma = torch.tensor([[float(sigma)]], device=device, dtype=dtype)
KORNIA_CHECK_SHAPE(sigma, ["B", "1"])
@@ -746,19 +746,17 @@ def get_gaussian_kernel1d(
- ``force_even=True`` also accepts an even ``kernel_size``, and in a floating ``dtype`` the kernel is then
symmetric about the middle of the window, ``(kernel_size - 1) / 2``.
- A tensor ``sigma`` of shape :math:`(B, 1)` gives one kernel per row.
- - Known defects:
-
- - a Python ``int`` ``sigma`` raises, while the 2d and 3d builders accept integers
- (`#5157 <https://github.com/kornia/kornia/issues/5157>`_).
- - an integer ``dtype`` truncates a fractional ``sigma``, and uint8 also wraps the negative offsets, so the
- taps before the centre are wrong (`#5155 <https://github.com/kornia/kornia/issues/5155>`_).
+ - A Python integer ``sigma`` is treated as its floating-point equivalent. With ``dtype=None``, both use
+ the default floating-point dtype.
+ - Known defect: an integer ``dtype`` truncates a fractional ``sigma``, and uint8 also wraps the negative
+ offsets, so the taps before the centre are wrong (`#5155 <https://github.com/kornia/kornia/issues/5155>`_).
Args:
kernel_size: filter size. It should be odd and positive.
sigma: gaussian standard deviation.
force_even: overrides requirement for odd kernel size.
- device: This value will be used if sigma is a float. Device desired to compute.
- dtype: This value will be used if sigma is a float. Dtype desired for compute.
+ device: This value will be used if sigma is an int or float. Device desired to compute.
+ dtype: This value will be used if sigma is an int or float. Dtype desired for compute.
Returns:
gaussian filter coefficients with shape :math:`(B, \text{kernel_size})`.
@@ -811,8 +809,8 @@ def get_gaussian_discrete_kernel1d(
kernel_size: filter size. It should be odd and positive.
sigma: gaussian standard deviation. If a tensor, should be in a shape :math:`(B, 1)`
force_even: overrides requirement for odd kernel size.
- device: This value will be used if sigma is a float. Device desired to compute.
- dtype: This value will be used if sigma is a float. Dtype desired for compute.
+ device: This value will be used if sigma is an int or float. Device desired to compute.
+ dtype: This value will be used if sigma is an int or float. Dtype desired for compute.
Returns:
1D tensor with gaussian filter coefficients. With shape :math:`(B, \text{kernel_size})` for an odd
@@ -857,8 +855,8 @@ def get_gaussian_erf_kernel1d(
kernel_size: filter size. It should be odd and positive.
sigma: gaussian standard deviation. If a tensor, should be in a shape :math:`(B, 1)`
force_even: overrides requirement for odd kernel size.
- device: This value will be used if sigma is a float. Device desired to compute.
- dtype: This value will be used if sigma is a float. Dtype desired for compute.
+ device: This value will be used if sigma is an int or float. Device desired to compute.
+ dtype: This value will be used if sigma is an int or float. Dtype desired for compute.
Returns:
1D tensor with gaussian filter coefficients. Shape :math:`(B, \text{kernel_size})`
diff --git a/tests/filters/test_filters.py b/tests/filters/test_filters.py
index 29525de09..a16874021 100644
--- a/tests/filters/test_filters.py
+++ b/tests/filters/test_filters.py
@@ -2223,11 +2223,12 @@ class TestConventionsKernels(BaseTester):
@pytest.mark.parametrize(
"builder", [get_gaussian_kernel1d, get_gaussian_erf_kernel1d, get_gaussian_discrete_kernel1d]
)
- def test_wart_gaussian_kernel1d_rejects_a_python_int_sigma_5157(self, builder, device, dtype):
- """The 1d Gaussian builders raise for sigma=1, where the 2d builder accepts sigma=(1, 1) (#5157)."""
- with pytest.raises((BaseError, AttributeError)):
- builder(5, 1, device=device, dtype=dtype)
- assert builder(5, 1.0, device=device, dtype=dtype).shape == (1, 5)
+ def test_convention_gaussian_kernel1d_accepts_a_python_int_sigma_5157(self, builder, device, dtype):
+ """The 1d Gaussian builders accept integer sigma just like the 2d builder (#5157)."""
+ actual = builder(5, 1, device=device, dtype=dtype)
+ expected = builder(5, 1.0, device=device, dtype=dtype)
+ assert actual.shape == (1, 5)
+ self.assert_close(actual, expected)
assert get_gaussian_kernel2d((5, 5), (1, 1), device=device, dtype=dtype).shape == (1, 5, 5)
@pytest.mark.parametrize("case", ["box_int32", "gaussian_uint8", "laplacian_uint8", "gradient3d_int32"])
diff --git a/tests/filters/test_gaussian.py b/tests/filters/test_gaussian.py
index f1c796625..ccbd8277d 100644
--- a/tests/filters/test_gaussian.py
+++ b/tests/filters/test_gaussian.py
@@ -36,6 +36,7 @@ from kornia.filters import (
get_gaussian_kernel2d,
get_gaussian_kernel3d,
)
+from kornia.filters.kernels import gaussian_discrete, gaussian_discrete_erf
from testing.base import BaseTester, assert_close
@@ -234,6 +235,69 @@ def test_get_gaussian_discrete_kernel1d_tensor(window_size, sigma, device, dtype
assert_close(actual.sum(), expected.sum())
+ "builder",
+ [
+ gaussian,
+ gaussian_discrete_erf,
+ gaussian_discrete,
+ get_gaussian_kernel1d,
+ get_gaussian_erf_kernel1d,
+ get_gaussian_discrete_kernel1d,
+ ],
+)
+class TestGaussianIntegerSigma(BaseTester):
+ @pytest.mark.parametrize("sigma", [1, 2])
+ def test_explicit_dtype(self, builder, sigma, device, dtype):
+ actual = builder(5, sigma, device=device, dtype=dtype)
+ expected = builder(5, float(sigma), device=device, dtype=dtype)
+
+ assert actual.shape == (1, 5)
+ assert actual.device == device
+ assert actual.dtype == dtype
+ self.assert_close(actual, expected)
+ self.assert_close(actual.sum(-1), torch.ones(1, device=device, dtype=dtype))
+
+ @pytest.mark.parametrize("sigma", [1, 2])
+ @pytest.mark.parametrize("default_dtype", [torch.float32, torch.float64])
+ def test_default_dtype(self, builder, sigma, default_dtype, device):
+ if device.type == "mps" and default_dtype == torch.float64:
+ pytest.skip("MPS does not support float64")
+ previous_dtype = torch.get_default_dtype()
+ try:
+ torch.set_default_dtype(default_dtype)
+ actual = builder(5, sigma, device=device)
+ expected = builder(5, float(sigma), device=device)
+ finally:
+ torch.set_default_dtype(previous_dtype)
+
+ # An int64 intermediate can silently truncate the discrete kernel to all zeros (#5157).
+ assert actual.shape == (1, 5)
+ assert actual.device == device
+ assert actual.dtype == default_dtype
+ self.assert_close(actual, expected)
+ self.assert_close(actual.sum(-1), torch.ones(1, device=device, dtype=default_dtype))
+
+ def test_tensor_sigma_gradcheck(self, builder, device):
+ sigma = torch.tensor([[1.5], [7.0]], device=device, dtype=torch.float64)
+ self.gradcheck(builder, (7, sigma))
+
+
+class TestGaussianIntegerMean(BaseTester):
+ def test_int_mean_matches_float_mean(self, device, dtype):
+ # gaussian() annotates mean as a float, like sigma: an int mean is the same Gaussian (#5157)
+ actual = gaussian(5, 1.5, mean=1, device=device, dtype=dtype)
+ expected = gaussian(5, 1.5, mean=1.0, device=device, dtype=dtype)
+ self.assert_close(actual, expected)
+
+ def test_int_sigma_keeps_a_fractional_mean(self, device):
+ # with dtype=None an int sigma must not build an integer tensor, which would truncate mean=1.5 to 1
+ actual = gaussian(4, 1, mean=1.5, device=device)
+ expected = gaussian(4, 1.0, mean=1.5, device=device)
+ assert actual.dtype == torch.get_default_dtype()
+ self.assert_close(actual, expected)
+
+
class TestGaussianDiscreteStability(BaseTester):
@pytest.mark.parametrize("window_size,sigma", [(19, 3.0), (43, 7.0), (121, 20.0), (5, 100.0)])
def test_finite_normalized(self, window_size, sigma, device, dtype):