Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(filters): reject integer kernel dtypes that cannot hold the taps (#5759)

Aditya sridhar072b063690ae
diff --git a/changelog.d/5759.breaking.md b/changelog.d/5759.breaking.md
new file mode 100644
index 000000000..4cfc53f21
--- /dev/null
+++ b/changelog.d/5759.breaking.md
@@ -0,0 +1,23 @@
+The kernel builders raise for an integer or bool `dtype` that cannot hold their taps, where they used to return a
+wrong kernel. `get_box_kernel1d`, `get_box_kernel2d`, `get_gaussian_kernel1d`, `get_gaussian_erf_kernel1d`,
+`get_gaussian_discrete_kernel1d`, `get_gaussian_kernel2d`, `get_gaussian_kernel3d`, `gaussian`, `gaussian_discrete`,
+`gaussian_discrete_erf`, `get_diff_kernel3d`, `get_diff_kernel3d_2nd_order` and `get_spatial_gradient_kernel3d` have
+fractional taps and now raise for every integer and bool `dtype` (for the Gaussians, the `dtype` that goes with a
+Python `sigma`). They used to return:
+
+- for the box kernels, the kernel in that dtype with every tap truncated to 0 (all `True` in bool), except a size-1
+ box, which was all ones and now raises too;
+- for the sampled and erf Gaussians, a floating kernel for `sigma` truncated to an integer, so
+ `get_gaussian_kernel1d(5, 1.5, dtype=torch.int32)` was the `sigma=1` kernel and an integer `sigma` such as `2` gave
+ the right kernel (it now raises); in uint8 the offsets also wrapped, so the taps before the centre were wrong (0 for
+ a `sigma` below about 15);
+- for the discrete Gaussians, the kernel in that dtype with every tap truncated to 0;
+- for the 3-D difference kernels in a signed dtype, the kernel with the half and quarter taps truncated to 0, so the
+ first-order channels and the mixed second-order ones were all zero (bool gave `True`/`False` taps).
+
+A bool `dtype` already raised for the Gaussians, and uint8 already raised for the 3-D difference kernels.
+`get_laplacian_kernel1d`, `get_laplacian_kernel2d` and `laplacian_1d` keep accepting a signed integer `dtype` wide
+enough for their centre tap and raise for uint8, bool and a narrower one, where they used to wrap the centre (to 252
+for a uint8 size 5, to 88 for an int8 13x13) or make every tap `True`. `spatial_gradient3d` and `SpatialGradient3d`
+now return float32 for an int8, int16, int32 or int64 input with `order=2`; they used to return the input's dtype,
+with the mixed second derivatives zero.
diff --git a/changelog.d/5759.fixed.md b/changelog.d/5759.fixed.md
new file mode 100644
index 000000000..d1716c4a7
--- /dev/null
+++ b/changelog.d/5759.fixed.md
@@ -0,0 +1,8 @@
+`spatial_gradient3d` and `SpatialGradient3d` differentiate an integer or bool volume in float32 and give the result of
+the same volume in float32: uint8 and int8 differences no longer wrap, the mixed second derivatives of an integer
+volume are no longer zero, and a uint8 volume with `order=2` and a bool volume no longer raise.
+`gaussian`, `gaussian_discrete` and the kernel builders that call them (`get_gaussian_kernel1d`,
+`get_gaussian_kernel2d`, `get_gaussian_kernel3d`, `get_gaussian_discrete_kernel1d`) build the kernel of an integer
+`sigma` tensor in the default floating dtype, as `gaussian_discrete_erf` does. `gaussian_discrete` used to cast the
+taps to the sigma's dtype, which made them all 0, and `gaussian` wrapped the offsets of a uint8 sigma, which made the
+taps before the centre wrong.
diff --git a/docs/source/get-started/conventions.rst b/docs/source/get-started/conventions.rst
index bcc4c47a0..a9be1b7de 100644
--- a/docs/source/get-started/conventions.rst
+++ b/docs/source/get-started/conventions.rst
@@ -605,10 +605,11 @@ border names and the even-kernel anchor do not. :func:`~kornia.filters.filter2d`
:func:`~kornia.filters.filter2d_separable`, :func:`~kornia.filters.filter3d`, :func:`~kornia.filters.fft_conv`,
:func:`~kornia.filters.box_blur`, :func:`~kornia.filters.gaussian_blur2d`, :func:`~kornia.filters.laplacian`,
:func:`~kornia.filters.motion_blur`, :func:`~kornia.filters.bilateral_blur`,
-:func:`~kornia.filters.joint_bilateral_blur`, :func:`~kornia.filters.canny` and their modules filter an integer or
-bool image in float32 and return float32 on its own scale, neither rescaled to :math:`[0, 1]` nor rounded and clamped
-to its dtype, where ``cv2.filter2D(img, -1, k)``, ``cv2.GaussianBlur`` and ``cv2.blur`` return a uint8 image rounded
-and saturated to uint8; a floating image keeps its dtype. :func:`~kornia.filters.median_blur`,
+:func:`~kornia.filters.joint_bilateral_blur`, :func:`~kornia.filters.canny`,
+:func:`~kornia.filters.spatial_gradient3d` and their modules filter an integer or bool image in float32 and return
+float32 on its own scale, neither rescaled to :math:`[0, 1]` nor rounded and clamped to its dtype, where
+``cv2.filter2D(img, -1, k)``, ``cv2.GaussianBlur`` and ``cv2.blur`` return a uint8 image rounded and saturated to
+uint8; a floating image keeps its dtype. :func:`~kornia.filters.median_blur`,
:func:`~kornia.filters.unsharp_mask`, :func:`~kornia.filters.spatial_gradient`, :func:`~kornia.filters.sobel`,
:func:`~kornia.filters.guided_blur` and the blur pools do not follow this yet: most of them raise on an integer image
(`#5155 <https://github.com/kornia/kornia/issues/5155>`_).
@@ -680,6 +681,11 @@ The kernel builders against their references:
- :func:`~kornia.filters.get_laplacian_kernel2d` of size 3 is the 8-neighbour stencil and estimates :math:`3 \nabla^2`,
where ``scipy.ndimage.laplace`` and ``cv2.Laplacian(ksize=1)`` return :math:`\nabla^2`, ``cv2.Laplacian(ksize=3)``
:math:`4 \nabla^2` and ``skimage.filters.laplace`` :math:`-\nabla^2`.
+- A builder raises for an integer or bool ``dtype`` that cannot hold its taps instead of truncating or wrapping them.
+ The box, Gaussian and 3-D difference kernels have fractional taps, so they raise for every integer ``dtype``, as
+ ``cv2.getGaussianKernel`` accepts only ``CV_32F`` and ``CV_64F``. The Laplacian kernels accept a signed integer
+ ``dtype`` wide enough for their negative centre, and raise for uint8, bool and a narrower one
+ (`#5155 <https://github.com/kornia/kornia/issues/5155>`_).
The derivative filters apply those kernels at different scales, and :func:`~kornia.filters.canny` thresholds the raw
one:
diff --git a/kornia/filters/kernels.py b/kornia/filters/kernels.py
index 151eab78b..0a2caf537 100644
--- a/kornia/filters/kernels.py
+++ b/kornia/filters/kernels.py
@@ -50,6 +50,23 @@ def _check_laplacian_kernel_size(kernel_size: tuple[int, ...] | int) -> None:
)
+def _check_kernel_dtype(dtype: Optional[torch.dtype], name: str, taps: Optional[tuple[int, int]] = None) -> None:
+ # An integer or bool dtype truncates fractional taps and wraps the ones outside its range (#5155). ``taps`` is
+ # the (lowest, highest) tap of a kernel whose taps are all integers; without it the kernel has fractional taps.
+ if dtype is None or dtype.is_floating_point or dtype.is_complex:
+ return
+ KORNIA_CHECK(
+ taps is not None,
+ f"{name} has fractional taps, which an integer dtype cannot hold. Got dtype={dtype}; use a floating dtype.",
+ )
+ low, high = (0, 1) if dtype == torch.bool else (torch.iinfo(dtype).min, torch.iinfo(dtype).max)
+ KORNIA_CHECK(
+ low <= taps[0] and taps[1] <= high,
+ f"{name} has taps from {taps[0]} to {taps[1]}, which dtype={dtype} cannot hold. Use a signed integer dtype "
+ "wide enough for them, or a floating one.",
+ )
+
+
def _unpack_2d_ks(kernel_size: tuple[int, int] | int) -> tuple[int, int]:
if isinstance(kernel_size, int):
ky = kx = kernel_size
@@ -143,10 +160,14 @@ def gaussian(
"""
if isinstance(sigma, (int, float)):
+ _check_kernel_dtype(dtype, "A Gaussian kernel")
sigma = torch.tensor([[float(sigma)]], device=device, dtype=dtype)
KORNIA_CHECK_IS_TENSOR(sigma)
KORNIA_CHECK_SHAPE(sigma, ["B", "1"])
+ if not (sigma.dtype.is_floating_point or sigma.dtype.is_complex):
+ # as in `gaussian_discrete`: in a uint8 sigma's dtype the offsets below the mean would wrap (#5155)
+ sigma = sigma.to(torch.get_default_dtype())
batch_size = sigma.shape[0]
mean = float(window_size // 2) if mean is None else mean
@@ -205,6 +226,7 @@ def gaussian_discrete_erf(
"""
if isinstance(sigma, (int, float)):
+ _check_kernel_dtype(dtype, "A Gaussian kernel")
sigma = torch.tensor([[float(sigma)]], device=device, dtype=dtype)
KORNIA_CHECK_SHAPE(sigma, ["B", "1"])
@@ -351,6 +373,7 @@ def gaussian_discrete(
"""
if isinstance(sigma, (int, float)):
+ _check_kernel_dtype(dtype, "A Gaussian kernel")
sigma = torch.tensor([[float(sigma)]], device=device, dtype=dtype)
KORNIA_CHECK_SHAPE(sigma, ["B", "1"])
@@ -359,7 +382,12 @@ def gaussian_discrete(
KORNIA_CHECK(window_size % 2 == 1, f"The discrete Gaussian kernel needs an odd window. Got {window_size}")
output_dtype = sigma.dtype
- if sigma.dtype in (torch.float16, torch.bfloat16):
+ if not (sigma.dtype.is_floating_point or sigma.dtype.is_complex):
+ # An integer sigma tensor gives a floating kernel, as it does in `gaussian` and `gaussian_discrete_erf`;
+ # casting the normalized taps back to its dtype would truncate them all to 0 (#5155).
+ output_dtype = torch.get_default_dtype()
+ sigma = sigma.to(output_dtype)
+ elif sigma.dtype in (torch.float16, torch.bfloat16):
sigma = sigma.float()
sigma2 = sigma * sigma
tail = int(window_size // 2) + 1
@@ -393,6 +421,7 @@ def laplacian_1d(
"""
# TODO: add default dtype as None when kornia relies on torch > 1.12
+ _check_kernel_dtype(dtype, "The Laplacian kernel", (1 - window_size, 1))
filter_1d = torch.ones(window_size, device=device, dtype=dtype)
middle = window_size // 2
filter_1d[middle] = 1 - window_size
@@ -407,10 +436,8 @@ def get_box_kernel1d(
Convention:
- For a floating ``dtype`` every tap is ``1 / kernel_size``; an even ``kernel_size`` is accepted.
- The kernel is a contiguous tensor, so an in-place edit changes only the taps it addresses.
- - Known defects:
-
- - an integer ``dtype`` truncates ``1 / kernel_size``, so every tap is 0 once ``kernel_size`` is above 1
- (`#5155 <https://github.com/kornia/kornia/issues/5155>`_).
+ - An integer or bool ``dtype`` raises: it would truncate ``1 / kernel_size`` to 0
+ (`#5155 <https://github.com/kornia/kornia/issues/5155>`_).
Args:
kernel_size: the size of the kernel.
@@ -422,6 +449,7 @@ def get_box_kernel1d(
:math:`\frac{1}{\text{kernel\_size}}` for a floating ``dtype``.
"""
+ _check_kernel_dtype(dtype, "The box kernel")
return torch.full((1, kernel_size), 1.0 / kernel_size, device=device, dtype=dtype)
@@ -445,6 +473,7 @@ def get_box_kernel2d(
"""
ky, kx = _unpack_2d_ks(kernel_size)
+ _check_kernel_dtype(dtype, "The box kernel")
return torch.full((1, ky, kx), 1.0 / (kx * ky), device=device, dtype=dtype)
@@ -527,6 +556,7 @@ def get_diff_kernel_3x3(*, device: Optional[torch.device] = None, dtype: Optiona
def get_diff_kernel3d(device: Optional[torch.device] = None, dtype: Optional[torch.dtype] = None) -> torch.Tensor:
"""Return a first order derivative kernel of 3x3x3."""
+ _check_kernel_dtype(dtype, "The 3d first-order difference kernel")
kernel = torch.tensor(
[
[
@@ -555,6 +585,7 @@ def get_diff_kernel3d_2nd_order(
device: Optional[torch.device] = None, dtype: Optional[torch.dtype] = None
) -> torch.Tensor:
"""Return second order derivative kernels of 3x3x3 for ``(dxx, dyy, dzz, dxy, dyz, dxz)``."""
+ _check_kernel_dtype(dtype, "The 3d second-order difference kernel")
kernel = torch.tensor(
[
[
@@ -704,8 +735,8 @@ def get_spatial_gradient_kernel3d(
- In a floating ``dtype`` every channel is in derivative units: it answers 1 to a unit slope or a unit
second derivative, unlike the raw 2d stencils.
- ``mode`` is case-insensitive: ``'Diff'`` is ``'diff'``.
- - Known defect: a signed integer ``dtype`` truncates the half and quarter taps to 0, so the first-order
- channels and the mixed second-order ones are all zero
+ - An integer or bool ``dtype`` raises: it would truncate the half and quarter taps to 0, leaving the
+ first-order channels and the mixed second-order ones all zero
(`#5155 <https://github.com/kornia/kornia/issues/5155>`_).
Args:
@@ -754,8 +785,8 @@ def get_gaussian_kernel1d(
- A tensor ``sigma`` of shape :math:`(B, 1)` gives one kernel per row.
- 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>`_).
+ - An integer or bool ``dtype`` raises: the taps are fractional, and an integer ``dtype`` would also
+ truncate a fractional ``sigma`` (`#5155 <https://github.com/kornia/kornia/issues/5155>`_).
Args:
kernel_size: filter size. It should be odd and positive.
@@ -931,6 +962,7 @@ def get_gaussian_kernel2d(
"""
if isinstance(sigma, tuple):
+ _check_kernel_dtype(dtype, "A Gaussian kernel")
sigma = torch.tensor([sigma], device=device, dtype=dtype)
KORNIA_CHECK_IS_TENSOR(sigma)
@@ -996,6 +1028,7 @@ def get_gaussian_kernel3d(
"""
if isinstance(sigma, tuple):
+ _check_kernel_dtype(dtype, "A Gaussian kernel")
sigma = torch.tensor([sigma], device=device, dtype=dtype)
KORNIA_CHECK_IS_TENSOR(sigma)
@@ -1022,7 +1055,8 @@ def get_laplacian_kernel1d(
``[1, -2, 1]``; a larger size is not a wider second difference, and size 5 answers 5 to a unit second
derivative.
- The negative centre makes the response positive where the values curve upwards.
- - Known defect: uint8 wraps the negative centre, to 252 for size 5
+ - An integer or bool ``dtype`` that cannot hold ``1 - kernel_size`` raises, so uint8 and bool always do,
+ rather than wrap the centre (to 252 for size 5 in uint8)
(`#5155 <https://github.com/kornia/kornia/issues/5155>`_).
Args:
@@ -1100,6 +1134,7 @@ def get_laplacian_kernel2d(
ky, kx = _unpack_2d_ks(kernel_size)
_check_kernel_size((ky, kx))
_check_laplacian_kernel_size((ky, kx))
+ _check_kernel_dtype(dtype, "The Laplacian kernel", (1 - ky * kx, 1))
kernel = torch.ones((ky, kx), device=device, dtype=dtype)
mid_x = kx // 2
diff --git a/kornia/filters/sobel.py b/kornia/filters/sobel.py
index 768e41549..7e2c4fba1 100644
--- a/kornia/filters/sobel.py
+++ b/kornia/filters/sobel.py
@@ -25,6 +25,7 @@ from torch import nn
from kornia.core.check import KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
+from .filter import _to_floating
from .kernels import (
_normalize_kernel2d_2nd_order,
get_spatial_gradient_kernel2d,
@@ -123,6 +124,8 @@ def spatial_gradient3d(input: torch.Tensor, mode: str = "diff", order: int = 1)
new axis 2; see its Convention block for their order and units. There is no ``normalized`` argument: a
floating input gives derivative units.
- The border is always replicated, as in :func:`~kornia.filters.spatial_gradient`.
+ - An integer or bool input is differentiated in float32 and the output is float32, on the input's scale,
+ as :func:`~kornia.filters.filter3d` does (`#5155 <https://github.com/kornia/kornia/issues/5155>`_).
Args:
input: input features torch.Tensor with shape :math:`(B, C, D, H, W)`.
@@ -143,6 +146,8 @@ def spatial_gradient3d(input: torch.Tensor, mode: str = "diff", order: int = 1)
"""
KORNIA_CHECK_IS_TENSOR(input)
KORNIA_CHECK_SHAPE(input, ["B", "C", "D", "H", "W"])
+ # in its own dtype, uint8 wraps the differences and an integer kernel truncates the half and quarter taps (#5155)
+ input = _to_floating(input)
b, c, d, h, w = input.shape
dev = input.device
diff --git a/tests/filters/test_filters.py b/tests/filters/test_filters.py
index a92b81c3e..5d8019dd0 100644
--- a/tests/filters/test_filters.py
+++ b/tests/filters/test_filters.py
@@ -2463,21 +2463,89 @@ class TestConventionsKernels(BaseTester):
assert message in str(errinfo.value)
assert "Gotcha" not in str(errinfo.value)
- @pytest.mark.parametrize("case", ["box_int32", "gaussian_uint8", "laplacian_uint8", "gradient3d_int32"])
- def test_wart_kernel_builders_truncate_or_wrap_in_an_integer_dtype_5155(self, case, device):
- """An integer dtype truncates fractional taps to 0, and uint8 wraps the negative ones (#5155)."""
- if case == "box_int32":
- assert bool((get_box_kernel1d(3, device=device, dtype=torch.int32) == 0).all())
- elif case == "gaussian_uint8":
- # the offsets -2 and -1 wrap to 254 and 255, so the taps before the centre vanish
- kernel = get_gaussian_kernel1d(5, 1.5, device=device, dtype=torch.uint8)[0]
- assert kernel[:2].tolist() == [0, 0]
- assert bool((kernel[2:] > 0).all())
- elif case == "laplacian_uint8":
- assert get_laplacian_kernel1d(5, device=device, dtype=torch.uint8).tolist() == [1, 1, 252, 1, 1]
- else:
- # the first-order taps are +-0.5
- assert bool((get_spatial_gradient_kernel3d("diff", 1, device=device, dtype=torch.int32) == 0).all())
+ @pytest.mark.parametrize("int_dtype", [torch.uint8, torch.int8, torch.int32, torch.int64, torch.bool])
+ @pytest.mark.parametrize(
+ "build",
+ [
+ lambda device, dtype: get_box_kernel1d(3, device=device, dtype=dtype),
+ lambda device, dtype: get_box_kernel2d((3, 5), device=device, dtype=dtype),
+ lambda device, dtype: get_gaussian_kernel1d(5, 1.5, device=device, dtype=dtype),
+ lambda device, dtype: get_gaussian_kernel1d(5, 2, device=device, dtype=dtype),
+ lambda device, dtype: get_gaussian_erf_kernel1d(5, 1.5, device=device, dtype=dtype),
+ lambda device, dtype: get_gaussian_discrete_kernel1d(5, 1.5, device=device, dtype=dtype),
+ lambda device, dtype: get_gaussian_kernel2d((5, 3), (1.5, 1.0), device=device, dtype=dtype),
+ lambda device, dtype: get_gaussian_kernel3d((3, 3, 3), (1.5, 1.5, 1.5), device=device, dtype=dtype),
+ lambda device, dtype: get_spatial_gradient_kernel3d("diff", 1, device=device, dtype=dtype),
+ lambda device, dtype: get_spatial_gradient_kernel3d("diff", 2, device=device, dtype=dtype),
+ ],
+ ids=[
+ "box1d",
+ "box2d",
+ "gaussian1d",
+ "gaussian1d_int_sigma",
+ "erf1d",
+ "discrete1d",
+ "gaussian2d",
+ "gaussian3d",
+ "gradient3d_order1",
+ "gradient3d_order2",
+ ],
+ )
+ def test_convention_fractional_kernel_builders_reject_an_integer_dtype_5155(self, build, int_dtype, device):
+ """A kernel with fractional taps raises for an integer or bool dtype instead of truncating them (#5155)."""
+ with pytest.raises(BaseError, match="fractional taps"):
+ build(device, int_dtype)
+
+ @pytest.mark.parametrize("sigma_dtype", [torch.int64, torch.uint8])
+ @pytest.mark.parametrize(
+ "build", [get_gaussian_kernel1d, get_gaussian_erf_kernel1d, get_gaussian_discrete_kernel1d]
+ )
+ def test_convention_gaussian_of_an_integer_sigma_tensor_is_floating_5155(self, build, sigma_dtype, device):
+ """An integer sigma tensor gives the floating kernel of its float value, not taps truncated to 0 (#5155)."""
+ # in uint8 the offsets below the centre and 20 * 20 would wrap
+ actual = build(5, torch.tensor([[20]], device=device, dtype=sigma_dtype))
+ assert actual.dtype == torch.get_default_dtype()
+ self.assert_close(actual, build(5, torch.tensor([[20.0]], device=device)))
+
+ @pytest.mark.parametrize("build", [get_gaussian_kernel1d, get_gaussian_discrete_kernel1d])
+ def test_gaussian_of_a_complex_sigma_tensor_is_not_cast_to_real(self, build):
+ # only an integer sigma is promoted to floating point; a complex one must not lose its imaginary part
+ with pytest.raises(RuntimeError, match="not implemented for 'ComplexFloat'"):
+ build(5, torch.tensor([[1.0 + 1.0j]]))
+
+ @pytest.mark.parametrize(
+ ("kernel_size", "int_dtype"),
+ [
+ (3, torch.int8),
+ (5, torch.int16),
+ (129, torch.int8),
+ ((11, 11), torch.int8),
+ ((3, 43), torch.int8),
+ ((13, 13), torch.int16),
+ ((3, 5), torch.int32),
+ (7, torch.int64),
+ ],
+ )
+ def test_convention_laplacian_kernel_in_a_signed_integer_dtype_that_holds_it_is_exact_5155(
+ self, kernel_size, int_dtype, device
+ ):
+ """A signed integer dtype wide enough for the centre tap gives the floating kernel's integers (#5155)."""
+ build = get_laplacian_kernel1d if isinstance(kernel_size, int) else get_laplacian_kernel2d
+ actual = build(kernel_size, device=device, dtype=int_dtype)
+ assert actual.dtype == int_dtype
+ # float32 holds every tap here exactly, and unlike float64 it runs on MPS.
+ expected = build(kernel_size, device=device, dtype=torch.float32)
+ assert torch.equal(actual.to(torch.float32), expected)
+
+ @pytest.mark.parametrize(
+ ("kernel_size", "int_dtype"),
+ [(3, torch.uint8), (5, torch.bool), (131, torch.int8), ((3, 3), torch.uint8), ((13, 13), torch.int8)],
+ )
+ def test_convention_laplacian_kernel_rejects_a_dtype_that_cannot_hold_it_5155(self, kernel_size, int_dtype, device):
+ """uint8 and bool cannot hold the negative centre, nor int8 one below -128, so they raise (#5155)."""
+ build = get_laplacian_kernel1d if isinstance(kernel_size, int) else get_laplacian_kernel2d
+ with pytest.raises(BaseError, match="cannot hold"):
+ build(kernel_size, device=device, dtype=int_dtype)
@pytest.mark.parametrize("kernel_size", [5, 7])
def test_convention_motion_kernel2d_nearest_ties_ignore_a_full_turn_5181(self, kernel_size):
diff --git a/tests/filters/test_sobel.py b/tests/filters/test_sobel.py
index b79a65f8a..79e843776 100644
--- a/tests/filters/test_sobel.py
+++ b/tests/filters/test_sobel.py
@@ -747,6 +747,20 @@ class TestConventionsSpatialGradient(BaseTester):
with pytest.raises(NotImplementedError):
SpatialGradient3d(mode="sobel")
+ @pytest.mark.parametrize("order", [1, 2])
+ @pytest.mark.parametrize("int_dtype", [torch.uint8, torch.int16])
+ def test_convention_spatial_gradient3d_integer_input_is_differentiated_in_float32_5155(
+ self, int_dtype, order, device
+ ):
+ """#5155: an integer volume is differentiated in float32, so uint8 differences do not wrap and the mixed
+ second derivatives keep their quarter taps."""
+ self._require_replicate_padding(device, torch.float32, three_d=True)
+ values = torch.randint(0, 256, (1, 2, 5, 6, 7), generator=torch.Generator().manual_seed(0))
+ volume = values.to(device=device, dtype=int_dtype)
+ actual = spatial_gradient3d(volume, order=order)
+ assert actual.dtype == torch.float32
+ self.assert_close(actual, spatial_gradient3d(volume.float(), order=order), rtol=0, atol=0)
+
def test_convention_sobel_magnitude_of_normalized_gradient_eps_inside_root(self, device, dtype):
self._require_replicate_padding(device, dtype)
# sobel = sqrt(gx^2 + gy^2 + eps) of the normalized gradient: slope (3, 2) -> sqrt(13), not 8 * sqrt(13)