π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(filters): filter an integer image in float32 in median_blur (#5989)
Dmytro Mishkina34c70b03a86
diff --git a/changelog.d/5989.fixed.md b/changelog.d/5989.fixed.mdnew file mode 100644index 000000000..2fc67cedc--- /dev/null+++ b/changelog.d/5989.fixed.md@@ -0,0 +1 @@+`median_blur` and `MedianBlur` filter an integer or bool image in float32 and return float32 on its own scale, like `box_blur`, instead of raising a dtype error.diff --git a/docs/source/get-started/conventions.rst b/docs/source/get-started/conventions.rstindex 9552f9d7f..b3c3c18a7 100644--- a/docs/source/get-started/conventions.rst+++ b/docs/source/get-started/conventions.rst@@ -713,15 +713,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_gradient`,+:func:`~kornia.filters.unsharp_mask`, :func:`~kornia.filters.median_blur`, :func:`~kornia.filters.spatial_gradient`,:func:`~kornia.filters.spatial_gradient3d`, :func:`~kornia.filters.sobel` and their modules filter an integer or boolimage 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`-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>`_).+``guidance`` and ``input``, an integer one counting as float32. The blur pools are network layers and expect a+floating input; an integer image is outside their contract.- :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 thediff --git a/kornia/filters/median.py b/kornia/filters/median.pyindex 5da8e0a04..3a5ff5e51 100644--- a/kornia/filters/median.py+++ b/kornia/filters/median.py@@ -24,6 +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, is_exporting+from .filter import _to_floatingfrom .kernels import _check_kernel_size, _unpack_2d_ks, get_binary_kernel2d_VALID_BORDERS = {"constant", "reflect", "replicate", "circular"}@@ -123,6 +124,9 @@ def median_blur(input: torch.Tensor, kernel_size: tuple[int, int] | int, border_- A window of more than one pixel that holds a NaN or an infinity returns NaN, even where the median of itsvalues is finite; a 1x1 window returns its pixel, infinity included.- The border modes are :func:`~kornia.filters.filter2d`'s; see its Convention block.+ - An integer or bool image is filtered in float32 and the result is float32 on its own scale, like+ :func:`~kornia.filters.box_blur`; a floating image keeps its dtype. A median selects one of its window's+ values, so the result equals that of ``input.float()`` exactly.Args:input: the input image with shape :math:`(B,C,H,W)`.@@ -155,6 +159,7 @@ def median_blur(input: torch.Tensor, kernel_size: tuple[int, int] | int, border_ky, kx = _unpack_2d_ks(kernel_size)_check_kernel_size((ky, kx), min_value=0)+ input = _to_floating(input)if input.shape[1] == 0:return input# ATen's per-pixel median reduction dominates inference for small windows.diff --git a/tests/filters/test_median.py b/tests/filters/test_median.pyindex d996082b9..e7d15f8f2 100644--- a/tests/filters/test_median.py+++ b/tests/filters/test_median.py@@ -438,3 +438,21 @@ class TestConventionsMedianBlur(BaseTester):out = median_blur(image, kernel_size).detach()assert torch.equal(out.isnan(), image.detach().isnan())self.assert_close(out.nan_to_num(), image.detach().nan_to_num())++ @pytest.mark.parametrize("border_type", ["reflect", "constant"])+ @pytest.mark.parametrize("input_dtype", [torch.uint8, torch.int16, torch.int32, torch.int64, torch.bool])+ def test_convention_median_blur_integer_image_is_filtered_in_float32_5155(self, input_dtype, border_type, device):+ """An integer or bool image is filtered in float32 and returns float32 on its own scale (#5155)."""+ # A median selects one of its window's values, so the result equals the float32 one exactly. On the CPU the+ # 3x3 window runs the selection network and the (3, 5) one the convolution + median path.+ generator = torch.Generator().manual_seed(0)+ low = -128 if input_dtype.is_signed else 0+ high = 2 if input_dtype == torch.bool else 256+ image = torch.randint(low, high, (2, 3, 9, 13), generator=generator).to(device, input_dtype)+ for kernel_size in (3, (3, 5)):+ expected = median_blur(image.float(), kernel_size, border_type)+ out = median_blur(image, kernel_size, border_type)+ assert out.dtype == torch.float32+ self.assert_close(out, expected, rtol=0, atol=0)+ self.assert_close(MedianBlur(kernel_size, border_type)(image), expected, rtol=0, atol=0)+ assert median_blur(image[:, :0], 3, border_type).dtype == torch.float32