π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(enhance): count each equalize and CLAHE pixel in the lookup entry it reads (#6190)
Prateekshit Jaiswalc187bc8bcec6
diff --git a/changelog.d/6018.fixed.md b/changelog.d/6018.fixed.mdindex e8e951e45..2db247263 100644--- a/changelog.d/6018.fixed.md+++ b/changelog.d/6018.fixed.md@@ -1 +1 @@-`equalize_clahe` and `RandomClahe` now count, clip and accumulate the tile histograms of float16 and bfloat16 images in float32 on the default (fast) path, and cast only the finished lookup tables back. Before, with clipping enabled, a float16 image whose tiles hold about 65520 or more pixels, such as 2048 x 2048 with the default 8 x 8 grid, came back entirely NaN. Once the per-bin cap `clip_limit * tile_pixels // 256` passed 65504, `equalize_clahe` raised an overflow error on a float16 image instead (and aborted the process on MPS); at the default `clip_limit=40.0` that is any tile above about 419,000 pixels, such as the 8 x 8 grid of a 7680 x 4320 image. Smaller half-precision tiles got lookup tables one or more gray levels off in float16 and several in bfloat16. The lookup tables now equal those of a float32 image with the same pixel values. float32 and float64 results, and the `slow_and_differentiable` path, are unchanged.+`equalize_clahe` and `RandomClahe` now count, clip and accumulate the tile histograms of float16 and bfloat16 images in float32 on the default (fast) path, and cast only the finished lookup tables back. Before, with clipping enabled, a float16 image whose tiles hold about 65520 or more pixels, such as 2048 x 2048 with the default 8 x 8 grid, came back entirely NaN. Once the per-bin cap `clip_limit * tile_pixels // 256` passed 65504, `equalize_clahe` raised an overflow error on a float16 image instead (and aborted the process on MPS); at the default `clip_limit=40.0` that is any tile above about 419,000 pixels, such as the 8 x 8 grid of a 7680 x 4320 image. Smaller half-precision tiles got lookup tables one or more gray levels off in float16 and several in bfloat16. The lookup tables now equal those of a float32 image that holds the 8-bit levels the lookup reads, `(x * 255).long()` in the image dtype. float32 and float64 results, and the `slow_and_differentiable` path, are unchanged.diff --git a/changelog.d/6190.fixed.md b/changelog.d/6190.fixed.mdnew file mode 100644index 000000000..1d7838fdb--- /dev/null+++ b/changelog.d/6190.fixed.md@@ -0,0 +1,19 @@+`equalize`, `equalize3d`, `RandomEqualize` and `RandomEqualize3D`, and `equalize_clahe` and `RandomClahe` on their+default (fast) path, now count each pixel in the lookup-table entry it reads: its 8-bit level `(x * 255).long()` in+the input dtype. Before, they counted it in `floor(256 x)`, the `torch.histc` placement, which put every value in+`[k/256, k/255)` one bin above the entry it reads; that is about half of a continuous image (#6181). `equalize` of a+float32 or float64 image is now `PIL.ImageOps.equalize` of those levels, as long as a float32 channel holds at most+`2**24` pixels (4096 x 4096). A channel whose lookup step is 0 is still returned unchanged.++On continuous float32 input, over 20 random images per size:++- `equalize` changes 48β49% of the pixels:+ - at 64 x 64, 42% move by 1 gray level and 1.8% by 2;+ - at 300 x 300, 49% move by 1 and 0.04% by 2;+ - in one 64 x 64 image the lookup step went from 16 to 15, and its pixels moved by up to 18 levels.+- `equalize3d` changes 50% of the voxels of 4 x 64 x 64 volumes.+- `equalize_clahe` with the default arguments changes about 77% of the pixels at 256 x 256 and 296 x 296. The pixels+ that change move by 0.73 gray levels on average, and by at most 3.6.++8-bit images in float32 and float64 are unchanged. On 8-bit images, half-precision `equalize_clahe` now stays within+0.2 gray levels of float32 in float16 and within 1.5 in bfloat16 (default arguments, 256 x 256 and 296 x 296).diff --git a/kornia/enhance/adjust.py b/kornia/enhance/adjust.pyindex 10ddcfe0e..3f1c80b27 100644--- a/kornia/enhance/adjust.py+++ b/kornia/enhance/adjust.py@@ -1135,10 +1135,10 @@ def _scale_channel_batched(input: torch.Tensor) -> torch.Tensor:r"""Vectorized histogram equalization over the leading ``(B, C)`` planes.Computes all per-plane histograms/LUTs in a single batched pass instead of a Python loop of- ``B * C`` serial ``torch.histc`` calls. The per-plane histogram is built with ``scatter_add``- instead of ``torch.histc``; the two agree except for a handful of values landing exactly on a- bin edge (``~1%`` of pixels shift by one 256-bin, i.e. ``~1/255`` in the output), which is- within the equalization test tolerance.+ ``B * C`` serial calls. Each pixel is counted in the LUT entry it reads, its 8-bit level+ ``(x * 255).long()`` computed in the input dtype, so a plane whose LUT step is not 0 comes out as+ ``PIL.ImageOps.equalize`` of those levels while the counts and their running sums are exact (a plane of+ up to ``2**24`` pixels in float32); a plane whose step is 0 is returned unchanged.Args:input: image tensor shaped ``(B, C, *spatial)`` with values in ``[0, 1]``.@@ -1150,8 +1150,8 @@ def _scale_channel_batched(input: torch.Tensor) -> torch.Tensor:n = shape[0] * shape[1]scaled = input.flatten(0, 1).flatten(1) * 255.0 # (N, P)- # 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).+ # Input is expected in [0, 1]. The histogram and the LUT lookup both index with ``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;# on MPS before torch 2.13 it costs one host sync instead (see ``_lookup_value_check``). Inputs the# lookup can index keep working exactly as before.@@ -1165,13 +1165,12 @@ def _scale_channel_batched(input: torch.Tensor) -> torch.Tensor:# 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)+ # Per-plane 256-bin histogram on the index the lookup below reads, so every pixel is counted in its own+ # entry, as PIL counts and reads one 8-bit level. ``torch.histc(x, 256, 0, 255)`` bins in ``floor(256 x)``,+ # which puts every value in ``[k/256, k/255)``, about half of a continuous image, one bin above that entry.+ index = scaled.long()histo = torch.zeros(n, 256, device=input.device, dtype=count_dtype)- histo.scatter_add_(1, bins, torch.ones_like(scaled, dtype=count_dtype))+ histo.scatter_add_(1, index, torch.ones_like(scaled, dtype=count_dtype))# step = (sum(nonzero) - last_nonzero) // 255, per plane.total = histo.sum(1)@@ -1189,7 +1188,7 @@ def _scale_channel_batched(input: torch.Tensor) -> torch.Tensor:# The LUT holds integers in [0, 255], which every floating dtype represents exactly.lut = torch.clamp(lut, 0, 255).to(scaled.dtype)- result = lut.gather(1, scaled.long())+ result = lut.gather(1, index)result = torch.where(step_col == 0, scaled, result)return (result / 255.0).reshape(shape)@@ -1215,12 +1214,16 @@ def equalize(input: torch.Tensor) -> torch.Tensor:.. note::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``.+ a 256-bin histogram. Each pixel is counted in the lookup-table entry it reads, its 8-bit level+ ``(x * 255).long()`` in the input dtype, so a float32 or float64 image gives ``PIL.ImageOps.equalize``+ of those levels. A channel whose lookup step is 0 is returned unchanged, and a float32 image counts in+ float32, which is exact while a channel holds at most ``2**24`` pixels (4096 x 4096). 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)diff --git a/kornia/enhance/equalization.py b/kornia/enhance/equalization.pyindex 590b7945e..cf737d193 100644--- a/kornia/enhance/equalization.py+++ b/kornia/enhance/equalization.py@@ -154,14 +154,15 @@ def _compute_interpolation_tiles(padded_imgs: torch.Tensor, tile_size: Tuple[intdef _tiles_histc(tiles: torch.Tensor, bins: int) -> torch.Tensor:- r"""Histogram every tile over ``[0, 1]`` in one pass, matching a per-tile CPU ``torch.histc``.+ r"""Histogram every tile over ``[0, 1]`` in one pass, on the index its lookup table is read with.- One ``scatter_add_`` counts all tiles, instead of one ``histc`` launch per tile, and keeps a static- output shape so the function stays a single dynamo graph. The index is computed as ``histc``- computes it, in the same float32/float64 promotion as ``_torch_histc_cast``: ``floor(x * bins)``,- with ``x == 1`` in the last bin. Values outside ``[0, 1]`` and NaN are not counted, which the CPU- ``histc`` also skips; they go to one extra overflow column per tile that is dropped. (``histc`` on- MPS counts values marginally outside ``[0, 1]``, so there this matches CPU rather than MPS.)+ A value ``x`` is counted in bin ``(x * (bins - 1)).long()``, computed in the dtype of ``tiles`` as the+ tile lookups compute ``(x * 255).long()``, so every pixel is counted in the entry it reads, as OpenCV+ counts and reads one 8-bit level; ``torch.histc``'s ``floor(x * bins)`` would put every value in+ ``[k/256, k/255)`` one bin above that entry. One ``scatter_add_`` counts all+ tiles, instead of one ``histc`` launch per tile, and keeps a static output shape so the function stays+ a single dynamo graph. Values outside ``[0, 1]`` and NaN are not counted, which the CPU ``histc`` also+ skips; they go to one extra overflow column per tile that is dropped.Args:tiles: flattened tiles. (T, P)@@ -172,10 +173,11 @@ def _tiles_histc(tiles: torch.Tensor, bins: int) -> torch.Tensor:"""num_tiles = tiles.shape[0]+ # The index is computed in the dtype of ``tiles``, as the lookups compute theirs; only the counts are wider.+ idx = (tiles * (bins - 1)).long().clamp_(0, bins - 1)x = tiles.to(_normalize_to_float32_or_float64(tiles.dtype))# clamp keeps [0, 1] unchanged and NaN as NaN, so the comparison is False exactly where histc skips.in_range = x.clamp(0, 1) == x- idx = (x * bins).to(torch.int64).clamp_(0, bins - 1)# this mask is what drops out-of-range values; without it they land in the first or last binidx = torch.where(in_range, idx, bins)counts = torch.zeros(num_tiles, bins + 1, dtype=x.dtype, device=x.device)@@ -519,12 +521,15 @@ def equalize_clahe(.. note::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`.+ 256-bin lookup table. On the default path each pixel is counted in the entry it reads, its 8-bit+ level ``(x * 255).long()`` in the input dtype, as OpenCV counts and reads one level;+ ``slow_and_differentiable=True`` keeps its soft histogram centred on the levels ``k / 255``. 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")diff --git a/testing/half_precision_xfails/cpu_bfloat16.txt b/testing/half_precision_xfails/cpu_bfloat16.txtindex fe40d69b6..fc8fe013a 100644--- a/testing/half_precision_xfails/cpu_bfloat16.txt+++ b/testing/half_precision_xfails/cpu_bfloat16.txt@@ -14,7 +14,6 @@ call builtins.AssertionError tests/augmentation/_3d/test_random_rotation_3d.py::call builtins.AssertionError tests/augmentation/_3d/test_random_rotation_3d.py::TestRandomRotation3D::test_random_rotation[cpu-bfloat16]call builtins.AssertionError tests/augmentation/container/test_augmentation_sequential.py::TestAugmentationSequential::test_random_crops[cpu-bfloat16]call builtins.AssertionError tests/augmentation/container/test_augmentation_sequential.py::TestAugmentationSequential::test_random_erasing[cpu-bfloat16]-call builtins.AssertionError tests/augmentation/test_augmentation.py::TestRandomClahe::test_smoke[cpu-bfloat16]call builtins.AssertionError tests/augmentation/test_augmentation.py::TestRandomGaussianIllumination::test_smoke[cpu-bfloat16]call builtins.AssertionError tests/augmentation/test_augmentation.py::TestRandomHue::test_sequential[cpu-bfloat16]call builtins.AssertionError tests/augmentation/test_augmentation.py::TestRandomRGBShift::test_random_rgb_shift[cpu-bfloat16]diff --git a/tests/augmentation/test_augmentation.py b/tests/augmentation/test_augmentation.pyindex 68a9fead3..4b6d5b3f7 100644--- a/tests/augmentation/test_augmentation.py+++ b/tests/augmentation/test_augmentation.py@@ -4541,7 +4541,7 @@ class TestRandomClahe(BaseTester):def test_smoke(self, device, dtype):img = torch.arange(36, device=device, dtype=dtype).reshape(2, 2, 3, 3) / 36# Centre-anchored blending of the 2 x 2 tile LUTs, evaluated with the per-pixel reference.- expected = torch.tensor(86173 / (16 * 255), device=device, dtype=dtype)+ expected = torch.tensor(102320 / (16 * 255), device=device, dtype=dtype)self.assert_close(RandomClahe(p=1.0, grid_size=(2, 2))(img).sum(), expected)@pytest.mark.parametrize("batch_shape", [(1, 3, 5, 7), (3, 1, 5, 7)])diff --git a/tests/enhance/test_adjust.py b/tests/enhance/test_adjust.pyindex 3e1c7e77c..b98c67c6b 100644--- a/tests/enhance/test_adjust.py+++ b/tests/enhance/test_adjust.py@@ -1652,13 +1652,14 @@ def _weights(input):def _equalize_reference(input):- # Independent per-plane histogram: bincount instead of the batched scatter_add implementation.+ # Independent per-plane histogram: bincount instead of the batched scatter_add implementation, counting each+ # pixel in the 8-bit level its lookup reads, as PIL does.count_dtype = torch.float64 if input.dtype == torch.float64 else torch.float32planes = input.reshape(input.shape[0] * input.shape[1], -1)outputs = []for plane in planes:scaled = plane * 255.0- indices = (scaled * (256.0 / 255.0)).floor().long().clamp(0, 255)+ indices = scaled.long().clamp(0, 255)hist = torch.bincount(indices, minlength=256).to(count_dtype)last_count = hist[hist.nonzero()[-1, 0]]step = torch.div(hist.sum() - last_count, 255, rounding_mode="trunc")diff --git a/tests/enhance/test_conventions_enhance.py b/tests/enhance/test_conventions_enhance.pyindex fcad5fb66..47960d2b8 100644--- a/tests/enhance/test_conventions_enhance.py+++ b/tests/enhance/test_conventions_enhance.py@@ -281,6 +281,47 @@ class TestEnhanceConventions(BaseTester):# Compare on the CPU: MPS has no float64.self.assert_close(out.cpu().double(), expected, rtol=0, atol=ulp / 2 + 1e-12)+ # equalize, equalize3d and equalize_clahe count every pixel in the lookup-table entry it reads, its 8-bit level+ # (x * 255).long() in the input dtype, so a continuous image gives exactly what its 8-bit levels give. They used to+ # count it in floor(256 x), one bin above the entry it reads for every value in [k/256, k/255) (#6181).+ @pytest.mark.parametrize(+ ("op", "shape"),+ [+ (kornia.enhance.equalize, (2, 3, 64, 64)),+ (kornia.enhance.equalize3d, (1, 2, 4, 32, 32)),+ (lambda x: kornia.enhance.equalize_clahe(x, 40.0, (2, 2)), (1, 2, 32, 32)), # 16 x 16 tiles+ (lambda x: kornia.enhance.equalize_clahe(x, 40.0, (2, 2)), (1, 2, 30, 30)), # 15 x 15 tiles+ ],+ ids=["equalize", "equalize3d", "clahe_even_tiles", "clahe_odd_tiles"],+ )+ def test_convention_equalize_counts_the_8bit_level_it_reads_6181(self, device, dtype, op, shape):+ image = torch.rand(shape, generator=torch.Generator().manual_seed(6181)).to(device, dtype)+ levels = (image * 255).long().to(dtype) / 255+ assert torch.equal(op(image), op(levels))++ # equalize is PIL's Equalize of the 8-bit levels its lookup reads, for continuous input as well. 13 of these 32+ # values lie in [k/256, k/255); counting them in floor(256 x) put two of the columns up to 17 levels off (#6181).+ # Snippet used to generate expected (Pillow 13.0.0; every row of the output is the same):+ # x = np.array(_PIL_VALUES, dtype=np.float32)+ # image = Image.fromarray(np.tile((x * np.float32(255)).astype(np.uint8), (33, 1)))+ # np.asarray(PIL.ImageOps.equalize(image))[0]+ _PIL_VALUES = [+ 0.8563, 0.3588, 0.4575, 0.3561, 0.8804, 0.1501, 0.1975, 0.664, 0.5902, 0.133, 0.4056, 0.0907, 0.315, 0.7355,+ 0.1808, 0.1451, 0.4088, 0.7295, 0.0887, 0.3781, 0.8849, 0.8814, 0.2303, 0.7546, 0.1854, 0.2752, 0.9493, 0.3477,+ 0.636, 0.3706, 0.505, 0.765,+ ] # fmt: skip+ _PIL_EXPECTED = [+ 223, 107, 149, 99, 231, 33, 58, 182, 165, 17, 132, 8, 83, 198, 41, 25, 140, 190, 0, 124, 248, 231, 66, 206, 50,+ 74, 255, 91, 173, 116, 157, 215,+ ] # fmt: skip++ def test_convention_equalize_matches_pil_on_continuous_input_6181(self, device, dtype):+ if dtype in (torch.float16, torch.bfloat16):+ pytest.skip("the expected levels are those of the float32 values, which half precision rounds first")+ image = torch.tensor(self._PIL_VALUES, device=device, dtype=dtype).repeat(33, 1)[None, None]+ expected = torch.tensor(self._PIL_EXPECTED, device=device, dtype=dtype).div(255).expand(33, 32)+ assert torch.equal(kornia.enhance.equalize(image)[0, 0], expected)+# 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 = {diff --git a/tests/enhance/test_equalization.py b/tests/enhance/test_equalization.pyindex 6ff44877d..3e9279741 100644--- a/tests/enhance/test_equalization.py+++ b/tests/enhance/test_equalization.py@@ -236,7 +236,7 @@ class TestEqualization(BaseTester):y = enhance.equalize_clahe(x, 40.0, (1, 1))- assert y.sum().item() == pytest.approx(8416 / 255)+ assert y.sum().item() == pytest.approx(8539 / 255)assert y.max().item() == pytest.approx(1.0)@pytest.mark.parametrize("grid_size", [(1, 1), (1, 2), (2, 1), (2, 2)])@@ -249,15 +249,15 @@ class TestEqualization(BaseTester):assert torch.isfinite(out).all()def test_histogram_skips_out_of_range(self, device, dtype):- # torch.histc on CPU counts only values inside [min, max] and _tiles_histc must too. 1.0000001 and- # -1e-7 are inside the window equalize_clahe admits (see RandomClahe's warning and #4564), and MPS's- # torch.histc counts them, so this also pins CPU/MPS parity.+ # Like torch.histc on CPU, _tiles_histc counts only values inside [0, 1]. 1.0000001 and -1e-7 are inside the+ # window equalize_clahe admits (see RandomClahe's warning and #4564), and MPS's torch.histc counts them, so+ # this also pins CPU/MPS parity. With 4 bins a value is counted in (x * 3).long(): 0.5 in 1 and 0.25 in 0.from kornia.enhance.equalization import _tiles_histcif dtype in (torch.float16, torch.bfloat16):pytest.skip("1.0000001 and -1e-7 round to 1 and 0 in half precision")tiles = torch.tensor([[0.5, 1.0000001, -1e-7, 0.25]], device=device, dtype=dtype)- expected = torch.tensor([[0.0, 1.0, 1.0, 0.0]], device=device, dtype=dtype)+ expected = torch.tensor([[1.0, 1.0, 0.0, 0.0]], device=device, dtype=dtype)self.assert_close(_tiles_histc(tiles, 4), expected)def test_dynamo(self, device, dtype, torch_optimizer):@@ -343,46 +343,14 @@ class TestEqualization(BaseTester):return torch.arange(width, device=device).div(float(width - 1))[None].expand(height, width)[None][None]def test_he(self, img):- # should be similar to enhance.equalize but slower. Similar because the lut is computed in a different way.- clip_limit: float = 0.0- grid_size: Tuple = (1, 1)- res = enhance.equalize_clahe(img, clip_limit=clip_limit, grid_size=grid_size)- # NOTE: for next versions we need to improve the computation of the LUT- # and test with a better image- self.assert_close(- res[..., 0, :],- torch.tensor(- [- [- [- 0.051,- 0.102,- 0.1490,- 0.2000,- 0.251,- 0.2980,- 0.3490,- 0.3490,- 0.451,- 0.451,- 0.5490,- 0.5490,- 0.651,- 0.651,- 0.6980,- 0.7490,- 0.8000,- 0.851,- 0.902,- 1.0000,- ]- ]- ],- dtype=res.dtype,- device=res.device,- ),- low_tolerance=True,- )+ # With no clip limit and one tile this is global equalization with OpenCV's rounded LUT: the 20-step ramp maps+ # to 20 evenly spaced levels, round(12.75 * (i + 1)) with ties to even, as an exact rational evaluation of+ # CLAHE gives. Counting each pixel in floor(256 x) instead of the entry floor(255 x) it reads merged four pairs+ # of neighbouring steps (#6181).+ res = enhance.equalize_clahe(img, clip_limit=0.0, grid_size=(1, 1))+ levels = [13, 26, 38, 51, 64, 76, 89, 102, 115, 128, 140, 153, 166, 178, 191, 204, 217, 230, 242, 255]+ expected = torch.tensor(levels, dtype=res.dtype, device=res.device) / 255+ self.assert_close(res[0, 0, 0], expected, rtol=0, atol=0)def test_ahe(self, img):clip_limit: float = 0.0@@ -426,8 +394,8 @@ class TestEqualization(BaseTester):# its range; piling them into the first 6 bins mapped every pixel but the first above 0.77. No other test# pins the values of the differentiable path's soft histogram.expected_row = torch.tensor(- [0.2235, 0.3333, 0.332, 0.2967, 0.4431, 0.4458, 0.4078, 0.4431, 0.5556, 0.4444]- + [0.6667, 0.5922, 0.6301, 0.6667, 0.7033, 0.668, 0.7765, 0.8523, 0.851, 1.0],+ [0.2235, 0.3333, 0.332, 0.2967, 0.4431, 0.4458, 0.4078, 0.5569, 0.5556, 0.5176]+ + [0.6667, 0.6654, 0.6301, 0.7765, 0.7791, 0.7412, 0.8902, 0.9255, 0.9268, 1.0],dtype=res.dtype,device=res.device,)@@ -437,7 +405,7 @@ class TestEqualization(BaseTester):dtype=res.dtype,device=res.device,)- self.assert_close(res[0, 0, 0], expected_row, low_tolerance=True)+ self.assert_close(res[0, 0, 0], expected_row, rtol=0, atol=1e-4)self.assert_close(res_diff[0, 0, 0], expected_row_diff, low_tolerance=True)@pytest.mark.parametrize("count, expected_level", [(100, 100), (128, 128)])@@ -460,8 +428,8 @@ class TestEqualization(BaseTester):assert out.device == devicedef test_clahe_lut_rounding_ties_to_even(self, device, dtype):- # Four bins with counts [1, 2, 1, 2] give CDF values [0.5, 1.5, 2, 3].- tiles = torch.tensor([0.0, 0.25, 0.25, 0.5, 0.75, 0.75], device=device, dtype=dtype)+ # Four bins with counts [1, 2, 1, 2] give CDF values [0.5, 1.5, 2, 3]. A value is counted in (x * 3).long().+ tiles = torch.tensor([0.0, 0.34, 0.34, 0.67, 1.0, 1.0], device=device, dtype=dtype)luts = enhance.equalization._compute_luts(tiles.view(1, 1, 1, 1, 2, 3), num_bins=4, clip=0.0)expected = torch.tensor([0.0, 2.0, 2.0, 3.0], device=device, dtype=dtype)self.assert_close(luts.flatten(), expected, rtol=0, atol=0)@@ -494,7 +462,7 @@ class TestEqualization(BaseTester):# round(cumsum * 255 / 1024): bin 100 maps to round(535 * 255 / 1024) = 133 and bin 200 to# round(908 * 255 / 1024) = 226, where writing the residual into bins 0..31 would give 138 and 228.# The counts stay in float32 for half-precision tiles too, so this is exact in every dtype.- values = torch.cat([torch.zeros(342), torch.full((341,), 100 / 256), torch.full((341,), 200 / 256)])+ values = torch.cat([torch.zeros(342), torch.full((341,), 100 / 255), torch.full((341,), 200 / 255)])tiles = values.to(device, dtype).view(1, 1, 1, 1, 32, 32)clip = torch.tensor([40.0], device=device, dtype=dtype) if clip_as_tensor else 40.0luts = enhance.equalization._compute_luts(tiles, clip=clip)@@ -511,7 +479,7 @@ class TestEqualization(BaseTester):# is a multiple of 1/8, so 64 * 255 * output is an integer. The expected integers come from an exact# rational evaluation of CLAHE pixel by pixel, independent of this implementation's tile indexing; the# reference is an exact-Fraction restatement of _compute_tiles/_compute_luts/_compute_equalized_tiles- # (tile size ceil(n/g) rounded up to even, trailing reflect pad, floor(v*256) histogram, clip and+ # (tile size ceil(n/g) rounded up to even, trailing reflect pad, floor(v*255) histogram, clip and# redistribute, round(cumsum*255/P), axis blend weight (T-k-0.5)/T); the reference posted on #4628 is# evaluated here with round-to-even LUTs and the clipped residual spread over every (256 // residual)-th# bin from bin 0, as OpenCV does.@@ -532,14 +500,14 @@ class TestEqualization(BaseTester):img = levels[codes][None, None]expected = torch.tensor([- [2048, 3072, 10304, 11840, 2048, 11328, 2048, 8792, 6528, 16320, 6144, 10176],- [3072, 12224, 12096, 16320, 2048, 7168, 11328, 4096, 8552, 2048, 4096, 2048],- [5248, 5248, 8265, 8411, 11488, 3760, 6816, 16320, 8411, 8265, 6144, 6144],- [9792, 8192, 2384, 7120, 8087, 5056, 3424, 16320, 2288, 5440, 12224, 12224],- [3712, 2688, 2608, 11040, 3152, 16320, 16320, 4800, 3616, 3936, 6144, 6144],- [16320, 3968, 2832, 5056, 16320, 5712, 8769, 2384, 3424, 7983, 2944, 12224],- [16320, 16320, 3840, 4992, 16320, 8312, 8440, 4224, 2688, 6016, 16320, 6144],- [4096, 10176, 16320, 10560, 6912, 11072, 11328, 6912, 2688, 2944, 10176, 3072],+ [3072, 5120, 12096, 13888, 3712, 13376, 4096, 10816, 8552, 16320, 8192, 11200],+ [5120, 14272, 14144, 16320, 2048, 9032, 13376, 5760, 10560, 2048, 5120, 4096],+ [7296, 7296, 10040, 10264, 13536, 5696, 8703, 16320, 10339, 10145, 8192, 8192],+ [11072, 9432, 2384, 8129, 9832, 6544, 5056, 16320, 3808, 6176, 13888, 13888],+ [5760, 3712, 2608, 13088, 4800, 16320, 16320, 5984, 5184, 5568, 8192, 8192],+ [16320, 6016, 2832, 7056, 16320, 6729, 10416, 2384, 5056, 9191, 2944, 13376],+ [16320, 16320, 5760, 7040, 16320, 10048, 10304, 5504, 3328, 7936, 16320, 8192],+ [6144, 12224, 16320, 12608, 8192, 13120, 13248, 8552, 2688, 2944, 11200, 3072],],dtype=torch.float64,)@@ -560,8 +528,8 @@ class TestEqualization(BaseTester):self.assert_close(out_t, out.transpose(-2, -1))# The fast path counts, clips and accumulates each tile's histogram in float32 (float64 for float64 images) and- # casts only the finished LUT back, so a half-precision tile gets the LUT a float32 tile with the same pixels gets.- # Counting in float16 overflowed the clipped total of a 256 x 256 tile to inf, the tile the default 8 x 8 grid+ # casts only the finished LUT back, so a half-precision tile gets the LUT a float32 tile with the same 8-bit levels+ # gets. Counting in float16 overflowed the clipped total of a 256 x 256 tile to inf, the tile the default 8 x 8 grid# gives on a 2048 x 2048 image, and rounded counts above 2048; bfloat16 rounded counts above 256.@pytest.mark.parametrize("clip_as_tensor", [False, True])@pytest.mark.parametrize(@@ -575,7 +543,10 @@ class TestEqualization(BaseTester):clip = torch.tensor([40.0], device=device) if clip_as_tensor else 40.0luts = enhance.equalization._compute_luts(tiles, clip=clip)count_dtype = torch.float64 if dtype == torch.float64 else torch.float32- expected = enhance.equalization._compute_luts(tiles.to(count_dtype), clip=clip)+ # A pixel is counted in the level it reads, (x * 255).long() in the image dtype; float16 can round 255 x to+ # another level than float32 does, so the reference tiles hold those levels.+ levels = (tiles * 255).long().to(count_dtype) / 255+ expected = enhance.equalization._compute_luts(levels, clip=clip)assert luts.dtype == dtypeassert torch.equal(luts.to(count_dtype), expected)