π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(enhance)!: reject integer and boolean images in equalize, equalize3d and equalize_clahe (#6047)
Prateekshit Jaiswal913b0c707dc0
diff --git a/changelog.d/6047.breaking.md b/changelog.d/6047.breaking.mdnew file mode 100644index 000000000..7b1fbbf35--- /dev/null+++ b/changelog.d/6047.breaking.md@@ -0,0 +1 @@+`equalize`, `equalize3d` and `equalize_clahe` now raise `TypeCheckError` (a `TypeError`) for an integer or boolean image, with a message that names the dtype and the conversion `image.float() / 255`, as the `[0, 1]` adjustment functions do since #5983; the check is skipped under `disable_checks()`. Before, their `[0, 1]` range check let through an integer or boolean mask whose values are all 0 or 1: `equalize` and `equalize3d` returned the same result as for the floating-point mask and now raise, so convert such a mask with `.float()` first; `equalize_clahe` returned values that did not match the floating-point mask's (by up to almost 1.0 at `clip_limit=0`), and a boolean mask made it raise a raw `NotImplementedError`. A `uint8` image with values above 1 used to raise a `RuntimeError` and now raises the `TypeCheckError`, which `except RuntimeError` does not catch. Floating-point input is unchanged, and out-of-range floating-point input still raises the `RuntimeError` naming the range.diff --git a/docs/source/enhance.equalization.rst b/docs/source/enhance.equalization.rstindex 9be5bb76c..ea3aa5a12 100644--- a/docs/source/enhance.equalization.rst+++ b/docs/source/enhance.equalization.rst@@ -10,6 +10,10 @@ grid across the batch.Equalization------------+:func:`equalize`, :func:`equalize_clahe` and :func:`equalize3d` expect a floating-point image in ``[0, 1]``+and raise :exc:`~kornia.core.exceptions.TypeCheckError` (a :exc:`TypeError`) for an integer or boolean image,+as the ``[0, 1]`` adjustment functions do; convert 8-bit data with ``image.float() / 255`` first.+.. autofunction:: equalize.. autofunction:: equalize_clahe.. autofunction:: equalize3ddiff --git a/kornia/enhance/adjust.py b/kornia/enhance/adjust.pyindex 14553c36c..ef77aa501 100644--- a/kornia/enhance/adjust.py+++ b/kornia/enhance/adjust.py@@ -78,11 +78,12 @@ def _check_floating_image(image: torch.Tensor, op: str) -> None:"""Reject an integer image in an op that expects floating-point values in ``[0, 1]``.These ops clamp to ``[0, 1]``, scale by 255 or index a 256-entry table, so an 8-bit image would- otherwise come back saturated, wrapped or negative without an error (#5981). The check reads only- the dtype, so it stays ``torch.compile(fullgraph=True)``-safe, and ``disable_checks()`` skips it- like every kornia check. A non-tensor is left to the op's own type check. As in the core checks,- TorchScript compiles neither the checks flag nor the exception metadata, so a scripted op raises a- plain message instead.+ otherwise come back saturated, wrapped or negative without an error (#5981). The equalize family's+ ``[0, 1]`` range check let an integer 0/1 mask through, which ``equalize_clahe`` then mapped to wrong+ values. The check reads only the dtype, so it stays ``torch.compile(fullgraph=True)``-safe, and+ ``disable_checks()`` skips it like every kornia check. A non-tensor is left to the op's own type check.+ As in the core checks, TorchScript compiles neither the checks flag nor the exception metadata, so a+ scripted op raises a plain message instead."""if not isinstance(image, torch.Tensor) or image.is_floating_point():return@@ -1205,11 +1206,13 @@ def equalize(input: torch.Tensor) -> torch.Tensor:Equalized image torch.Tensor with shape :math:`(*, C, H, W)`... note::- The input is expected in :math:`[0, 1]`, and each channel is equalized from a 256-bin histogram.- Values the 256-bin lookup cannot index (outside roughly :math:`[0, 1]`) raise a ``RuntimeError``- naming the range. The check is ``torch._assert_async``, which has an MPS kernel from torch ``2.13``;- on an older MPS release the condition is read on the host instead, one device sync per call, and is- skipped there under ``torch.compile``.+ The input is expected as a floating-point image in :math:`[0, 1]`, and each channel is equalized from+ a 256-bin histogram. An integer or boolean image raises :exc:`~kornia.core.exceptions.TypeCheckError` (a+ :exc:`TypeError`); convert 8-bit data with ``image.float() / 255`` first. Values the 256-bin lookup+ cannot index (outside roughly :math:`[0, 1]`) raise a ``RuntimeError`` naming the range. The check is+ ``torch._assert_async``, which has an MPS kernel from torch ``2.13``; on an older MPS release the+ condition is read on the host instead, one device sync per call, and is skipped there under+ ``torch.compile``.Example:>>> x = torch.rand(1, 2, 3, 3)@@ -1217,6 +1220,7 @@ def equalize(input: torch.Tensor) -> torch.Tensor:torch.Size([1, 2, 3, 3])"""+ _check_floating_image(input, "equalize")# Scales each channel independently, batched over (B, C) in a single pass.return _scale_channel_batched(_prepare_intensity_input(input, 2)).reshape(input.shape)@@ -1239,16 +1243,18 @@ def equalize3d(input: torch.Tensor) -> torch.Tensor:Equalized volume with the same shape as the input... note::- The input is expected in :math:`[0, 1]`, and each channel's whole :math:`(D, H, W)` volume is- equalized from one 256-bin histogram. The lookup step is an integer division by 255, so a volume- with no more than 255 voxels per channel is returned unchanged up to floating-point roundoff; just- above that, whether it changes- depends on the values. Values the 256-bin lookup cannot index (outside roughly :math:`[0, 1]`)- raise a ``RuntimeError`` naming the range. The check is ``torch._assert_async``, which has an MPS- kernel from torch ``2.13``; on an older MPS release the condition is read on the host instead, one- device sync per call, and is skipped there under ``torch.compile``.+ The input is expected as a floating-point volume in :math:`[0, 1]`, and each channel's whole+ :math:`(D, H, W)` volume is equalized from one 256-bin histogram. The lookup step is an integer+ division by 255, so a volume with no more than 255 voxels per channel is returned unchanged up to+ floating-point roundoff; just above that, whether it changes depends on the values. An integer or+ boolean volume raises :exc:`~kornia.core.exceptions.TypeCheckError`, as for :func:`equalize`. Values+ the 256-bin lookup cannot index (outside roughly :math:`[0, 1]`) raise a ``RuntimeError`` naming the+ range. The check is ``torch._assert_async``, which has an MPS kernel from torch ``2.13``; on an older+ MPS release the condition is read on the host instead, one device sync per call, and is skipped there+ under ``torch.compile``."""+ _check_floating_image(input, "equalize3d")# Scales each channel independently (each (D, H, W) volume), batched over (B, C).return _scale_channel_batched(_prepare_intensity_input(input, 3)).reshape(input.shape)diff --git a/kornia/enhance/equalization.py b/kornia/enhance/equalization.pyindex 012f659ef..7dee647d0 100644--- a/kornia/enhance/equalization.py+++ b/kornia/enhance/equalization.py@@ -26,7 +26,7 @@ import torch.nn.functional as Ffrom kornia.core.utils import _normalize_to_float32_or_float64from kornia.image.utils import perform_keep_shape_image-from .adjust import _lookup_value_check+from .adjust import _check_floating_image, _lookup_value_checkfrom .histogram import histogram@@ -509,13 +509,16 @@ def equalize_clahe(torch.Size([2, 3, 10, 20]).. note::- The input is expected in :math:`[0, 1]`; each tile is equalized from a 256-bin lookup table.- Values the lookup cannot index (outside roughly :math:`[0, 1]`) raise a ``RuntimeError``- naming the range. The check is ``torch._assert_async``, which has an MPS kernel from torch- ``2.13``; on an older MPS release the condition is read on the host instead, one device sync per- call, and is skipped there under ``torch.compile``, as for :func:`kornia.enhance.equalize`.+ The input is expected as a floating-point image in :math:`[0, 1]`; each tile is equalized from a+ 256-bin lookup table. An integer or boolean image raises :exc:`~kornia.core.exceptions.TypeCheckError`+ (a :exc:`TypeError`); convert 8-bit data with ``image.float() / 255`` first, as for+ :func:`kornia.enhance.equalize`. Values the lookup cannot index (outside roughly :math:`[0, 1]`) raise+ a ``RuntimeError`` naming the range. The check is ``torch._assert_async``, which has an MPS kernel+ from torch ``2.13``; on an older MPS release the condition is read on the host instead, one device+ sync per call, and is skipped there under ``torch.compile``, as for :func:`kornia.enhance.equalize`."""+ _check_floating_image(input, "equalize_clahe")if not isinstance(clip_limit, float):raise TypeError(f"Input clip_limit type is not float. Got {type(clip_limit)}")diff --git a/tests/enhance/test_conventions_enhance.py b/tests/enhance/test_conventions_enhance.pyindex 372ca4dfb..4b6fec49e 100644--- a/tests/enhance/test_conventions_enhance.py+++ b/tests/enhance/test_conventions_enhance.py@@ -276,6 +276,11 @@ class TestEnhanceConventions(BaseTester):"jpeg_codec_differentiable": lambda x: kornia.enhance.jpeg_codec_differentiable(x, torch.full((x.shape[0],), 50.0, device=x.device)),+ # The equalize family's range check caught an 8-bit image only once a value passed 1, so an integer 0/1 mask+ # got through: equalize_clahe then returned wrong values for it and a boolean one raised a raw error.+ "equalize": kornia.enhance.equalize,+ "equalize3d": kornia.enhance.equalize3d,+ "equalize_clahe": kornia.enhance.equalize_clahe,}@pytest.mark.parametrize("op", sorted(_FLOAT_ONLY_OPS))@@ -290,6 +295,18 @@ class TestEnhanceConventions(BaseTester):assert "image.float() / 255" in str(exc_info.value)assert exc_info.value.actual_type == int_dtype+ # A mask with values in {0, 1} passes the equalize family's [0, 1] range check, so only the dtype check catches it.+ @pytest.mark.parametrize("op", ["equalize", "equalize3d", "equalize_clahe"])+ @pytest.mark.parametrize("mask_dtype", [torch.uint8, torch.int64, torch.bool], ids=["uint8", "int64", "bool"])+ def test_convention_equalize_rejects_an_integer_mask_5981(self, op, mask_dtype, device):+ shape = (2, 3, 4, 16, 16) if op == "equalize3d" else (2, 3, 16, 16)+ mask = (torch.rand(shape, device=device) > 0.5).to(mask_dtype)++ with pytest.raises(TypeCheckError, match=rf"^{op} expects a floating-point image in \[0, 1\]") as exc_info:+ self._FLOAT_ONLY_OPS[op](mask)++ assert exc_info.value.actual_type == mask_dtype+@pytest.mark.parametrize("op", sorted(_FLOAT_ONLY_OPS))def test_convention_floating_image_is_accepted_5981(self, op, device, dtype):# The conversion the message names, in any floating dtype, passes the check.