π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(filters): filter integer images in float32 (#5669)
Aditya17-bot3159d0eb140e
diff --git a/changelog.d/5669.breaking.md b/changelog.d/5669.breaking.mdnew file mode 100644index 000000000..df6357467--- /dev/null+++ b/changelog.d/5669.breaking.md@@ -0,0 +1,7 @@+For an integer or bool input, `filter2d`, `filter2d_separable`, `filter3d`, `gaussian_blur2d`, `box_blur`,+`laplacian`, `motion_blur`, `pyrdown` and `pyrup`, the modules built on them (`GaussianBlur2d`, `BoxBlur`, `Laplacian`,+`MotionBlur`, `PyrDown`, `PyrUp`), the `ScalePyramid` levels, every `build_pyramid` level after the input itself, and+the edge map of `canny` / `Canny` now return float32 on the input's scale, without rounding or clamping. They used to+return the input's integer dtype, holding zeros for a fractional kernel and wrapped sums for an integer one.+`joint_bilateral_blur` with an integer `input` and a float64 `guidance` now returns float32 instead of float64.+Floating inputs keep their dtype and values (#5155).diff --git a/changelog.d/5669.fixed.md b/changelog.d/5669.fixed.mdnew file mode 100644index 000000000..a2836bc21--- /dev/null+++ b/changelog.d/5669.fixed.md@@ -0,0 +1,8 @@+`filter2d`, `filter2d_separable`, `filter3d`, `fft_conv`, `gaussian_blur2d`, `box_blur`, `laplacian`,+`bilateral_blur`, `joint_bilateral_blur` and `canny` filter an integer or bool image in float32 with a floating+kernel, as the color conversions do (#4053). A uint8 image used to blur to zeros, because the fractional kernel taps+were cast to uint8; integer sums wrapped (a 3x3 box of ones over 100 gave 132); `normalized=True` raised a dtype+error; a `sigma` below 1 was truncated to 0 and rejected; `bilateral_blur` subtracted uint8 values and blended the+edges it should keep; and `canny` found no edge on a signed integer image and raised on uint8 or on a 3-channel+integer image (#5155). Through them, `motion_blur`, `pyrdown` and `ScalePyramid` no longer return zeros for an+integer image, and `resize` and `rescale` with `antialias=True` no longer reject it.diff --git a/docs/source/get-started/conventions.rst b/docs/source/get-started/conventions.rstindex 1883a91ac..7a15eabe1 100644--- a/docs/source/get-started/conventions.rst+++ b/docs/source/get-started/conventions.rst@@ -599,7 +599,17 @@ Filtering:doc:`kornia.filters </filters>` follows torch's vocabulary: its kernels are correlated by default, ``border_type``takes the :func:`torch.nn.functional.pad` mode names, and an even kernel is anchored where``F.conv2d(padding='same')`` anchors it. The correlation matches ``cv2.filter2D`` and ``scipy.ndimage.correlate``; the-border names and the even-kernel anchor do not.+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.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>`_).- :func:`~kornia.filters.filter2d`, :func:`~kornia.filters.filter3d` and :func:`~kornia.filters.fft_conv`**correlate** by default, as ``cv2.filter2D`` and ``scipy.ndimage.correlate`` do; ``behaviour='conv'`` flips the@@ -680,9 +690,8 @@ one:``scipy.ndimage.sobel(x, axis=-1, mode='nearest')`` equal channel 0 of ``spatial_gradient(x, normalized=False)``;OpenCV's default ``BORDER_REFLECT_101`` differs on the outermost rows and columns.``skimage.filters.sobel(x, mode='nearest')`` equals ``sqrt(2) * sobel(x, eps=0)``.-- For floating inputs, :func:`~kornia.filters.laplacian` is normalized by default too, but by the stencil's absolute- sum, 16 for size 3: ``laplacian(x, 3)`` estimates :math:`3 \nabla^2 / 16`, and ``normalized=False`` the- :math:`3 \nabla^2` above. See its Convention block for the integer-input defect.+- :func:`~kornia.filters.laplacian` is normalized by default too, but by the stencil's absolute sum, 16 for size 3:+ ``laplacian(x, 3)`` estimates :math:`3 \nabla^2 / 16`, and ``normalized=False`` the :math:`3 \nabla^2` above.- :func:`~kornia.filters.canny` compares its thresholds with the **unnormalized** Sobel magnitude of the blurredimage, about eight times what :func:`~kornia.filters.sobel` returns by default, up to the ``eps`` inside the squareroot. For a **single-channel grayscale** uint8 image ``img``, ``cv2.Canny(img, t1, t2, L2gradient=True)`` correspondsdiff --git a/kornia/filters/bilateral.py b/kornia/filters/bilateral.pyindex 8a64a1e8c..aa2e66ead 100644--- a/kornia/filters/bilateral.py+++ b/kornia/filters/bilateral.py@@ -26,6 +26,7 @@ from torch import nnfrom kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPEfrom kornia.core.utils import is_compiling+from .filter import _to_floatingfrom .kernels import _check_kernel_size, _unpack_2d_ks, get_gaussian_kernel2dfrom .median import _compute_zero_padding@@ -63,6 +64,11 @@ def _bilateral_blur("guidance and input should have the same batch size and spatial dimensions",)+ # integer values are differenced and weighted in float32: in their own dtype uint8 differences wrap (#5155)+ input = _to_floating(input)+ if guidance is not None and not guidance.is_floating_point():+ guidance = guidance.to(input.dtype)+if isinstance(sigma_color, torch.Tensor):KORNIA_CHECK_SHAPE(sigma_color, ["B"])_check_sigma_batch("sigma_color", sigma_color, input)@@ -141,10 +147,8 @@ def bilateral_blur(- The border modes are :func:`~kornia.filters.filter2d`'s, but only in lower case; see its Convention block.- A floating input keeps its dtype: a tensor ``sigma_color`` or ``sigma_space`` is cast to it and moved toits device.- - Known defects:-- - an integer input is differenced in its own dtype, so uint8 differences wrap and the filter blends- across edges it should keep (`#5155 <https://github.com/kornia/kornia/issues/5155>`_).+ - An integer or bool input is differenced and averaged in float32 and the output is float32, as in+ :func:`~kornia.filters.filter2d`, so uint8 differences do not wrap.Arguments:input: the input torch.Tensor with shape :math:`(B,C,H,W)`.@@ -201,9 +205,9 @@ def joint_bilateral_blur(``guidance``, and ``input`` is what gets averaged.- ``input`` comes first and ``guidance`` second, the opposite of :func:`~kornia.filters.guided_blur`.- ``guidance`` may have its own channel count; its batch size and :math:`(H, W)` must equal ``input``'s.- - A floating ``guidance`` is cast to the dtype of a floating ``input``, so the output keeps ``input``'s dtype.- - Known defects: those of :func:`~kornia.filters.bilateral_blur`, for an integer ``guidance``- (`#5155 <https://github.com/kornia/kornia/issues/5155>`_).+ - ``guidance`` is cast to the dtype of a floating ``input``, so the output keeps ``input``'s dtype. An integer+ ``input`` is filtered in float32, as by :func:`~kornia.filters.bilateral_blur`, and its ``guidance`` is+ cast to float32.Arguments:input: the input torch.Tensor with shape :math:`(B,C,H,W)`.diff --git a/kornia/filters/blur.py b/kornia/filters/blur.pyindex dcfcd82eb..8510bc0c1 100644--- a/kornia/filters/blur.py+++ b/kornia/filters/blur.py@@ -26,7 +26,7 @@ from torch import nnfrom kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPEfrom kornia.core.utils import is_autocast_enabled, is_compiling-from .filter import filter2d, filter2d_separable+from .filter import _to_floating, filter2d, filter2d_separablefrom .kernels import _unpack_2d_ks, get_box_kernel1d, get_box_kernel2d_HAS_MKLDNN = torch.backends.mkldnn.is_available()@@ -128,8 +128,8 @@ def box_blur(- ``kernel_size`` is ``(kH, kW)``. An even extent is anchored at ``(k - 1) // 2`` and the output keeps theinput's size; see the Convention block on :func:`~kornia.filters.filter2d` for the anchor and the bordermodes.- - Known defect: an integer input gets a kernel in its own dtype, whose ``1 / k`` taps truncate to 0, so on- the CPU a uint8 image comes back as zeros (`#5155 <https://github.com/kornia/kornia/issues/5155>`_).+ - An integer or bool input is blurred in float32 and the output is float32, as in+ :func:`~kornia.filters.filter2d`.Args:input: the image to blur with shape :math:`(B,C,H,W)`.@@ -155,6 +155,8 @@ def box_blur("""KORNIA_CHECK_IS_TENSOR(input)+ # the box kernel is built in the input's dtype, where an integer dtype truncates its 1 / k taps (#5155)+ input = _to_floating(input)if _box_blur_pool_eligible(input, kernel_size, separable):ky, kx = _unpack_2d_ks(kernel_size)diff --git a/kornia/filters/canny.py b/kornia/filters/canny.pyindex 4ca85499a..e8175ee5c 100644--- a/kornia/filters/canny.py+++ b/kornia/filters/canny.py@@ -31,6 +31,7 @@ from kornia.core.check import (KORNIA_CHECK_SHAPE,)+from .filter import _to_floatingfrom .gaussian import gaussian_blur2dfrom .kernels import get_hysteresis_kernelfrom .sobel import spatial_gradient@@ -72,7 +73,8 @@ def canny(Convention:- A 3-channel input is converted with :func:`~kornia.color.rgb_to_grayscale`, which reads channel 0 as- red. For a floating input both outputs are :math:`(B, 1, H, W)` in the input's dtype.+ red. Both outputs are :math:`(B, 1, H, W)`, in the input's dtype for a floating input and in float32 for+ an integer one, which is processed in float32 on its own scale.- The image is blurred with ``gaussian_blur2d(input, kernel_size, sigma)``; the Convention block on:func:`~kornia.filters.gaussian_blur2d` gives the order of both pairs, and ``kernel_size=1`` skips theblur. The magnitude is :math:`\sqrt{g_x^2 + g_y^2 + \epsilon}` of the **unnormalised** Sobel gradient@@ -94,10 +96,8 @@ def canny(to the input, and the edge map is not.- Hysteresis keeps a weak pixel connected to a strong one through any of its 8 neighbours, repeated untilnothing changes, and returns edges of 0 and 1.- - Known defect: an integer input is not converted to a floating dtype. With the default blur a 1-channel- signed integer image blurs to zeros and yields no edge; a uint8 image, a 3-channel integer image, or any- integer image where torch has no integer convolution raises- (`#5155 <https://github.com/kornia/kornia/issues/5155>`_).+ - An integer image is promoted to float32 before the grayscale conversion, so a 3-channel integer image+ is converted with the floating weights rather than rounded to an integer grey.Args:input: input image torch.Tensor with shape :math:`(B,C,H,W)`, with :math:`C` equal to 1, or to 3 for an RGB@@ -132,13 +132,17 @@ def canny(KORNIA_CHECK_IS_COLOR_OR_GRAY(input, f"canny expects 1 or 3 channels. Got: {input.shape[1]}")_check_thresholds(low_threshold, high_threshold)- device = input.device- dtype = input.dtype+ # an integer image is processed in float32, so both outputs are float32 (#5155); promoting before the grayscale+ # conversion keeps the fractional grey a uint8 conversion would round away+ input = _to_floating(input)# To Grayscaleif input.shape[1] == 3:input = rgb_to_grayscale(input)+ device = input.device+ dtype = input.dtype+# Gaussian filterblurred: torch.Tensor = gaussian_blur2d(input, kernel_size, sigma)diff --git a/kornia/filters/filter.py b/kornia/filters/filter.pyindex a131daa0f..5f5d89556 100644--- a/kornia/filters/filter.py+++ b/kornia/filters/filter.py@@ -51,6 +51,17 @@ def _compute_padding(kernel_size: list[int]) -> list[int]:return out_padding+def _to_floating(input: torch.Tensor) -> torch.Tensor:+ """Promote an integer or bool input to float32, the compute dtype for filtering.++ A kernel cast to an integer dtype truncates its fractional taps and wraps its sums, so an integer image is filtered+ in float32 and the result stays float32, as the color conversions do for integer images (#4053, #5155).+ """+ if input.is_floating_point() or input.is_complex():+ return input+ return input.to(torch.float32)++def _check_kernel_batch(input: torch.Tensor, kernel: torch.Tensor) -> None:"""Check that the kernel batch is 1 or the input batch."""# Format the sizes only on failure: an f-string evaluated on every call makes Dynamo specialize the batch size,@@ -95,13 +106,11 @@ def filter2d(keeps its sign.- ``border_type``, ``padding`` and ``behaviour`` are case-insensitive: ``'REFLECT'``, ``'SAME'`` and``'CONV'`` are ``'reflect'``, ``'same'`` and ``'conv'``.- - The kernel is cast to the input's dtype and device and stays differentiable; the output has the input's- dtype.- - Known defects:-- - an integer input casts the kernel to its dtype, so a fractional kernel truncates to 0: a uint8 image- filtered with a box kernel comes back as zeros, or the call raises where torch has no integer- convolution (`#5155 <https://github.com/kornia/kornia/issues/5155>`_).+ - For a floating input, the kernel is cast to the input's dtype and device and stays differentiable, and the+ output has the input's dtype.+ - An integer or bool input is filtered in float32 and the output is float32, on the input's scale: a uint8+ image is not rescaled to :math:`[0, 1]`, and the result is not rounded or clamped back to the integer+ range (`#5155 <https://github.com/kornia/kornia/issues/5155>`_).Args:input: the input tensor with shape of@@ -159,6 +168,8 @@ def filter2d(# the checks are case-insensitive, so dispatch on the lower-case spelling as wellborder_type, padding, behaviour = str(border_type).lower(), str(padding).lower(), str(behaviour).lower()+ input = _to_floating(input)+# prepare kernelb, c, h, w = input.shapeif behaviour == "conv":@@ -349,6 +360,8 @@ def filter3d(# the checks are case-insensitive, so dispatch on the lower-case spelling as wellborder_type, behaviour = str(border_type).lower(), str(behaviour).lower()+ input = _to_floating(input)+# prepare kernelb, c, d, h, w = input.shapeif behaviour == "conv":@@ -406,11 +419,8 @@ def fft_conv(``fft_conv`` returns the same result, to roundoff. A NaN or inf in a channel of the input makes thatchannel's whole output non-finite, where :func:`~kornia.filters.filter2d` keeps it to the pixels whosewindow reaches it.- - Known defects:-- - an integer input truncates a fractional kernel to 0, as in :func:`~kornia.filters.filter2d`, and the- result is in torch's default floating dtype (float32) instead of the input's- (`#5155 <https://github.com/kornia/kornia/issues/5155>`_).+ - An integer or bool input is filtered in float32 and the output is float32, as in+ :func:`~kornia.filters.filter2d`.Args:input: Input tensor of shape :math:`(B, C, H, W)`.@@ -485,6 +495,8 @@ def fft_conv(# the checks are case-insensitive, so dispatch on the lower-case spelling as wellborder_type, padding, behaviour = str(border_type).lower(), str(padding).lower(), str(behaviour).lower()+ input = _to_floating(input)+_, c, h, w = input.shapekh, kw = kernel.shape[-2:]diff --git a/kornia/filters/gaussian.py b/kornia/filters/gaussian.pyindex 62ee261f6..4ffd582e3 100644--- a/kornia/filters/gaussian.py+++ b/kornia/filters/gaussian.py@@ -24,7 +24,7 @@ from torch import nnfrom kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPEfrom kornia.core.utils import is_autocast_enabled, is_compiling-from .filter import filter2d, filter2d_separable+from .filter import _to_floating, filter2d, filter2d_separablefrom .kernels import _check_kernel_size, _unpack_2d_ks, get_gaussian_kernel1d, get_gaussian_kernel2d# This build capability is immutable; querying it inside forward breaks Dynamo@@ -101,9 +101,8 @@ def gaussian_blur2d(first, so ``sigma[0]`` blurs along ``H`` and ``sigma[1]`` along ``W``.:ref:`Filtering <filtering-conventions>` maps both pairs onto OpenCV and scipy.- The border modes are :func:`~kornia.filters.filter2d`'s; see its Convention block.- - Known defect: an integer input casts ``sigma`` and the kernel to its dtype, so on the CPU a uint8 image- comes back as zeros, and a ``sigma`` below 1 truncates to 0 and is rejected as not positive- (`#5155 <https://github.com/kornia/kornia/issues/5155>`_).+ - An integer or bool input is blurred in float32 and the output is float32, as in+ :func:`~kornia.filters.filter2d`; ``sigma`` is cast to float32 as well.Arguments:input: the input torch.Tensor with shape :math:`(B,C,H,W)`.@@ -156,6 +155,8 @@ def gaussian_blur2d(KORNIA_CHECK_IS_TENSOR(input)KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])_check_kernel_size(kernel_size, min_value=0)+ # promote before casting sigma and the kernel to the input's dtype, where an integer dtype truncates them (#5155)+ input = _to_floating(input)if isinstance(sigma, tuple):sigma = torch.tensor([sigma], device=input.device, dtype=input.dtype)diff --git a/kornia/filters/laplacian.py b/kornia/filters/laplacian.pyindex 735b22c68..2f781bfdd 100644--- a/kornia/filters/laplacian.py+++ b/kornia/filters/laplacian.py@@ -25,7 +25,7 @@ from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECKfrom kornia.core.utils import is_autocast_enabled, is_compilingfrom .blur import _HAS_MKLDNN, _ONEDNN_LARGE_INPUT, _needs_convolution_for_extreme_cpu_values-from .filter import filter2d+from .filter import _to_floating, filter2dfrom .kernels import (_check_kernel_size,_check_laplacian_kernel_size,@@ -76,10 +76,8 @@ def laplacian(:func:`~kornia.filters.spatial_gradient`, this does not give derivative units: size 3 returns:math:`3 \nabla^2 / 16`. :ref:`Filtering <filtering-conventions>` compares both scales with scipy andOpenCV.- - Known defect: an integer input casts the kernel to its dtype, as :func:`~kornia.filters.filter2d` does,- so the normalised kernel truncates to 0 and on the CPU the output is all zeros. For uint8, the negative- centre wraps before normalisation, making its absolute sum 256 for size 3, but every normalised tap still- truncates to 0 (`#5155 <https://github.com/kornia/kornia/issues/5155>`_).+ - An integer or bool input is filtered in float32 and the output is float32, as in+ :func:`~kornia.filters.filter2d`.Args:input: the input image tensor with shape :math:`(B, C, H, W)`.@@ -122,6 +120,8 @@ def laplacian(border_type = str(border_type).lower()ky, kx = _check_laplacian_size(kernel_size)+ # the kernel is built in the input's dtype, where an integer dtype truncates its normalized taps (#5155)+ input = _to_floating(input)if not _laplacian_slices_eligible(input) or _needs_convolution_for_extreme_cpu_values(input, ky * kx):kernel = get_laplacian_kernel2d((ky, kx), device=input.device, dtype=input.dtype)[None]diff --git a/tests/filters/test_bilateral.py b/tests/filters/test_bilateral.pyindex 8ae4a3976..e9d647551 100644--- a/tests/filters/test_bilateral.py+++ b/tests/filters/test_bilateral.py@@ -631,20 +631,20 @@ class TestConventionsBilateralBlur(BaseTester):assert out.shape == image.shapeself.assert_close(out, expected)- def test_wart_bilateral_blur_integer_image_wraps_its_differences_5155(self, device):- """bilateral_blur subtracts uint8 values in uint8, so 10 - 250 wraps and blends edges it should keep (#5155)."""- if device.type not in ("cpu", "mps"):- pytest.skip("#5155 is pinned on the CPU and MPS only")- # Columns alternate 10 and 250. A colour sigma of 50 keeps them apart, but the wrapped difference- # 10 - 250 = 16 (mod 256) makes the 10s look close to the 250s, which come back near 162.- # Snippet used to generate expected:- # s = torch.tensor([10, 250], dtype=torch.uint8).repeat(8, 5)[None, None]- # print(bilateral_blur(s, 3, 50.0, (1.0, 1.0))[0, 0, 3, :4]) # [10.0, 162.3, 10.0, 162.3]+ def test_convention_bilateral_blur_integer_image_keeps_its_edges_5155(self, device):+ """An integer image is differenced in float32, so 10 - 250 does not wrap and the stripes stay apart (#5155)."""+ # Columns alternate 10 and 250. A colour sigma of 50 keeps them apart; differenced in uint8, 10 - 250 wrapped+ # to 16 and the 250s came back near 162.stripes = torch.tensor([10, 250], device=device, dtype=torch.uint8).repeat(8, 5)[None, None]out = bilateral_blur(stripes, 3, 50.0, (1.0, 1.0))- assert out[0, 0, :, 1::2].max() < 200- # the same filter on the same values in floating point keeps the stripes- self.assert_close(bilateral_blur(stripes.float(), 3, 50.0, (1.0, 1.0)), stripes.float(), rtol=0.0, atol=0.01)+ assert out.dtype == torch.float32+ self.assert_close(out, bilateral_blur(stripes.float(), 3, 50.0, (1.0, 1.0)))+ self.assert_close(out, stripes.float(), rtol=0.0, atol=0.01)+ # an integer guidance is differenced in the input's dtype (float32 where MPS has no float64)+ wide = torch.float32 if device.type == "mps" else torch.float64+ guided = joint_bilateral_blur(stripes.to(wide), stripes, 3, 50.0, (1.0, 1.0))+ assert guided.dtype == wide+ self.assert_close(guided, stripes.to(wide), rtol=0.0, atol=0.01)def test_convention_bilateral_blur_wider_sigma_space_keeps_the_input_dtype_5521(self, device, dtype):"""A tensor sigma_space or guidance of a wider dtype is cast to the input's, as sigma_color is (#5521)."""diff --git a/tests/filters/test_blur.py b/tests/filters/test_blur.pyindex 6488b4609..fef34a34d 100644--- a/tests/filters/test_blur.py+++ b/tests/filters/test_blur.py@@ -397,12 +397,11 @@ class TestConventionsBoxBlur(BaseTester):assert lit[:, 1].unique().tolist() == colsself.assert_close(out[out != 0], torch.full((8,), 1 / 8, device=device, dtype=dtype))- def test_wart_box_blur_integer_image_blurs_to_zero_5155(self, device):- """box_blur builds its kernel in an integer input's dtype, so a uint8 image blurs to zero (#5155)."""- if device.type != "cpu":- pytest.skip("#5155 is pinned on the CPU; MPS raises for an integer convolution instead")+ def test_convention_box_blur_integer_image_is_blurred_in_float32_5155(self, device):+ """An integer image is blurred in float32 and returns float32: a constant uint8 image stays constant (#5155)."""image = torch.full((1, 1, 5, 7), 100, device=device, dtype=torch.uint8)for separable in (True, False):- assert box_blur(image, (3, 3), separable=separable).eq(0).all()- # the same blur of the same values in floating point keeps the constant image- self.assert_close(box_blur(image.float(), (3, 3)), image.float())+ out = box_blur(image, (3, 3), separable=separable)+ assert out.dtype == torch.float32+ self.assert_close(out, box_blur(image.float(), (3, 3), separable=separable))+ self.assert_close(out, image.float())diff --git a/tests/filters/test_canny.py b/tests/filters/test_canny.pyindex 4c456600e..828547126 100644--- a/tests/filters/test_canny.py+++ b/tests/filters/test_canny.py@@ -762,15 +762,27 @@ class TestConventionsCanny(BaseTester):with pytest.raises(ImageError):Canny()(torch.rand(1, channels, 12, 13, device=device, dtype=dtype))- def test_wart_canny_integer_input_finds_no_edge_5155(self, device, dtype):- """#5155: an integer image is not converted to a floating dtype, and the default blur truncates it to zeros."""- if device.type != "cpu":- pytest.skip("integer convolution raises on this device, so there is no truncated result to pin (#5155)")+ def test_convention_canny_integer_input_finds_the_float_edge_5155(self, device, dtype):+ """#5155: an integer image is blurred in float32, so it finds the edge of the same image in floating point."""self._require_padding(device, dtype)# the ramped step 0 | 6 | 10: in a floating dtype its blurred ridge, about 26, gives one edge pixel per row- img = self._ramped_step(10.0, device, torch.float64)+ img = self._ramped_step(10.0, device, torch.float32)_, edges = canny(img.to(dtype), 5.0, 10.0)assert edges[0, 0].nonzero()[:, 1].tolist() == [7] * 9for int_dtype in (torch.int16, torch.int32, torch.int64):_, edges = canny(img.to(int_dtype), 5.0, 10.0)- assert edges.count_nonzero().item() == 0+ assert edges[0, 0].nonzero()[:, 1].tolist() == [7] * 9++ def test_convention_canny_integer_rgb_is_promoted_before_grayscale_5155(self, device, dtype):+ """#5155: an integer RGB image is converted to grey in float32, so a faint red step is not rounded away."""+ self._require_padding(device, dtype)+ # a red-only step of 1 is a grey step of 0.299; a uint8 grey conversion rounds it to 0 and finds no edge+ rgb = torch.zeros(1, 3, 9, 14, device=device, dtype=torch.uint8)+ rgb[:, 0, :, 7:] = 1+ for int_dtype in (torch.uint8, torch.int16, torch.int32):+ magnitude, edges = canny(rgb.to(int_dtype))+ assert magnitude.dtype == edges.dtype == torch.float32+ expected_magnitude, expected_edges = canny(rgb.float())+ assert edges.count_nonzero().item() > 0+ self.assert_close(magnitude, expected_magnitude)+ self.assert_close(edges, expected_edges)diff --git a/tests/filters/test_filters.py b/tests/filters/test_filters.pyindex c9016808a..a92b81c3e 100644--- a/tests/filters/test_filters.py+++ b/tests/filters/test_filters.py@@ -1696,21 +1696,37 @@ class TestConventionsFilter2d(BaseTester):assert counter.frame_count == 1@pytest.mark.parametrize("name", ["filter2d", "filter2d_separable", "filter3d", "fft_conv"])- def test_wart_integer_input_truncates_a_fractional_kernel_to_zero_5155(self, name, device, dtype):- """An integer input casts the kernel to its dtype: a 1/9 box kernel turns a constant 100 image to 0 (#5155)."""- if name != "fft_conv" and device.type != "cpu":- pytest.skip("integer convolution raises on this device, so there is no truncated result to pin (#5155)")+ def test_convention_integer_input_is_filtered_in_float32_5155(self, name, device, dtype):+ """An integer input is filtered in float32 with a floating kernel and returns float32 (#5155)."""spatial = (3, 5, 7) if name == "filter3d" else (5, 7)image = torch.full((1, 1, *spatial), 100, dtype=torch.uint8, device=device)- if name == "filter2d_separable":- third = torch.full((1, 3), 1 / 3, device=device, dtype=dtype)- out = filter2d_separable(image, third, third, "constant")- elif name == "filter3d":- out = filter3d(image, torch.full((1, 3, 3, 3), 1 / 27, device=device, dtype=dtype), "constant")- else:- out = _FILTER2D_FNS[name](image, torch.full((1, 3, 3), 1 / 9, device=device, dtype=dtype), "constant")- # the interior of a box-filtered constant image is 100 in floating point- assert out[..., 2, 3].flatten()[0].item() == 0++ def run(x):+ if name == "filter2d_separable":+ third = torch.full((1, 3), 1 / 3, device=device, dtype=dtype)+ return filter2d_separable(x, third, third, "constant")+ if name == "filter3d":+ return filter3d(x, torch.full((1, 3, 3, 3), 1 / 27, device=device, dtype=dtype), "constant")+ return _FILTER2D_FNS[name](x, torch.full((1, 3, 3), 1 / 9, device=device, dtype=dtype), "constant")++ out = run(image)+ assert out.dtype == torch.float32+ self.assert_close(out, run(image.float()), rtol=1e-4, atol=1e-4)+ # the interior of a box-filtered constant image is 100, no longer truncated to 0; a half-precision kernel+ # rounds its 1 / 9 taps, which moves the sum by up to 0.4+ interior = out[0, 0, 1, 2, 3] if name == "filter3d" else out[0, 0, 2, 3]+ self.assert_close(interior, torch.tensor(100.0, device=device), rtol=0.0, atol=0.5)++ def test_convention_integer_sums_do_not_wrap_5155(self, device):+ """A box of ones over a uint8 100 sums to 900 in float32 instead of wrapping to 132 (#5155)."""+ image = torch.full((1, 1, 5, 7), 100, dtype=torch.uint8, device=device)+ out = filter2d(image, torch.ones(1, 3, 3))+ assert out.dtype == torch.float32+ assert out[0, 0, 2, 3].item() == 900+ out3d = filter3d(image[:, :, None].expand(-1, -1, 3, -1, -1), torch.ones(1, 3, 3, 3))+ assert out3d[0, 0, 1, 2, 3].item() == 2700+ # normalized=True used to raise a dtype error on an integer input+ self.assert_close(filter2d(image, torch.ones(1, 3, 3), normalized=True), image.float())@pytest.mark.parametrize("name", ["filter2d", "fft_conv"])def test_convention_padding_and_behaviour_are_case_insensitive_5156(self, name, device, dtype):diff --git a/tests/filters/test_gaussian.py b/tests/filters/test_gaussian.pyindex 9f71dd579..0e8b1d7ae 100644--- a/tests/filters/test_gaussian.py+++ b/tests/filters/test_gaussian.py@@ -856,18 +856,16 @@ class TestConventionsGaussianBlur(BaseTester):for separable in (True, False):self.assert_close(gaussian_blur2d(image, (5, 7), (1.0, 2.0), border_type, separable), expected)- def test_wart_gaussian_blur2d_integer_image_blurs_to_zero_5155(self, device):- """gaussian_blur2d casts sigma and the kernel to an integer dtype: a uint8 image blurs to zero (#5155)."""- if device.type != "cpu":- pytest.skip("#5155 is pinned on the CPU; MPS raises for an integer convolution instead")+ def test_convention_gaussian_blur2d_integer_image_is_blurred_in_float32_5155(self, device):+ """An integer image is blurred in float32 and returns float32: a constant uint8 image stays constant (#5155)."""image = torch.full((1, 1, 5, 7), 100, device=device, dtype=torch.uint8)for separable in (True, False):- assert gaussian_blur2d(image, (3, 3), (1.0, 1.0), separable=separable).eq(0).all()- # a sigma below 1 truncates to 0 in uint8 and is then rejected as not positive- with pytest.raises(BaseError):- gaussian_blur2d(image, (3, 3), (0.5, 0.5))- # the same blur of the same values in floating point keeps the constant image- self.assert_close(gaussian_blur2d(image.float(), (3, 3), (1.0, 1.0)), image.float())+ out = gaussian_blur2d(image, (3, 3), (1.0, 1.0), separable=separable)+ assert out.dtype == torch.float32+ self.assert_close(out, gaussian_blur2d(image.float(), (3, 3), (1.0, 1.0), separable=separable))+ self.assert_close(out, image.float())+ # a sigma below 1 is no longer truncated to 0 and rejected+ self.assert_close(gaussian_blur2d(image, (3, 3), (0.5, 0.5)), image.float())def test_convention_gaussian_blur2d_sigma_batch_is_one_or_the_input_batch_5169(self, device, dtype):"""gaussian_blur2d rejects a tensor sigma whose batch is neither 1 nor B, on both paths (#5169)."""diff --git a/tests/filters/test_laplacian.py b/tests/filters/test_laplacian.pyindex 98ae9b50f..f17d3024a 100644--- a/tests/filters/test_laplacian.py+++ b/tests/filters/test_laplacian.py@@ -334,22 +334,18 @@ class TestConventionsLaplacian(BaseTester):ramp = (torch.arange(6, device=device, dtype=dtype) ** 2).expand(1, 1, 5, 6)self.assert_close(laplacian(ramp, (1, 3))[0, 0, 2, 1:-1], torch.full((4,), 0.5, device=device, dtype=dtype))- def test_wart_laplacian_integer_input_returns_zeros_5155(self, device, dtype):- """#5155: the kernel takes the integer input's dtype, so the normalised taps truncate to 0."""- if device.type != "cpu":- pytest.skip("integer convolution raises on this device, so there is no truncated result to pin (#5155)")+ def test_convention_laplacian_integer_input_is_filtered_in_float32_5155(self, device, dtype):+ """#5155: an integer input is filtered in float32 with a floating kernel, so it gets the float response."""self._require_reflect_padding(device, dtype)img = torch.full((1, 1, 5, 7), 100, device=device, dtype=torch.uint8)img[0, 0, 2, 3] = 180- # in a float dtype: (8 * 100 - 8 * 180) / 16 = -40 at the bright pixel, (180 - 100) / 16 = 5 beside it- reference = laplacian(img.to(dtype), 3)[0, 0, [2, 1], [3, 3]]- self.assert_close(reference, torch.tensor([-40.0, 5.0], device=device, dtype=dtype))- # every tap of the normalised kernel is below 1 in magnitude (1/16 and -8/16 in int16; 1/256 and 248/256 in- # uint8, whose centre wraps) and truncates to 0, so the wrap does not decide the result+ # (8 * 100 - 8 * 180) / 16 = -40 at the bright pixel, (180 - 100) / 16 = 5 beside it+ expected = torch.tensor([-40.0, 5.0], device=device)for int_dtype in (torch.uint8, torch.int16):- assert laplacian(img.to(int_dtype), 3).count_nonzero().item() == 0- # unnormalised, the taps survive but the sum is uint8 arithmetic: -640 at the bright pixel reads -640 mod 256- assert laplacian(img, 3, normalized=False)[0, 0, 2, 3].item() == 128+ out = laplacian(img.to(int_dtype), 3)+ assert out.dtype == torch.float32+ self.assert_close(out[0, 0, [2, 1], [3, 3]], expected)+ self.assert_close(out, laplacian(img.float(), 3))def test_convention_laplacian_border_type_is_case_insensitive_5156(self, device, dtype):"""border_type is case-insensitive: 'REFLECT' and 'Reflect' pad as 'reflect' does, and so for every mode."""