Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(enhance): reject integer images in the [0, 1] intensity ops (#5983)

Saksham Sharma2a35f047f99b
diff --git a/changelog.d/5983.fixed.md b/changelog.d/5983.fixed.md
new file mode 100644
index 000000000..a1c35ff04
--- /dev/null
+++ b/changelog.d/5983.fixed.md
@@ -0,0 +1 @@
+`adjust_brightness`, `adjust_brightness_accumulative`, `adjust_contrast`, `adjust_contrast_with_mean_subtraction`, `adjust_saturation_with_gray_subtraction`, `adjust_gamma`, `adjust_sigmoid`, `adjust_log`, `posterize`, `solarize`, `sharpness`, `shift_rgb` and `jpeg_codec_differentiable` raise `TypeCheckError` (a `TypeError`) for an integer image, with a message that names the conversion (`image.float() / 255`). Previously eleven of them returned a saturated, wrapped or negative result for a `uint8` image without an error, and the other two raised an unrelated PyTorch error. Floating-point input is unchanged, and the check is skipped under `disable_checks()`.
diff --git a/docs/source/enhance.adjustment.rst b/docs/source/enhance.adjustment.rst
index 6dbe766ce..72790656d 100644
--- a/docs/source/enhance.adjustment.rst
+++ b/docs/source/enhance.adjustment.rst
@@ -11,6 +11,13 @@ count. :func:`sharpness` filters neighboring pixels and
:func:`adjust_contrast_with_mean_subtraction` subtracts an image mean, so their output also
depends on the rest of the image.
+The brightness, contrast, gamma, logarithmic and sigmoid adjustments,
+:func:`adjust_saturation_with_gray_subtraction`, :func:`posterize`, :func:`solarize`,
+:func:`sharpness` and :func:`shift_rgb` expect a floating-point image in ``[0, 1]`` and raise
+:exc:`~kornia.core.exceptions.TypeCheckError` (a :exc:`TypeError`) for an integer image; convert
+8-bit data with ``image.float() / 255`` first. :func:`adjust_hue`, :func:`adjust_saturation`,
+:func:`add_weighted` and :func:`invert` (with ``max_val``) also accept integer input.
+
Functions
---------
diff --git a/docs/source/enhance.codec.rst b/docs/source/enhance.codec.rst
index 0b46ca23e..baee52d57 100644
--- a/docs/source/enhance.codec.rst
+++ b/docs/source/enhance.codec.rst
@@ -5,7 +5,8 @@ Codec
A differentiable JPEG codec, useful to simulate compression artifacts inside a training loop.
It accepts RGB ``(*, 3, H, W)`` tensors in ``[0, 1]`` and a quality tensor of
-shape ``(1,)`` or ``(N,)``, one per flattened image.
+shape ``(1,)`` or ``(N,)``, one per flattened image. An integer image raises
+:exc:`~kornia.core.exceptions.TypeCheckError`; convert 8-bit data with ``image.float() / 255`` first.
.. autofunction:: jpeg_codec_differentiable
diff --git a/kornia/enhance/adjust.py b/kornia/enhance/adjust.py
index f0d317135..a5263a123 100644
--- a/kornia/enhance/adjust.py
+++ b/kornia/enhance/adjust.py
@@ -30,7 +30,9 @@ from kornia.core.check import (
KORNIA_CHECK,
KORNIA_CHECK_IS_COLOR_OR_GRAY,
KORNIA_CHECK_IS_TENSOR,
+ are_checks_enabled,
)
+from kornia.core.exceptions import TypeCheckError
from kornia.core.utils import _normalize_to_float32_or_float64, is_compiling
from kornia.image.utils import _to_bcdhw, _to_bchw
@@ -71,6 +73,33 @@ def _lookup_value_check(cond: torch.Tensor, msg: str) -> None:
torch._assert_async(cond, msg)
+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.
+ """
+ if not isinstance(image, torch.Tensor) or image.is_floating_point():
+ return
+ if not torch.jit.is_scripting(): # noqa: SIM102 - TorchScript only skips a bare is_scripting() guard
+ if not are_checks_enabled():
+ return
+ if torch.jit.is_scripting():
+ raise TypeCheckError(
+ op + " expects a floating-point image in [0, 1]; convert it first, e.g. image.float() / 255."
+ )
+ raise TypeCheckError(
+ f"{op} expects a floating-point image in [0, 1], got {image.dtype}. "
+ "Convert it first, for example image.float() / 255 for 8-bit data.",
+ actual_type=image.dtype,
+ expected_type=(torch.float16, torch.bfloat16, torch.float32, torch.float64),
+ )
+
+
def _make_factor_broadcastable(factor: torch.Tensor, image: torch.Tensor) -> torch.Tensor:
"""Right-pad ``factor`` with singleton dimensions so it broadcasts against ``image``.
@@ -155,6 +184,7 @@ def adjust_saturation_with_gray_subtraction(image: torch.Tensor, factor: Union[f
torch.Size([2, 3, 3, 3])
"""
+ _check_floating_image(image, "adjust_saturation_with_gray_subtraction")
KORNIA_CHECK_IS_TENSOR(image, "Expected shape (*, H, W)")
KORNIA_CHECK(isinstance(factor, (float, torch.Tensor)), "Factor should be float or torch.Tensor.")
KORNIA_CHECK_IS_COLOR_OR_GRAY(image, "Image should be an RGB or gray image")
@@ -379,6 +409,7 @@ def adjust_gamma(
torch.Size([2, 5, 3, 3])
"""
+ _check_floating_image(input, "adjust_gamma")
if not isinstance(input, torch.Tensor):
raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")
@@ -469,6 +500,7 @@ def adjust_contrast(image: torch.Tensor, factor: Union[float, torch.Tensor], cli
torch.Size([2, 5, 3, 3])
"""
+ _check_floating_image(image, "adjust_contrast")
KORNIA_CHECK_IS_TENSOR(image, "Expected shape (*, H, W)")
KORNIA_CHECK(isinstance(factor, (float, torch.Tensor)), "Factor should be float or torch.Tensor.")
@@ -526,6 +558,7 @@ def adjust_contrast_with_mean_subtraction(image: torch.Tensor, factor: Union[flo
torch.Size([2, 5, 3, 3])
"""
+ _check_floating_image(image, "adjust_contrast_with_mean_subtraction")
KORNIA_CHECK_IS_TENSOR(image, "Expected shape (*, H, W)")
KORNIA_CHECK(isinstance(factor, (float, torch.Tensor)), "Factor should be float or torch.Tensor.")
@@ -596,6 +629,7 @@ def adjust_brightness(
torch.Size([2, 5, 3, 3])
"""
+ _check_floating_image(image, "adjust_brightness")
KORNIA_CHECK_IS_TENSOR(image, "Expected shape (*, H, W)")
KORNIA_CHECK(isinstance(factor, (float, torch.Tensor)), "Factor should be float or torch.Tensor.")
@@ -653,6 +687,7 @@ def adjust_brightness_accumulative(
torch.Size([2, 5, 3, 3])
"""
+ _check_floating_image(image, "adjust_brightness_accumulative")
KORNIA_CHECK_IS_TENSOR(image, "Expected shape (*, H, W)")
KORNIA_CHECK(isinstance(factor, (float, torch.Tensor)), "Factor should be float or torch.Tensor.")
@@ -703,6 +738,7 @@ def adjust_sigmoid(image: torch.Tensor, cutoff: float = 0.5, gain: float = 10, i
[0.5000, 0.5000]]]])
"""
+ _check_floating_image(image, "adjust_sigmoid")
KORNIA_CHECK_IS_TENSOR(image, "Expected shape (*, H, W)")
return 1 - 1 / (1 + (gain * (cutoff - image)).exp()) if inv else 1 / (1 + (gain * (cutoff - image)).exp())
@@ -736,6 +772,7 @@ def adjust_log(image: torch.Tensor, gain: float = 1, inv: bool = False, clip_out
[0., 0.]]]])
"""
+ _check_floating_image(image, "adjust_log")
KORNIA_CHECK_IS_TENSOR(image, "Expected shape (*, H, W)")
img_adjust = (2**image - 1) * gain if inv else (1 + image).log2() * gain
@@ -829,6 +866,7 @@ def solarize(
torch.Size([2, 4, 3, 3])
"""
+ _check_floating_image(input, "solarize")
if not isinstance(input, torch.Tensor):
raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")
@@ -916,6 +954,7 @@ def posterize(input: torch.Tensor, bits: Union[int, torch.Tensor]) -> torch.Tens
torch.Size([2, 6, 3, 3])
"""
+ _check_floating_image(input, "posterize")
if not isinstance(input, torch.Tensor):
raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")
@@ -1014,6 +1053,7 @@ def sharpness(input: torch.Tensor, factor: Union[float, torch.Tensor]) -> torch.
torch.Size([1, 1, 5, 5])
"""
+ _check_floating_image(input, "sharpness")
batched_input = _prepare_intensity_input(input, 2)
input_shape = input.shape
input = batched_input
diff --git a/kornia/enhance/jpeg.py b/kornia/enhance/jpeg.py
index 43b76b8a6..4b783b4d2 100644
--- a/kornia/enhance/jpeg.py
+++ b/kornia/enhance/jpeg.py
@@ -31,6 +31,7 @@ from kornia.core.check import (
KORNIA_CHECK_SHAPE,
)
from kornia.core.utils import is_compiling, is_exporting
+from kornia.enhance.adjust import _check_floating_image
from kornia.geometry.transform.affwarp import rescale
from kornia.image.utils import perform_keep_shape_image
@@ -576,6 +577,7 @@ def jpeg_codec_differentiable(
>>> img_jpeg.sum().backward()
"""
+ _check_floating_image(input, "jpeg_codec_differentiable")
# Check that inputs are tensors
KORNIA_CHECK_IS_TENSOR(input)
KORNIA_CHECK_IS_TENSOR(jpeg_quality)
diff --git a/kornia/enhance/shift_rgb.py b/kornia/enhance/shift_rgb.py
index 0a64a2fbf..720f40c32 100644
--- a/kornia/enhance/shift_rgb.py
+++ b/kornia/enhance/shift_rgb.py
@@ -19,6 +19,7 @@
import torch
from kornia.core.check import KORNIA_CHECK_IS_COLOR, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
+from kornia.enhance.adjust import _check_floating_image
def shift_rgb(image: torch.Tensor, r_shift: torch.Tensor, g_shift: torch.Tensor, b_shift: torch.Tensor) -> torch.Tensor:
@@ -31,6 +32,7 @@ def shift_rgb(image: torch.Tensor, r_shift: torch.Tensor, g_shift: torch.Tensor,
Shift each image's channel by either r_shift for red, g_shift for green and b_shift for blue channels.
"""
+ _check_floating_image(image, "shift_rgb")
KORNIA_CHECK_IS_TENSOR(image)
KORNIA_CHECK_IS_COLOR(image, f"with shape {image.shape}")
KORNIA_CHECK_SHAPE(image, ["B", "3", "H", "W"])
diff --git a/tests/enhance/test_conventions_enhance.py b/tests/enhance/test_conventions_enhance.py
index b50f896ee..372ca4dfb 100644
--- a/tests/enhance/test_conventions_enhance.py
+++ b/tests/enhance/test_conventions_enhance.py
@@ -19,7 +19,8 @@ import pytest
import torch
import kornia
-from kornia.core.exceptions import BaseError, ShapeError
+from kornia.core.check import disable_checks, enable_checks
+from kornia.core.exceptions import BaseError, ShapeError, TypeCheckError
from testing.base import BaseTester
@@ -252,3 +253,78 @@ class TestEnhanceConventions(BaseTester):
image = torch.zeros(1, 1, 300, 300, dtype=torch.float16)
image[..., :, 150:] = 1.0
self.assert_close(kornia.enhance.equalize(image), kornia.enhance.equalize(image.float()).half())
+
+ # Each op expects a floating-point image in [0, 1]. An integer image used to come back saturated, wrapped or
+ # negative without an error, so it is now rejected with the conversion to use (#5981).
+ _FLOAT_ONLY_OPS = {
+ "adjust_brightness": lambda x: kornia.enhance.adjust_brightness(x, 0.2),
+ "adjust_brightness_accumulative": lambda x: kornia.enhance.adjust_brightness_accumulative(x, 1.3),
+ "adjust_contrast": lambda x: kornia.enhance.adjust_contrast(x, 1.5),
+ "adjust_contrast_with_mean_subtraction": lambda x: kornia.enhance.adjust_contrast_with_mean_subtraction(x, 1.5),
+ "adjust_saturation_with_gray_subtraction": lambda x: kornia.enhance.adjust_saturation_with_gray_subtraction(
+ x, 1.5
+ ),
+ "adjust_gamma": lambda x: kornia.enhance.adjust_gamma(x, 2.0),
+ "adjust_sigmoid": kornia.enhance.adjust_sigmoid,
+ "adjust_log": kornia.enhance.adjust_log,
+ "posterize": lambda x: kornia.enhance.posterize(x, 3),
+ "solarize": lambda x: kornia.enhance.solarize(x, 0.5),
+ "sharpness": lambda x: kornia.enhance.sharpness(x, 0.5),
+ "shift_rgb": lambda x: kornia.enhance.shift_rgb(
+ x, *(torch.full((x.shape[0],), s, device=x.device) for s in (0.1, 0.0, 0.0))
+ ),
+ "jpeg_codec_differentiable": lambda x: kornia.enhance.jpeg_codec_differentiable(
+ x, torch.full((x.shape[0],), 50.0, device=x.device)
+ ),
+ }
+
+ @pytest.mark.parametrize("op", sorted(_FLOAT_ONLY_OPS))
+ @pytest.mark.parametrize("int_dtype", [torch.uint8, torch.int32])
+ def test_convention_integer_image_is_rejected_5981(self, op, int_dtype, device):
+ image = torch.randint(0, 256, (2, 3, 16, 16), device=device).to(int_dtype)
+
+ with pytest.raises(TypeCheckError, match=rf"^{op} expects a floating-point image in \[0, 1\]") as exc_info:
+ self._FLOAT_ONLY_OPS[op](image)
+
+ assert isinstance(exc_info.value, TypeError)
+ assert "image.float() / 255" in str(exc_info.value)
+ assert exc_info.value.actual_type == int_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.
+ image = torch.randint(0, 256, (2, 3, 16, 16), device=device, dtype=torch.uint8)
+ out = self._FLOAT_ONLY_OPS[op](image.to(dtype) / 255)
+
+ assert out.dtype == dtype
+ assert out.shape == image.shape
+
+ @pytest.mark.device_agnostic
+ def test_convention_integer_image_check_follows_disable_checks_5981(self):
+ image = torch.randint(0, 256, (1, 3, 16, 16), dtype=torch.uint8)
+ disable_checks()
+ try:
+ kornia.enhance.adjust_brightness(image, 0.2)
+ finally:
+ enable_checks()
+ with pytest.raises(TypeCheckError):
+ kornia.enhance.adjust_brightness(image, 0.2)
+
+ _SCRIPTABLE_FLOAT_ONLY_OPS = {
+ "adjust_sigmoid": lambda op, x: op(x),
+ "adjust_log": lambda op, x: op(x),
+ "shift_rgb": lambda op, x: op(
+ x, *(torch.full((x.shape[0],), s, device=x.device, dtype=x.dtype) for s in (0.1, 0.0, 0.0))
+ ),
+ }
+
+ @pytest.mark.parametrize("op", sorted(_SCRIPTABLE_FLOAT_ONLY_OPS))
+ def test_convention_integer_image_check_keeps_torchscript_5981(self, op, device, dtype):
+ # The ops that scripted before the check still script, match eager on a float image and reject an integer one.
+ call = self._SCRIPTABLE_FLOAT_ONLY_OPS[op]
+ scripted = torch.jit.script(getattr(kornia.enhance, op))
+ image = torch.rand(2, 3, 8, 8, device=device, dtype=dtype)
+
+ self.assert_close(call(scripted, image), call(getattr(kornia.enhance, op), image))
+ with pytest.raises(Exception, match=f"{op} expects a floating-point image"):
+ call(scripted, torch.randint(0, 256, (2, 3, 8, 8), device=device, dtype=torch.uint8))