🐍 Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(filters): make get_gaussian_discrete_kernel1d return kernel_size taps and centre the even erf kernel (#5376)
区梓灏8491d6120042
diff --git a/changelog.d/5376.breaking.md b/changelog.d/5376.breaking.mdnew file mode 100644index 000000000..d04b4daab--- /dev/null+++ b/changelog.d/5376.breaking.md@@ -0,0 +1,8 @@+`get_gaussian_discrete_kernel1d` now returns `kernel_size` taps and rejects an even `kernel_size` with+`force_even=True` (#5158). Previously it returned `2 * (kernel_size // 2) + 1` taps and never fewer than 3:+`kernel_size=1` gave 3 taps and `kernel_size=4` with `force_even=True` gave 5. `kernel_size=1` is now the single tap+`[1.0]`, and an even size raises a `BaseError`, because the discrete Gaussian is defined at integer offsets from the+centre tap. `get_gaussian_erf_kernel1d` with `force_even=True` now centres an even kernel on the middle of the window,+`(kernel_size - 1) / 2`, as `get_gaussian_kernel1d` does; previously it was centred on tap `kernel_size // 2`, so+`(4, 1.0)` gave `[0.0654, 0.2608, 0.4131, 0.2608]` and now gives `[0.1424, 0.3576, 0.3576, 0.1424]`. Odd sizes above 1+are unchanged in both builders.diff --git a/kornia/filters/kernels.py b/kornia/filters/kernels.pyindex 075407bc5..fab618203 100644--- a/kornia/filters/kernels.py+++ b/kornia/filters/kernels.py@@ -210,7 +210,10 @@ def gaussian_discrete_erf(KORNIA_CHECK_SHAPE(sigma, ["B", "1"])batch_size = sigma.shape[0]- x = (torch.arange(window_size, device=sigma.device, dtype=sigma.dtype) - window_size // 2).expand(batch_size, -1)+ # Centre the window at (window_size - 1) / 2: the middle tap of an odd window, and halfway between the two+ # middle taps of an even one, as the sampled kernel in `gaussian` is.+ centre = (window_size - 1) / 2+ x = (torch.arange(window_size, device=sigma.device, dtype=sigma.dtype) - centre).expand(batch_size, -1)t = 0.70710678 / sigma.abs()# t = torch.tensor(2, device=sigma.device, dtype=sigma.dtype).sqrt() / (sigma.abs() * 2)@@ -337,7 +340,7 @@ def gaussian_discrete(Adapted from: https://github.com/Project-MONAI/MONAI/blob/master/monai/networks/layers/convutils.pyArgs:- window_size: the size which drives the filter amount.+ window_size: the size which drives the filter amount. It must be odd.sigma: gaussian standard deviation. 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.@@ -351,17 +354,19 @@ def gaussian_discrete(sigma = torch.tensor([[float(sigma)]], device=device, dtype=dtype)KORNIA_CHECK_SHAPE(sigma, ["B", "1"])+ # The discrete Gaussian is defined at the integer offsets of the taps from the centre tap, so there is no even+ # window: the window must be odd, and holds the offsets 0 .. window_size // 2 on either side of the centre.+ KORNIA_CHECK(window_size % 2 == 1, f"The discrete Gaussian kernel needs an odd window. Got {window_size}")output_dtype = sigma.dtypeif sigma.dtype in (torch.float16, torch.bfloat16):sigma = sigma.float()sigma2 = sigma * sigmatail = int(window_size // 2) + 1- bessels = [- _modified_bessel_0(sigma2, scaled=True),- _modified_bessel_1(sigma2, scaled=True),- *(_modified_bessel_i(k, sigma2, scaled=True, max_order=tail) for k in range(2, tail)),- ]+ bessels = [_modified_bessel_0(sigma2, scaled=True)]+ if tail > 1:+ bessels.append(_modified_bessel_1(sigma2, scaled=True))+ bessels.extend(_modified_bessel_i(k, sigma2, scaled=True, max_order=tail) for k in range(2, tail))# The exp(-sigma²) factor is already included in the scaled Bessel terms.out = torch.cat(bessels[:0:-1] + bessels, -1)@@ -802,20 +807,20 @@ def get_gaussian_discrete_kernel1d(kernel is Lindeberg's discrete Gaussian :math:`e^{-\sigma^2} I_{|n|}(\sigma^2)`, with :math:`I_n` themodified Bessel function of the first kind, normalized over the window: the smoothing kernel of discretescale space. A float16 or bfloat16 kernel is computed in float32 and rounded to its ``dtype``.- - Known defect: the tap count is not always ``kernel_size``. ``kernel_size=1`` gives 3 taps, and an even- size with ``force_even=True`` gives one more than asked- (`#5158 <https://github.com/kornia/kornia/issues/5158>`_).+ - The kernel has ``kernel_size`` taps, and ``kernel_size=1`` is the single tap ``[1.0]``. The discrete+ Gaussian is defined at integer offsets from the centre tap, so there is no even window: an even+ ``kernel_size`` raises with and without ``force_even``.Args: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.+ force_even: accepted for parity with the other Gaussian builders. The discrete Gaussian needs an odd+ ``kernel_size`` either way.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- ``kernel_size`` greater than 1 (see the known defects).+ 1D tensor with gaussian filter coefficients. Shape :math:`(B, \text{kernel_size})`Examples:>>> get_gaussian_discrete_kernel1d(3, 2.5)@@ -849,8 +854,8 @@ def get_gaussian_erf_kernel1d(kernel integrates the Gaussian over each pixel, :math:`\Phi((n + 1/2) / \sigma) - \Phi((n - 1/2) / \sigma)`with :math:`\Phi` the normal CDF, so it blurs more than the sampled kernel: for :math:`\sigma` ofabout 1 or more, on a window wide enough for the tails, its variance is :math:`\sigma^2 + 1/12`.- - Known defect: with ``force_even=True`` an even kernel is centred on tap ``kernel_size // 2`` instead of- the middle of the window, so it is not symmetric (`#5158 <https://github.com/kornia/kornia/issues/5158>`_).+ - With ``force_even=True`` an even kernel is symmetric about the middle of the window,+ ``(kernel_size - 1) / 2``, as the sampled kernel is.Args:kernel_size: filter size. It should be odd and positive.diff --git a/tests/filters/test_filters.py b/tests/filters/test_filters.pyindex dcee6257e..aa779801b 100644--- a/tests/filters/test_filters.py+++ b/tests/filters/test_filters.py@@ -1991,6 +1991,13 @@ def _grid(*sizes: int, centre: tuple[int, ...], device, dtype) -> tuple[torch.Tereturn tuple(g.to(device=device, dtype=dtype) for g in torch.meshgrid(*axes, indexing="ij"))+def _erf_kernel_reference(size: int, sigma: float) -> torch.Tensor:+ """The Gaussian integrated over each of ``size`` unit pixels centred on ``(size - 1) / 2``, in float64."""+ offsets = torch.arange(size, dtype=torch.float64) - (size - 1) / 2+ weights = torch.special.ndtr((offsets + 0.5) / sigma) - torch.special.ndtr((offsets - 0.5) / sigma)+ return (weights / weights.sum())[None]++def _correlate_at(kernel: torch.Tensor, field: torch.Tensor, centre: tuple[int, ...]) -> torch.Tensor:"""Correlate a stack of kernels ``(N, *k)`` with ``field`` at one point, as filter2d / filter3d do."""window = tuple(slice(c - k // 2, c + k // 2 + 1) for c, k in zip(centre, kernel.shape[1:]))@@ -2257,18 +2264,42 @@ class TestConventionsKernels(BaseTester):expected[3, 1, 2] = 1 / 2self.assert_close(kernel((90.0, 90.0, 0.0)), expected)- def test_wart_gaussian_discrete_kernel1d_tap_count_is_not_kernel_size_5158(self, device, dtype):- """get_gaussian_discrete_kernel1d gives 3 taps for kernel_size=1 and k + 1 for an even force_even k (#5158)."""- assert get_gaussian_discrete_kernel1d(1, 1.0, device=device, dtype=dtype).shape == (1, 3)- even = get_gaussian_discrete_kernel1d(4, 1.0, force_even=True, device=device, dtype=dtype)- assert even.shape == (1, 5)-- def test_wart_gaussian_erf_kernel1d_even_kernel_peaks_at_k_half_5158(self, device, dtype):- """get_gaussian_erf_kernel1d(force_even=True) samples about k // 2, so an even kernel is off-centre (#5158)."""- kernel = get_gaussian_erf_kernel1d(4, 1.0, force_even=True, device=device, dtype=dtype)[0]- # the sampled get_gaussian_kernel1d with the same arguments is symmetric about (k - 1) / 2 = 1.5- assert int(kernel.float().argmax()) == 2- assert kernel[2] > kernel[1]+ def test_convention_gaussian_discrete_kernel1d_has_kernel_size_taps_5158(self, device, dtype):+ """get_gaussian_discrete_kernel1d gives kernel_size taps, [1.0] for size 1, and rejects an even size (#5158)."""+ self.assert_close(+ get_gaussian_discrete_kernel1d(1, 1.0, device=device, dtype=dtype),+ torch.ones(1, 1, device=device, dtype=dtype),+ )+ sigma = torch.tensor([[0.0], [1.5], [20.0]], device=device, dtype=dtype)+ self.assert_close(get_gaussian_discrete_kernel1d(1, sigma), torch.ones(3, 1, device=device, dtype=dtype))+ for size in (3, 5, 7):+ assert get_gaussian_discrete_kernel1d(size, 1.0, device=device, dtype=dtype).shape == (1, size)+ # force_even changes nothing for an odd size and does not admit an even one: the discrete Gaussian is+ # defined at integer offsets from the centre tap, so there is no even window+ odd = get_gaussian_discrete_kernel1d(5, 1.0, device=device, dtype=dtype)+ assert torch.equal(get_gaussian_discrete_kernel1d(5, 1.0, force_even=True, device=device, dtype=dtype), odd)+ for size in (2, 4, 6):+ with pytest.raises(BaseError, match=f"needs an odd window. Got {size}"):+ get_gaussian_discrete_kernel1d(size, 1.0, force_even=True, device=device, dtype=dtype)++ def test_convention_gaussian_erf_kernel1d_even_kernel_is_symmetric_5158(self, device, dtype):+ """get_gaussian_erf_kernel1d(force_even=True) centres an even kernel on the middle of the window (#5158)."""+ for size in (2, 4, 6):+ kernel = get_gaussian_erf_kernel1d(size, 1.0, force_even=True, device=device, dtype=dtype)+ assert kernel.shape == (1, size)+ self.assert_close(kernel, kernel.flip(-1))+ # the two middle taps weigh the same and the most, as in the sampled kernel of the same size+ self.assert_close(kernel[0, size // 2 - 1], kernel[0, size // 2])+ assert int(kernel[0].float().argmax()) in (size // 2 - 1, size // 2)+ # the pixel-integrated Gaussian about (size - 1) / 2+ for size, sigma in ((4, 0.7), (6, 1.0), (8, 2.5)):+ kernel = get_gaussian_erf_kernel1d(size, sigma, force_even=True, device=device, dtype=dtype)+ self.assert_close(kernel, _erf_kernel_reference(size, sigma).to(device=device, dtype=dtype))+ # an odd size is centred on its middle tap as before+ self.assert_close(+ get_gaussian_erf_kernel1d(5, 1.5, device=device, dtype=dtype),+ _erf_kernel_reference(5, 1.5).to(device=device, dtype=dtype),+ )@pytest.mark.parametrize("sigma, expected",