Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(enhance): name the [0, 1] range when equalize cannot index an input (#4489)

Dipak Chaudhari81ef78999049
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a8e6fa585..081d16935 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -407,6 +407,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Bug fixes
+* `kornia.enhance.equalize`, `equalize3d`, `RandomEqualize` and `RandomEqualize3D` raise a `RuntimeError` naming
+ the `[0, 1]` input range for values the 256-bin lookup cannot index, instead of a raw
+ `index 259 is out of bounds for dimension 1 with size 256` from the gather. The check uses
+ `torch._assert_async`, so it adds no device sync and `torch.compile` fullgraph still works, and inputs that
+ equalized before (including values a hair above 1) are unchanged. The docstrings now state the range, the
+ 256-bin histogram, and that a 3D volume of at most 255 voxels per channel comes back unchanged.
+ (#4431, #4432, #4489)
+
* `kornia.contrib.diamond_square` generates fractals with a spatial side below 3 px. A 1 px side raised
`ValueError: math domain error` and a 2 px side a `TypeError` from a float in the `torch.rand` size, so
`RandomPlasmaBrightness`, `RandomPlasmaContrast` and `RandomPlasmaShadow` failed on such images. A small
diff --git a/kornia/augmentation/_2d/intensity/equalize.py b/kornia/augmentation/_2d/intensity/equalize.py
index 5c22af432..8578a643c 100644
--- a/kornia/augmentation/_2d/intensity/equalize.py
+++ b/kornia/augmentation/_2d/intensity/equalize.py
@@ -39,7 +39,8 @@ class RandomEqualize(IntensityAugmentationBase2D):
- Output: :math:`(B, C, H, W)`
.. note::
- This function internally uses :func:`kornia.enhance.equalize`.
+ This function internally uses :func:`kornia.enhance.equalize`, which expects the input in
+ :math:`[0, 1]` and raises a ``RuntimeError`` naming that range for values it cannot equalize.
Examples:
>>> rng = torch.manual_seed(0)
diff --git a/kornia/augmentation/_3d/intensity/equalize.py b/kornia/augmentation/_3d/intensity/equalize.py
index c82747cc5..1922242b2 100644
--- a/kornia/augmentation/_3d/intensity/equalize.py
+++ b/kornia/augmentation/_3d/intensity/equalize.py
@@ -37,7 +37,10 @@ class RandomEqualize3D(IntensityAugmentationBase3D):
- Output: :math:`(B, C, D, H, W)`
Note:
- Input tensor must be float and normalized into [0, 1] for the best differentiability support.
+ Input tensor must be float and normalized into [0, 1]: values outside it that the 256-bin lookup
+ cannot index raise a ``RuntimeError`` naming the range. This uses :func:`kornia.enhance.equalize3d`,
+ which equalizes each channel's whole volume from one 256-bin histogram, so a volume with no more
+ than 255 voxels per channel is returned unchanged.
Additionally, this function accepts another transformation tensor (:math:`(B, 4, 4)`), then the
applied transformation will be merged int to the input transformation tensor and returned.
diff --git a/kornia/enhance/adjust.py b/kornia/enhance/adjust.py
index f6800a70e..4e3856df4 100644
--- a/kornia/enhance/adjust.py
+++ b/kornia/enhance/adjust.py
@@ -964,9 +964,15 @@ def _scale_channel_batched(input: torch.Tensor) -> torch.Tensor:
n = shape[0] * shape[1]
scaled = input.reshape(n, -1) * 255.0 # (N, P)
- # Input is expected in [0, 1] (see the docstring). Out-of-range values are clamped into the
- # 256-bin range below rather than raising: the previous ``.item()`` range check forced two
- # device syncs and broke ``torch.compile`` fullgraph for no correctness benefit on valid input.
+ # Input is expected in [0, 1]. The histogram index below is clamped, but the LUT lookup indexes
+ # with the unclamped ``scaled.long()``, which is out of bounds unless ``scaled`` is in (-1, 256).
+ # Check that domain without ``.item()``, so there is no device sync and fullgraph still compiles;
+ # inputs the lookup can index keep working exactly as before.
+ _assert_async_value_check(
+ ((scaled > -1.0) & (scaled < 256.0)).all(),
+ "equalize expects input values in [0, 1]. Scale the image into that range first, "
+ "for example image / 255.0 for 8-bit data.",
+ )
# Per-plane 256-bin histogram matching ``torch.histc(x, 256, 0, 255)`` bin placement.
bins = torch.clamp((scaled * (256.0 / 255.0)).floor().long(), 0, 255)
@@ -1051,6 +1057,12 @@ def equalize(input: torch.Tensor) -> torch.Tensor:
Returns:
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 runs on CPU and CUDA (via ``torch._assert_async``); on MPS it is
+ skipped, as for :func:`adjust_gamma`.
+
Example:
>>> x = torch.rand(1, 2, 3, 3)
>>> equalize(x).shape
@@ -1074,6 +1086,14 @@ def equalize3d(input: torch.Tensor) -> torch.Tensor:
Returns:
Equalized volume with shape :math:`(B, C, D, H, W)`.
+ .. 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; 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 runs on CPU and CUDA (via
+ ``torch._assert_async``); on MPS it is skipped.
+
"""
# Scales each channel independently (each (D, H, W) volume), batched over (B, C).
return _scale_channel_batched(input)
diff --git a/tests/enhance/test_adjust.py b/tests/enhance/test_adjust.py
index 5a814a8ab..4c76e8623 100644
--- a/tests/enhance/test_adjust.py
+++ b/tests/enhance/test_adjust.py
@@ -885,6 +885,28 @@ class TestEqualize(BaseTester):
inputs = torch.ones(bs, channels, height, width, device=device, dtype=torch.float64)
self.gradcheck(kornia.enhance.equalize, (inputs,), fast_mode=False)
+ @pytest.mark.parametrize("scale, shift", [(2.0, 0.0), (1.0, -1.0)])
+ def test_out_of_range_input_names_the_range(self, scale, shift, device, dtype):
+ # kornia#4431: an input the 256-bin lookup cannot index used to fail with a raw
+ # "index 259 is out of bounds" from the gather.
+ if device.type != "cpu":
+ pytest.skip("value asserts are synchronous only on CPU (async on CUDA, skipped on MPS)")
+ x = torch.linspace(0, 1, 64, device=device, dtype=dtype).reshape(1, 1, 8, 8) * scale + shift
+ with pytest.raises(RuntimeError, match=r"expects input values in \[0, 1\]"):
+ kornia.enhance.equalize(x)
+
+ def test_input_the_lookup_can_index_is_still_accepted(self, device, dtype):
+ # The check covers exactly the values that crashed, so a hair above 1 keeps working.
+ x = torch.linspace(0, 1, 64, device=device, dtype=dtype).reshape(1, 1, 8, 8) * 1.0001
+ assert kornia.enhance.equalize(x).shape == x.shape
+
+ def test_dynamo_fullgraph(self, device, dtype):
+ # The range check must not reintroduce a graph break (#3842 removed an ``.item()`` check).
+ x = torch.rand(2, 3, 8, 8, device=device, dtype=dtype)
+ torch._dynamo.reset()
+ compiled = torch.compile(kornia.enhance.equalize, fullgraph=True, backend="eager")
+ self.assert_close(compiled(x), kornia.enhance.equalize(x))
+
@pytest.mark.skip(reason="args and kwargs in decorator")
def test_jit(self, device, dtype):
batch_size, channels, height, width = 1, 2, 3, 3
@@ -908,6 +930,22 @@ class TestEqualize(BaseTester):
class TestEqualize3D(BaseTester):
+ @pytest.mark.parametrize("scale, shift", [(1.5, 0.0), (1.0, -0.5)])
+ def test_out_of_range_input_names_the_range(self, scale, shift, device, dtype):
+ # kornia#4432: the 3D path shares the lookup and failed the same way.
+ if device.type != "cpu":
+ pytest.skip("value asserts are synchronous only on CPU (async on CUDA, skipped on MPS)")
+ torch.manual_seed(0)
+ x = torch.rand(1, 1, 5, 7, 9, device=device, dtype=dtype) * scale + shift
+ with pytest.raises(RuntimeError, match=r"expects input values in \[0, 1\]"):
+ kornia.enhance.equalize3d(x)
+
+ def test_at_most_255_voxels_per_channel_is_unchanged(self, device, dtype):
+ # As the docstring states: the lookup step is an integer division by 255.
+ torch.manual_seed(0)
+ x = torch.rand(2, 3, 3, 5, 17, device=device, dtype=dtype) * 0.5
+ self.assert_close(kornia.enhance.equalize3d(x), x)
+
@pytest.mark.parametrize("shape", [(3, 6, 10, 10), (2, 3, 6, 10, 10), (3, 2, 3, 6, 10, 10)])
def test_shape_equalize3d(self, shape, device, dtype):
inputs3d = torch.ones(*shape, device=device, dtype=dtype)