π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(filters): differentiate an integer image in float32 in spatial_gradient and sobel (#5974)
XXXXXQ.113b2f793e1d
diff --git a/changelog.d/5974.fixed.md b/changelog.d/5974.fixed.mdnew file mode 100644index 000000000..6eb5981f7--- /dev/null+++ b/changelog.d/5974.fixed.md@@ -0,0 +1,3 @@+`spatial_gradient` and `sobel` now differentiate an integer or bool image in float32 instead of raising, matching+`spatial_gradient3d`. They cast the Sobel kernel to the input dtype before, so in `uint8`, `int16` or `int32` the+call failed, and with `normalized=False` an integer accumulation wrapped silently instead.diff --git a/docs/source/get-started/conventions.rst b/docs/source/get-started/conventions.rstindex 547a42e27..90a4668bd 100644--- a/docs/source/get-started/conventions.rst+++ b/docs/source/get-started/conventions.rst@@ -714,12 +714,14 @@ border names and the even-kernel anchor do not. :func:`~kornia.filters.filter2d`: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.guided_blur`, :func:`~kornia.filters.canny`,-:func:`~kornia.filters.unsharp_mask`, :func:`~kornia.filters.spatial_gradient3d` and their modules filter an integer or bool image in float32 and return+:func:`~kornia.filters.unsharp_mask`, :func:`~kornia.filters.spatial_gradient`,+:func:`~kornia.filters.spatial_gradient3d`, :func:`~kornia.filters.sobel` and their modules filter an integer or bool+image in float32 and returnfloat32 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 touint8; a floating image keeps its dtype. :func:`~kornia.filters.guided_blur` returns the promoted dtype of its-``guidance`` and ``input``, an integer one counting as float32. :func:`~kornia.filters.median_blur`,-:func:`~kornia.filters.spatial_gradient`, :func:`~kornia.filters.sobel` and the blur pools do not follow this yet: most of them raise on an integer image+``guidance`` and ``input``, an integer one counting as float32. :func:`~kornia.filters.median_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>`_).- :func:`~kornia.filters.filter2d`, :func:`~kornia.filters.filter3d` and :func:`~kornia.filters.fft_conv`diff --git a/kornia/filters/sobel.py b/kornia/filters/sobel.pyindex 7e2c4fba1..513f04379 100644--- a/kornia/filters/sobel.py+++ b/kornia/filters/sobel.py@@ -75,11 +75,13 @@ def spatial_gradient(input: torch.Tensor, mode: str = "sobel", order: int = 1, n"""KORNIA_CHECK_IS_TENSOR(input)KORNIA_CHECK_SHAPE(input, ["B", "C", "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)# The first-order Sobel kernels are fixed. Construct them directly instead# of allocating one kernel, transposing it, stacking both directions, and- # normalizing at runtime. Keep the generic construction for integer and- # complex inputs, whose division semantics are part of the public API.+ # normalizing at runtime. Keep the generic construction for complex inputs,+ # whose division semantics are part of the public API.if mode.lower() == "sobel" and order == 1 and input.is_floating_point():if normalized:kernel = torch.tensor(diff --git a/tests/filters/test_sobel.py b/tests/filters/test_sobel.pyindex 79e843776..d85a463d7 100644--- a/tests/filters/test_sobel.py+++ b/tests/filters/test_sobel.py@@ -761,6 +761,40 @@ class TestConventionsSpatialGradient(BaseTester):assert actual.dtype == torch.float32self.assert_close(actual, spatial_gradient3d(volume.float(), order=order), rtol=0, atol=0)+ @pytest.mark.parametrize("order", [1, 2])+ @pytest.mark.parametrize("int_dtype", [torch.uint8, torch.int16, torch.int32, torch.int64, torch.bool])+ def test_convention_spatial_gradient_integer_input_is_differentiated_in_float32_5155(+ self, int_dtype, order, device+ ):+ """#5155: an integer image 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)+ values = torch.randint(0, 256, (1, 2, 5, 6), generator=torch.Generator().manual_seed(0))+ image = values.to(device=device, dtype=int_dtype)+ actual = spatial_gradient(image, order=order)+ assert actual.dtype == torch.float32+ self.assert_close(actual, spatial_gradient(image.float(), order=order), rtol=0, atol=0)++ def test_convention_sobel_integer_input_is_filtered_in_float32_5155(self, device):+ """#5155: sobel inherits the float32 promotion from spatial_gradient."""+ self._require_replicate_padding(device, torch.float32)+ values = torch.randint(0, 256, (1, 2, 5, 6), generator=torch.Generator().manual_seed(0))+ image = values.to(device=device, dtype=torch.uint8)+ actual = sobel(image)+ assert actual.dtype == torch.float32+ self.assert_close(actual, sobel(image.float()), rtol=0, atol=0)++ @pytest.mark.parametrize("normalized", [True, False])+ def test_convention_spatial_gradient_integer_input_does_not_wrap_5155(self, normalized, device):+ """#5155: with ``normalized=False`` an int16 result used to wrap silently; a 0/32767 checkerboard is where+ that shows up as a 65536-sized error rather than as an exception."""+ self._require_replicate_padding(device, torch.float32)+ pattern = torch.tensor([[0, 32767, 0, 32767], [32767, 0, 32767, 0]] * 2, dtype=torch.int16)+ image = pattern[None, None].to(device=device)+ actual = spatial_gradient(image, normalized=normalized)+ assert actual.dtype == torch.float32+ self.assert_close(actual, spatial_gradient(image.float(), normalized=normalized), 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)