Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(enhance): count half-precision equalize pixels in the bin of the entry they read (#6075)

Prateekshit Jaiswal5b83154ab2f0
diff --git a/changelog.d/6075.fixed.md b/changelog.d/6075.fixed.md
new file mode 100644
index 000000000..8846476c5
--- /dev/null
+++ b/changelog.d/6075.fixed.md
@@ -0,0 +1 @@
+`equalize`, `equalize3d`, `RandomEqualize` and `RandomEqualize3D` now count each pixel of a float16 or bfloat16 image in the histogram bin of the lookup-table entry it reads. The bin was computed in the input dtype, where an 8-bit level v rounds up to bin v + 1 for v >= 240 in float16 and v >= 128 in bfloat16, so neighbouring levels merged and the whole table moved: `[10, 100, 254, 255] / 255` equalized to `[0, 150, 255, 255]` instead of the `[0, 100, 200, 255]` that float32 and `PIL.ImageOps.equalize` give, and a random 64 x 64 8-bit image was up to 16 gray levels off. Half-precision results on 8-bit images now match float32 up to output rounding; float32 and float64 results are unchanged.
diff --git a/kornia/enhance/adjust.py b/kornia/enhance/adjust.py
index fee9eadad..10ddcfe0e 100644
--- a/kornia/enhance/adjust.py
+++ b/kornia/enhance/adjust.py
@@ -1161,12 +1161,15 @@ def _scale_channel_batched(input: torch.Tensor) -> torch.Tensor:
"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)
# Count in float32 (float64 stays float64): a count grows with the plane size, which half precision
# cannot hold. float16 rounds counts above 2048 and their total overflows to inf past 65504, and
# bfloat16 rounds counts above 256.
count_dtype = _normalize_to_float32_or_float64(scaled.dtype)
+ # Per-plane 256-bin histogram matching ``torch.histc(x, 256, 0, 255)`` bin placement. The bin is computed
+ # from the same ``scaled`` the lookup below reads, but in ``count_dtype``: an 8-bit level v gives
+ # ``scaled == v`` in every dtype, and v * 256 / 255 rounds up to bin v + 1 in float16 (v >= 240) and
+ # bfloat16 (v >= 128), which counted the pixel one bin above the entry it reads.
+ bins = torch.clamp((scaled.to(count_dtype) * (256.0 / 255.0)).floor().long(), 0, 255)
histo = torch.zeros(n, 256, device=input.device, dtype=count_dtype)
histo.scatter_add_(1, bins, torch.ones_like(scaled, dtype=count_dtype))
diff --git a/tests/enhance/test_conventions_enhance.py b/tests/enhance/test_conventions_enhance.py
index 4b6fec49e..34964a25c 100644
--- a/tests/enhance/test_conventions_enhance.py
+++ b/tests/enhance/test_conventions_enhance.py
@@ -254,6 +254,29 @@ class TestEnhanceConventions(BaseTester):
image[..., :, 150:] = 1.0
self.assert_close(kornia.enhance.equalize(image), kornia.enhance.equalize(image.float()).half())
+ # An 8-bit level v reads lookup entry (v / 255 * 255).long() == v in every dtype. Its bin, v * 256 / 255, was
+ # computed in the input dtype, where it rounds up to v + 1 for v >= 240 in float16 and v >= 128 in bfloat16, so
+ # the pixel was counted one bin above the entry it reads and the whole table moved.
+ # Snippet used to generate expected (float32 kornia gives the same):
+ # PIL.ImageOps.equalize(Image.fromarray(np.repeat([10, 100, 254, 255], 300).astype(np.uint8).reshape(30, 40)))
+ def test_convention_equalize_counts_each_8bit_level_in_its_own_bin(self, device, dtype):
+ levels = torch.tensor([10.0, 100.0, 254.0, 255.0], device=device)
+ image = (levels.repeat_interleave(300) / 255).reshape(1, 1, 30, 40).to(dtype)
+ out = kornia.enhance.equalize(image)
+ assert out.dtype == dtype
+ expected = torch.tensor([0.0, 100.0, 200.0, 255.0], device=device)
+ self.assert_close((out.float().flatten()[::300] * 255).round(), expected, rtol=0, atol=0)
+
+ def test_convention_equalize_of_an_8bit_image_matches_float64_up_to_output_rounding(self, device, dtype):
+ # Every bin now matches the float64 one, so only the final division by 255 rounds: at most half a ulp.
+ torch.manual_seed(0)
+ image = torch.randint(0, 256, (2, 3, 64, 64)).double() / 255
+ expected = kornia.enhance.equalize(image)
+ out = kornia.enhance.equalize(image.to(device, dtype))
+ ulp = {torch.float16: 2.0**-11, torch.bfloat16: 2.0**-8}.get(dtype, 1e-6)
+ # Compare on the CPU: MPS has no float64.
+ self.assert_close(out.cpu().double(), expected, rtol=0, atol=ulp / 2 + 1e-12)
+
# 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 = {