π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(core)!: KORNIA_CHECK_IS_IMAGE checks the shape with raises=True; NaN, empty and wide-integer range fixes; Image.print permutes channels-last data (#5232)
Dmytro Mishkin232f3de2357b
diff --git a/changelog.d/5232.breaking.md b/changelog.d/5232.breaking.mdnew file mode 100644index 000000000..ec69a643c--- /dev/null+++ b/changelog.d/5232.breaking.md@@ -0,0 +1,6 @@+`KORNIA_CHECK_IS_IMAGE` checks the shape again with the default `raises=True`, as its docstring says and as it did+before #3156. It used to return `True` for a tensor that is not `(*, 1, H, W)` or `(*, 3, H, W)`, such as `(5, 4, 5)`,+an RGBA `(B, 4, H, W)`, `(4, 5)` or a 0-d scalar, while the same call with `raises=False` returned `False`. It now raises+`ImageError`, so code that passed a non-image through the check gets `ImageError`. So does `image_to_string`, which+rendered a 6-channel tensor as if it had 3 channels. A float image containing NaN used to pass the range check for+both `raises` values. It now fails it: `raises=True` raises `ValueCheckError` and `raises=False` returns `False`.diff --git a/changelog.d/5232.fixed.md b/changelog.d/5232.fixed.mdnew file mode 100644index 000000000..73ab4bcf1--- /dev/null+++ b/changelog.d/5232.fixed.md@@ -0,0 +1,8 @@+`KORNIA_CHECK_IS_IMAGE` range-check fixes. An empty image, such as a `(0, 3, H, W)` batch, passes instead of crashing+inside `torch.aminmax`, with `raises=False` too. A signed integer image whose `bits` is at least the dtype's width (for+example `int8` with the default `bits=8` or with `bits=9`, or `int64` with `bits=64`) used to fail for every value,+because `2 ** bits - 1` was converted to the dtype, where it overflowed. It is now range-checked normally. `uint16`,+`uint32` and `uint64` images are range-checked instead of crashing. The integer range error states+`[0, 2 ** bits - 1]` and sets `expected_range` to it, where it used to say `[0, 1]` whatever `bits` was.+`Image.print` now moves channels-last data to channels-first before rendering it, as `Image.write` does, so an RGB image+from `Image.from_numpy` prints correctly instead of as a garbled picture.diff --git a/kornia/core/check.py b/kornia/core/check.pyindex bbb146f96..f2c380a38 100644--- a/kornia/core/check.py+++ b/kornia/core/check.py@@ -654,8 +654,15 @@ def KORNIA_CHECK_IS_COLOR_OR_GRAY(x: torch.Tensor, msg: Optional[str] = None, rareturn True+# The unsigned dtypes wider than 8 bits, each with the signed dtype of the same width.+_UNSIGNED_AS_SIGNED = {torch.uint16: torch.int16, torch.uint32: torch.int32, torch.uint64: torch.int64}++def KORNIA_CHECK_IS_IMAGE(x: torch.Tensor, msg: Optional[str] = None, raises: bool = True, bits: int = 8) -> bool:- """Check whether an image tensor is ranged properly [0, 1] for float or [0, 2 ** bits] for int.+ """Check whether a tensor is a color or gray image with values in [0, 1] for float or [0, 2 ** bits - 1] for int.++ The shape must be :math:`(*, 3, H, W)` or :math:`(*, 1, H, W)`. A NaN value fails the range check, and an empty+ image passes it.Args:x: image tensor to evaluate.@@ -684,20 +691,30 @@ def KORNIA_CHECK_IS_IMAGE(x: torch.Tensor, msg: Optional[str] = None, raises: boif not _KORNIA_CHECKS_ENABLED:return True- # Combine the color or gray check with the range check- if not raises and not KORNIA_CHECK_IS_COLOR_OR_GRAY(x, msg, raises):+ if not KORNIA_CHECK_IS_COLOR_OR_GRAY(x, msg, raises):return False- amin, amax = torch.aminmax(x)+ if x.numel() == 0:+ return True+ offset = 0if x.dtype in (torch.bfloat16, float16, float32, float64):- invalid = (amin < 0) | (amax > 1)+ low, high = 0.0, 1.0else:- max_int_value = (1 << bits) - 1- invalid = (amin < 0) | (amax > max_int_value)-- if invalid.item():- return _handle_invalid_range(msg, raises, amin, amax)+ low, high = 0, (1 << bits) - 1+ signed = _UNSIGNED_AS_SIGNED.get(x.dtype)+ if signed is not None:+ # torch.aminmax has no kernel for these dtypes. Flipping the sign bit of a same-width signed view maps the+ # unsigned order onto the signed order; the offset is added back to the Python numbers below.+ x = x.view(signed) ^ torch.iinfo(signed).min+ offset = 1 << (torch.iinfo(signed).bits - 1)++ # The bounds are compared as Python numbers, so 2 ** bits - 1 cannot overflow the dtype, and in this form+ # a NaN, which fails every comparison, fails the check.+ amin, amax = torch.stack(torch.aminmax(x)).tolist()+ amin, amax = amin + offset, amax + offset+ if not (low <= amin and amax <= high):+ return _handle_invalid_range(msg, raises, amin, amax, (low, high))return True@@ -782,20 +799,17 @@ def KORNIA_CHECK_LAF(laf: torch.Tensor, raises: bool = True) -> bool:def _handle_invalid_range(- msg: Optional[str], raises: bool, min_val: float | torch.Tensor, max_val: float | torch.Tensor+ msg: Optional[str], raises: bool, min_val: float, max_val: float, expected_range: tuple[float, float]) -> bool:"""Handle invalid range cases."""- # Extract scalar values if tensors- min_scalar = min_val.item() if isinstance(min_val, torch.Tensor) else min_val- max_scalar = max_val.item() if isinstance(max_val, torch.Tensor) else max_val-- err_msg = f"Value range mismatch: expected [0, 1], got [{min_scalar}, {max_scalar}]."+ low, high = (f"{b:g}" if isinstance(b, float) else f"{b}" for b in expected_range)+ err_msg = f"Value range mismatch: expected [{low}, {high}], got [{min_val}, {max_val}]."if msg is not None:err_msg += f"\n {msg}"if raises:raise ValueCheckError(err_msg,- actual_value=(min_scalar, max_scalar),- expected_range=(0.0, 1.0),+ actual_value=(min_val, max_val),+ expected_range=expected_range,)return Falsediff --git a/kornia/image/image.py b/kornia/image/image.pyindex 6529520aa..3b760b82e 100644--- a/kornia/image/image.py+++ b/kornia/image/image.py@@ -396,4 +396,7 @@ class Image:.. image:: https://github.com/kornia/data/blob/main/print_image.png?raw=true"""- print(image_to_string(self.data, max_width))+ data = self.data+ if self.channels_order == ChannelsOrder.CHANNELS_LAST:+ data = data.permute(2, 0, 1)+ print(image_to_string(data, max_width))diff --git a/testing/half_precision_eager_rng.py b/testing/half_precision_eager_rng.pyindex 4b69f73dc..bb3c2f471 100644--- a/testing/half_precision_eager_rng.py+++ b/testing/half_precision_eager_rng.py@@ -172,7 +172,7 @@ AUDITED_EAGER_RNG_CALLS = tuple((f"tests/core/test_check.py::TestCheckShape::{test_name}",),"value-independent",)- for test_name, lines in (("test_valid", range(71, 75)), ("test_invalid", range(83, 87)))+ for test_name, lines in (("test_valid", range(73, 77)), ("test_invalid", range(85, 89)))for line in lines),*(diff --git a/tests/core/test_check.py b/tests/core/test_check.pyindex 0dd6b77ea..1f62b90dc 100644--- a/tests/core/test_check.py+++ b/tests/core/test_check.py@@ -46,6 +46,8 @@ from kornia.core.exceptions import (ValueCheckError,)+from testing.base import BaseTester+class TestCheck:def test_valid(self):@@ -295,7 +297,7 @@ class TestCheckLaf:assert KORNIA_CHECK_LAF(torch.rand(4, 2, 2), raises=False) is False-class TestCheckIsImage:+class TestCheckIsImage(BaseTester):def test_valid_float(self):assert KORNIA_CHECK_IS_IMAGE(torch.rand(3, 4, 4)) is Trueassert KORNIA_CHECK_IS_IMAGE(torch.rand(2, 3, 4, 4)) is True@@ -318,17 +320,100 @@ class TestCheckIsImage:def test_invalid_shape(self):x = torch.rand(1, 4, 4, 4)- assert KORNIA_CHECK_IS_IMAGE(x) is True+ with pytest.raises(ImageError):+ KORNIA_CHECK_IS_IMAGE(x)def test_invalid_range_no_raise(self):bad = torch.tensor([[[-0.1, 2.0]]], dtype=torch.float32)assert KORNIA_CHECK_IS_IMAGE(bad, raises=False) is Falsedef test_invalid_shape_no_raise(self):- # When raises=False, shape check is actually enforcedbad = torch.rand(1, 4, 4, 4)assert KORNIA_CHECK_IS_IMAGE(bad, raises=False) is False+ @pytest.mark.parametrize("shape", [(5, 4, 5), (2, 4, 4, 4), (4, 5), (7,), ()])+ def test_shape_verdict_does_not_depend_on_raises(self, device, dtype, shape):+ # The values lie in [0, 1], so only the shape can fail the check.+ x = torch.rand(shape, device=device, dtype=dtype)+ assert KORNIA_CHECK_IS_IMAGE(x, raises=False) is False+ with pytest.raises(ImageError):+ KORNIA_CHECK_IS_IMAGE(x)++ @pytest.mark.parametrize("nan_count", ["one", "all"])+ def test_nan_fails_the_range_check(self, device, dtype, nan_count):+ x = torch.rand(2, 3, 4, 5, device=device, dtype=dtype)+ if nan_count == "all":+ x.fill_(float("nan"))+ else:+ x[1, 2, 3, 4] = float("nan")+ assert KORNIA_CHECK_IS_IMAGE(x, raises=False) is False+ with pytest.raises(ValueCheckError, match=r"expected \[0, 1\]"):+ KORNIA_CHECK_IS_IMAGE(x)++ def test_float_range_error_reports_the_unit_range(self, device, dtype):+ x = torch.tensor([[[-0.5, 0.25, 1.5]]], device=device, dtype=dtype)+ with pytest.raises(ValueCheckError, match=r"expected \[0, 1\], got \[-0\.5, 1\.5\]\.") as err:+ KORNIA_CHECK_IS_IMAGE(x)+ assert err.value.actual_value == (-0.5, 1.5)+ assert err.value.expected_range == (0.0, 1.0)++ @pytest.mark.parametrize("shape", [(0, 3, 4, 5), (0, 1, 4, 5), (3, 0, 0)])+ def test_empty_image_passes(self, device, dtype, shape):+ # An empty image holds no value that could be out of range.+ x = torch.rand(shape, device=device, dtype=dtype)+ assert KORNIA_CHECK_IS_IMAGE(x, raises=False) is True+ assert KORNIA_CHECK_IS_IMAGE(x) is True+ u = torch.zeros(shape, device=device, dtype=torch.uint8)+ assert KORNIA_CHECK_IS_IMAGE(u, raises=False) is True+ assert KORNIA_CHECK_IS_IMAGE(u) is True++ def test_empty_tensor_with_a_bad_shape_fails(self, device, dtype):+ x = torch.rand(0, 5, 4, 5, device=device, dtype=dtype)+ assert KORNIA_CHECK_IS_IMAGE(x, raises=False) is False+ with pytest.raises(ImageError):+ KORNIA_CHECK_IS_IMAGE(x)++ @pytest.mark.parametrize("bits", [4, 8, 10, 16])+ def test_integer_range_is_zero_to_two_to_the_bits_minus_one(self, device, bits):+ top = 2**bits - 1+ assert KORNIA_CHECK_IS_IMAGE(torch.full((3, 4, 5), top, device=device, dtype=torch.int32), bits=bits) is True+ x = torch.full((3, 4, 5), top + 1, device=device, dtype=torch.int32)+ assert KORNIA_CHECK_IS_IMAGE(x, bits=bits, raises=False) is False+ with pytest.raises(ValueCheckError, match=rf"expected \[0, {top}\], got \[{top + 1}, {top + 1}\]\.") as err:+ KORNIA_CHECK_IS_IMAGE(x, bits=bits)+ assert err.value.actual_value == (top + 1, top + 1)+ assert err.value.expected_range == (0, top)++ @pytest.mark.parametrize(+ ("int_dtype", "bits"),+ [(torch.int8, 8), (torch.int8, 9), (torch.int16, 16), (torch.int32, 32), (torch.int64, 64), (torch.int64, 63)],+ )+ def test_signed_dtype_accepts_every_nonnegative_value_that_fits_the_bits(self, device, int_dtype, bits):+ # 2**bits - 1 exceeds these dtypes' maximum, so every non-negative value of the dtype is in range.+ top = torch.iinfo(int_dtype).max+ x = torch.tensor([[[0, 5, top]]], device=device, dtype=int_dtype)+ assert KORNIA_CHECK_IS_IMAGE(x, bits=bits, raises=False) is True+ assert KORNIA_CHECK_IS_IMAGE(x, bits=bits) is True+ x[0, 0, 0] = -1+ assert KORNIA_CHECK_IS_IMAGE(x, bits=bits, raises=False) is False+ with pytest.raises(ValueCheckError) as err:+ KORNIA_CHECK_IS_IMAGE(x, bits=bits)+ assert err.value.actual_value == (-1, top)+ assert err.value.expected_range == (0, 2**bits - 1)++ @pytest.mark.parametrize("uint_dtype", [torch.uint16, torch.uint32, torch.uint64])+ def test_wide_unsigned_dtype_is_range_checked(self, device, uint_dtype):+ info = torch.iinfo(uint_dtype)+ x = torch.tensor([[[0, 1000, info.max]]], dtype=uint_dtype).to(device)+ assert KORNIA_CHECK_IS_IMAGE(x, bits=info.bits, raises=False) is True+ assert KORNIA_CHECK_IS_IMAGE(x, bits=info.bits) is True+ # With one bit fewer the largest value is out of range, and the error reports it exactly.+ assert KORNIA_CHECK_IS_IMAGE(x, bits=info.bits - 1, raises=False) is False+ with pytest.raises(ValueCheckError) as err:+ KORNIA_CHECK_IS_IMAGE(x, bits=info.bits - 1)+ assert err.value.actual_value == (0, info.max)+ assert err.value.expected_range == (0, 2 ** (info.bits - 1) - 1)+class TestChecksEnableDisable:"""Tests for the runtime enable/disable check control API."""diff --git a/tests/image/test_image.py b/tests/image/test_image.pyindex 375c6cde1..cfbd5fe37 100644--- a/tests/image/test_image.py+++ b/tests/image/test_image.py@@ -25,6 +25,7 @@ from kornia.core._compat import torch_version_lefrom kornia.core.exceptions import ShapeErrorfrom kornia.image.base import KORNIA_CHECK_IMAGE_LAYOUT, ChannelsOrder, ColorSpace, ImageLayout, ImageSize, PixelFormatfrom kornia.image.image import Image+from kornia.image.image_print import image_to_stringfrom testing.base import BaseTester@@ -193,6 +194,14 @@ class TestImage(BaseTester):img = Image.from_numpy(data, color_space=ColorSpace.RGB, channels_order=ChannelsOrder.CHANNELS_LAST)img.write(tmp_path / "image.jpg")+ @pytest.mark.parametrize("order", [ChannelsOrder.CHANNELS_LAST, ChannelsOrder.CHANNELS_FIRST])+ @pytest.mark.parametrize("height", [4, 3])+ def test_print_renders_the_channels_first_image(self, device, order, height, capsys) -> None:+ chw = (torch.arange(3 * height * 5, device=device).reshape(3, height, 5) * 4).to(torch.uint8)+ data = chw.permute(1, 2, 0).contiguous() if order == ChannelsOrder.CHANNELS_LAST else chw+ make_image(data, ColorSpace.RGB, order).print()+ assert capsys.readouterr().out == image_to_string(chw) + "\n"+def make_image(data: torch.Tensor, cs: ColorSpace, order: ChannelsOrder) -> Image:if order not in [ChannelsOrder.CHANNELS_FIRST, ChannelsOrder.CHANNELS_LAST]:diff --git a/tests/image/test_print.py b/tests/image/test_print.pyindex bc534aea1..5e4ed91ca 100644--- a/tests/image/test_print.py+++ b/tests/image/test_print.py@@ -79,6 +79,12 @@ class TestImageToString:with pytest.raises(RuntimeError):print_image([img]) # Do not accept list+ def test_rejects_a_tensor_that_is_not_a_color_or_gray_image(self):+ from kornia.core.exceptions import ImageError++ with pytest.raises(ImageError):+ image_to_string(torch.rand(6, 4, 4))+def test_print_smoke(self):img = torch.rand(3, 15, 15)print_image(img)