Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(filters): promote integer images before guided-blur products (#5890)

A Aswanth Raj4326a3f851bb
diff --git a/changelog.d/5890.fixed.md b/changelog.d/5890.fixed.md
new file mode 100644
index 000000000..a3bbb9e71
--- /dev/null
+++ b/changelog.d/5890.fixed.md
@@ -0,0 +1 @@
+`guided_blur` and `GuidedBlur` convert integer and bool images to float32 before covariance products, avoiding wrapped products and dtype errors while preserving the original image scale.
diff --git a/docs/source/get-started/conventions.rst b/docs/source/get-started/conventions.rst
index 32c4c5b56..4feca84a4 100644
--- a/docs/source/get-started/conventions.rst
+++ b/docs/source/get-started/conventions.rst
@@ -713,13 +713,14 @@ 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`,
+:func:`~kornia.filters.joint_bilateral_blur`, :func:`~kornia.filters.guided_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
+uint8; 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.unsharp_mask`, :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
(`#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/guided.py b/kornia/filters/guided.py
index 968dd0a3d..f6ff4f332 100644
--- a/kornia/filters/guided.py
+++ b/kornia/filters/guided.py
@@ -26,6 +26,7 @@ from torch.nn.functional import interpolate
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE, KORNIA_CHECK_TYPE
from .blur import box_blur
+from .filter import _to_floating
from .kernels import _unpack_2d_ks
@@ -194,6 +195,9 @@ def guided_blur(
- ``eps`` is added to the local variance of ``guidance``, so it is in squared guidance units: guidance and
input scaled by ``s``, filtered with ``eps * s**2``, give the result scaled by ``s``.
:ref:`Filtering <filtering-conventions>` maps the arguments onto OpenCV's ``guidedFilter``.
+ - An integer or bool ``guidance`` or ``input`` is converted to float32 before the covariance products, on its
+ own scale, and the result has the promoted dtype of the two: a float16 ``input`` with a uint8 ``guidance``
+ returns float32, where :func:`~kornia.filters.joint_bilateral_blur` keeps ``input``'s dtype.
Arguments:
guidance: the guidance torch.Tensor with shape :math:`(B,C_g,H,W)`.
@@ -243,6 +247,10 @@ def guided_blur(
"guidance and input should have the same batch size and spatial dimensions",
)
+ input_is_guidance = input is guidance
+ guidance = _to_floating(guidance)
+ input = guidance if input_is_guidance else _to_floating(input)
+
if guidance.shape[1] == 1:
return _guided_blur_grayscale_guidance(
guidance,
diff --git a/tests/filters/test_guided.py b/tests/filters/test_guided.py
index 8fb285a49..84669e84d 100644
--- a/tests/filters/test_guided.py
+++ b/tests/filters/test_guided.py
@@ -237,6 +237,61 @@ class TestGuidedBlur(BaseTester):
actual = guided_blur(guide, inp, kernel_size, 0.1)
assert actual.shape == shape
+ @pytest.mark.parametrize("input_dtype", [torch.uint8, torch.int16, torch.bool])
+ @pytest.mark.parametrize("guide_dim", [1, 3])
+ @pytest.mark.parametrize("self_guided", [False, True])
+ @pytest.mark.parametrize("subsample", [1, 2])
+ @pytest.mark.parametrize("separable", [False, True])
+ def test_integer_inputs_match_float32_5155(
+ self,
+ input_dtype: torch.dtype,
+ guide_dim: int,
+ self_guided: bool,
+ subsample: int,
+ separable: bool,
+ device: torch.device,
+ ) -> None:
+ # Integer products must be promoted before computing the covariance, on the original image scale.
+ generator = torch.Generator().manual_seed(0)
+ low = -128 if input_dtype == torch.int16 else 0
+ high = 2 if input_dtype == torch.bool else 256
+ guide = torch.randint(low, high, (2, guide_dim, 9, 13), generator=generator).to(device, input_dtype)
+ inp = (
+ guide
+ if self_guided
+ else torch.randint(low, high, (2, 2, 9, 13), generator=generator).to(device, input_dtype)
+ )
+ float_guide = guide.float()
+ float_input = float_guide if self_guided else inp.float()
+ op = GuidedBlur(5, 100.0, subsample=subsample, separable=separable)
+
+ expected = op(float_guide, float_input)
+ actual = guided_blur(guide, inp, 5, 100.0, subsample=subsample, separable=separable)
+
+ assert actual.shape == inp.shape
+ assert actual.dtype == torch.float32
+ assert actual.device == inp.device
+ assert actual.isfinite().all()
+ self.assert_close(actual, expected)
+ self.assert_close(op(guide, inp), expected)
+
+ @pytest.mark.parametrize("integer_guidance", [False, True])
+ @pytest.mark.parametrize("guide_dim", [1, 3])
+ @pytest.mark.parametrize("subsample", [1, 2])
+ def test_mixed_integer_float32_inputs_5155(
+ self, integer_guidance: bool, guide_dim: int, subsample: int, device: torch.device
+ ) -> None:
+ generator = torch.Generator().manual_seed(0)
+ guide = torch.randint(256, (2, guide_dim, 9, 13), generator=generator).to(device, torch.uint8)
+ inp = torch.randint(256, (2, 2, 9, 13), generator=generator).to(device, torch.uint8)
+ expected = guided_blur(guide.float(), inp.float(), 5, 100.0, subsample=subsample)
+ guide, inp = (guide, inp.float()) if integer_guidance else (guide.float(), inp)
+
+ actual = guided_blur(guide, inp, 5, 100.0, subsample=subsample)
+
+ assert actual.dtype == torch.float32
+ self.assert_close(actual, expected)
+
def test_exception(self):
from kornia.core.exceptions import BaseError, TypeCheckError
@@ -751,3 +806,27 @@ class TestConventionsGuidedBlur(BaseTester):
assert out.shape == image.shape
assert out.isfinite().all()
self.assert_close(GuidedBlur(5, 0.01, subsample=2)(guidance, image), out)
+
+ @pytest.mark.parametrize(
+ ("input_dtype", "guidance_dtype", "expected"),
+ [
+ (torch.float16, torch.uint8, torch.float32),
+ (torch.uint8, torch.float16, torch.float32),
+ (torch.float64, torch.uint8, torch.float64),
+ (torch.uint8, torch.uint8, torch.float32),
+ ],
+ )
+ def test_convention_guided_blur_mixed_dtypes_promote_5155(self, input_dtype, guidance_dtype, expected, device):
+ """An integer guidance or input counts as float32, and the result has the promoted dtype of the two."""
+ if expected == torch.float64 and device.type == "mps":
+ pytest.skip("MPS has no float64")
+ generator = torch.Generator().manual_seed(0)
+ guidance = torch.randint(256, (2, 1, 9, 13), generator=generator).to(guidance_dtype)
+ image = torch.randint(256, (2, 2, 9, 13), generator=generator).to(input_dtype)
+ # torch 2.5.1 has no CPU float16 reflection-padding kernel.
+ out = guided_blur(guidance.to(device), image.to(device), 5, 100.0, border_type="constant")
+ assert out.dtype == expected
+ reference = guided_blur(
+ guidance.double(), image.double(), 5, 100.0, border_type="constant"
+ ) # CPU: MPS has no float64
+ self.assert_close(out.cpu().double(), reference, rtol=1e-2, atol=1e-1)