Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(enhance): read k / 255 at 8-bit level k on CUDA in equalize, CLAHE and posterize (#6542)

Dmytro Mishkin0ee23ec52c20
diff --git a/changelog.d/6542.fixed.md b/changelog.d/6542.fixed.md
new file mode 100644
index 000000000..4eb524eb4
--- /dev/null
+++ b/changelog.d/6542.fixed.md
@@ -0,0 +1 @@
+`equalize`, `equalize3d`, `equalize_clahe` and `posterize`, and the augmentations built on them, now read an 8-bit image normalized as `levels / 255` at its intended levels on every device. On CUDA, dividing a float64 tensor by 255 multiplies by a rounded `1 / 255` and leaves 24 of the 256 levels one unit in the last place below `k / 255`, which these ops truncated to level `k - 1`: on a random 8-bit image, float64 `equalize` on CUDA differed from the CPU by up to 2 levels on 8% of the pixels, `equalize_clahe` by up to 16 levels, and `posterize(x, 7)` by 2; `x * (1 / 255)` did the same on the CPU. For float32 and float64 input the factor 255 is now raised by `2**-21`, relative, before truncation, so a continuous value that close below a level boundary also reads the level above, about 7 in 100000 pixels of a uniform random image. Levels read from float16 and bfloat16 input are unchanged. A channel that `equalize` or `equalize3d` leaves unchanged (lookup step 0, for example a volume of at most 255 voxels) now comes back exactly as given, instead of as `(x * 255) / 255`, which could be one unit in the last place off.
diff --git a/kornia/augmentation/_3d/intensity/equalize.py b/kornia/augmentation/_3d/intensity/equalize.py
index 68f67f684..dd5700a4f 100644
--- a/kornia/augmentation/_3d/intensity/equalize.py
+++ b/kornia/augmentation/_3d/intensity/equalize.py
@@ -45,7 +45,7 @@ class RandomEqualize3D(IntensityAugmentationBase3D):
- values the 256-bin lookup cannot index (outside roughly ``[0, 1]``) raise a ``RuntimeError`` naming
the range. Each channel's whole volume supplies one 256-bin histogram
(:func:`kornia.enhance.equalize3d`), so a volume with at most 255 voxels per channel is returned
- unchanged up to roundoff.
+ unchanged.
Examples:
>>> import torch
diff --git a/kornia/enhance/adjust.py b/kornia/enhance/adjust.py
index a879d30bd..3ced32299 100644
--- a/kornia/enhance/adjust.py
+++ b/kornia/enhance/adjust.py
@@ -89,6 +89,26 @@ def _check_floating_image(image: torch.Tensor, op: str) -> None:
)
+def _level_scale(dtype: torch.dtype, top: float = 255.0) -> float:
+ """Return the factor that turns a value in ``[0, 1]`` into the level in ``0 .. top`` its truncation reads.
+
+ ``(x * _level_scale(x.dtype)).long()`` is the 8-bit level ``(x * 255).long()``, except that ``k / 255`` reads
+ level ``k`` even when it was rounded a few units in the last place below ``k / 255``. CUDA divides by a Python
+ number by multiplying with its rounded reciprocal, as ``x * (1 / 255)`` does on any device, which leaves 24 of the
+ 256 float64 levels one unit below ``k / 255``; truncating ``x * 255`` read those as ``k - 1``. For float32 and
+ float64 the factor is ``top`` raised by four float32 epsilons, relative (``2**-21``, eight units in the last place
+ of 255 in float32), so the margin grows with the level as that roundoff does, and a continuous value moves up a
+ level only within that margin below a level boundary, about 7 in 100000 values of a uniform image. float64 takes
+ the float32 margin rather than its own, so the same values read the same levels in both dtypes, and float32
+ roundoff carried into a float64 image is covered too. Half precision gets ``top`` itself, so the levels it reads
+ are unchanged: ``x * 255`` is rounded to the half-precision grid, which already gives ``k`` back for ``k / 255``
+ rounded to half precision.
+ """
+ if dtype in (torch.float32, torch.float64):
+ return top * (1.0 + 2.0**-21)
+ return top
+
+
def _make_factor_broadcastable(factor: torch.Tensor, image: torch.Tensor) -> torch.Tensor:
"""Right-pad ``factor`` with singleton dimensions so it broadcasts against ``image``.
@@ -990,7 +1010,9 @@ def posterize(input: torch.Tensor, bits: Union[int, torch.Tensor]) -> torch.Tens
.. image:: _static/img/posterize.png
- Non-differentiable function, ``torch.uint8`` involved.
+ Non-differentiable function, ``torch.uint8`` involved. Each value is read at its 8-bit level
+ ``(x * 255).long()``, with the 255 raised by four float32 epsilons, relative, in float32 and float64, so
+ ``k / 255`` reads level ``k`` even when its division was rounded a unit low, as dividing by 255 on CUDA does.
Args:
input: image torch.Tensor with shape ``(*, C, H, W)`` to posterize.
@@ -1045,11 +1067,14 @@ def posterize(input: torch.Tensor, bits: Union[int, torch.Tensor]) -> torch.Tens
# Ref: https://github.com/tensorflow/tpu/blob/master/models/official/efficientnet/autoaugment.py#L222
# Potential approach: implementing kornia.LUT with floating points
# https://github.com/albumentations-team/albumentations/blob/master/albumentations/augmentations/functional.py#L472
+ # Both shifts read an 8-bit level by truncation; ``_level_scale`` keeps ``k / 255`` rounded a unit low at ``k``.
+ scale = _level_scale(input.dtype)
+
def _left_shift(input: torch.Tensor, shift: torch.Tensor) -> torch.Tensor:
- return ((input * 255).to(torch.uint8) * (2**shift)).to(input.dtype) / 255.0
+ return ((input * scale).to(torch.uint8) * (2**shift)).to(input.dtype) / 255.0
def _right_shift(input: torch.Tensor, shift: torch.Tensor) -> torch.Tensor:
- return (input * 255).to(torch.uint8) / (2**shift).to(input.dtype) / 255.0
+ return (input * scale).to(torch.uint8) / (2**shift).to(input.dtype) / 255.0
def _posterize_one(input: torch.Tensor, bits: torch.Tensor) -> torch.Tensor:
# Branchless for torch.compile: the bits==0 / bits==8 special cases guard a uint8
@@ -1171,9 +1196,9 @@ def _scale_channel_batched(input: torch.Tensor) -> torch.Tensor:
Computes all per-plane histograms/LUTs in a single batched pass instead of a Python loop of
``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.
+ ``(x * _level_scale(x.dtype)).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 as it is.
Args:
input: image tensor shaped ``(B, C, *spatial)`` with values in ``[0, 1]``.
@@ -1183,16 +1208,20 @@ def _scale_channel_batched(input: torch.Tensor) -> torch.Tensor:
"""
shape = input.shape
n = shape[0] * shape[1]
- scaled = input.flatten(0, 1).flatten(1) * 255.0 # (N, P)
-
- # 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).
+ flat = input.flatten(0, 1).flatten(1) # (N, P)
+ # The level each pixel reads, before truncation. The factor is 255 raised by four float32 epsilons, relative, in
+ # float32 and float64, so k / 255 rounded a unit low, as dividing by 255 on CUDA leaves 24 float64 levels,
+ # still reads level k (see ``_level_scale``); half precision keeps 255.
+ levels = flat * _level_scale(flat.dtype)
+
+ # Input is expected in [0, 1]. The histogram and the LUT lookup both index with ``levels.long()``,
+ # which is out of bounds unless ``levels`` 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 ``_check_async``). Inputs the
# lookup can index keep working exactly as before. The check keeps the index in bounds, so it runs
# with checks disabled too: a compiled CPU scatter with an index out of range terminates the process.
_check_async(
- ((scaled > -1.0) & (scaled < 256.0)).all(),
+ ((levels > -1.0) & (levels < 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.",
guard=True,
@@ -1201,13 +1230,13 @@ def _scale_channel_batched(input: torch.Tensor) -> torch.Tensor:
# 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)
+ count_dtype = _normalize_to_float32_or_float64(flat.dtype)
# 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()
+ index = levels.long()
histo = torch.zeros(n, 256, device=input.device, dtype=count_dtype)
- histo.scatter_add_(1, index, torch.ones_like(scaled, dtype=count_dtype))
+ histo.scatter_add_(1, index, torch.ones_like(levels, dtype=count_dtype))
# step = (sum(nonzero) - last_nonzero) // 255, per plane.
total = histo.sum(1)
@@ -1223,11 +1252,12 @@ def _scale_channel_batched(input: torch.Tensor) -> torch.Tensor:
lut = torch.div(histo.cumsum(1) + step_trunc, step_col.clamp(min=1), rounding_mode="trunc")
lut = torch.cat([torch.zeros(n, 1, device=input.device, dtype=lut.dtype), lut[:, :-1]], 1)
# The LUT holds integers in [0, 255], which every floating dtype represents exactly.
- lut = torch.clamp(lut, 0, 255).to(scaled.dtype)
+ lut = torch.clamp(lut, 0, 255).to(flat.dtype)
- result = lut.gather(1, index)
- result = torch.where(step_col == 0, scaled, result)
- return (result / 255.0).reshape(shape)
+ # A plane whose step is 0 comes back as it is, not as (x * 255) / 255, which can be a unit off; it also keeps
+ # ``x * 255`` from being one more image-sized temporary next to ``levels``.
+ result = lut.gather(1, index) / 255.0
+ return torch.where(step_col == 0, flat, result).reshape(shape)
def equalize(input: torch.Tensor) -> torch.Tensor:
@@ -1253,7 +1283,10 @@ def equalize(input: torch.Tensor) -> torch.Tensor:
The input is expected as a floating-point image in :math:`[0, 1]`, and each channel is equalized from
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
+ of those levels. In float32 and float64 the 255 is raised by four float32 epsilons, relative (``2**-21``),
+ so ``k / 255`` reads level ``k`` even when its division was rounded a unit low, as dividing by 255 on CUDA
+ leaves 24 of the 256 float64 levels; a continuous value moves up a level only that close below a level
+ boundary. 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
@@ -1293,9 +1326,10 @@ def equalize3d(input: torch.Tensor) -> torch.Tensor:
.. note::
The input is expected as a floating-point volume in :math:`[0, 1]`, and each channel's whole
- ``(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 up to
- floating-point roundoff; just above that, whether it changes depends on the values. An integer or
+ ``(D, H, W)`` volume is equalized from one 256-bin histogram, reading each voxel at its 8-bit level as
+ :func:`equalize` reads a pixel. 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. An integer or
boolean volume raises :exc:`~kornia.core.exceptions.TypeCheckError`, as for :func:`equalize`. Values
the 256-bin lookup cannot index (outside roughly :math:`[0, 1]`) raise a ``RuntimeError`` naming the
range, during the call for a CPU volume, even when checks are disabled, as for :func:`equalize`. On CUDA,
diff --git a/kornia/enhance/equalization.py b/kornia/enhance/equalization.py
index 5f367dc75..04d04f40e 100644
--- a/kornia/enhance/equalization.py
+++ b/kornia/enhance/equalization.py
@@ -27,7 +27,7 @@ from kornia.core.check import _check_async
from kornia.core.utils import _normalize_to_float32_or_float64, _to_device_nonblocking
from kornia.image.utils import perform_keep_shape_image
-from .adjust import _check_floating_image
+from .adjust import _check_floating_image, _level_scale
from .histogram import histogram
@@ -157,10 +157,10 @@ def _compute_interpolation_tiles(padded_imgs: torch.Tensor, tile_size: Tuple[int
def _tiles_histc(tiles: torch.Tensor, bins: int) -> torch.Tensor:
r"""Histogram every tile over ``[0, 1]`` in one pass, on the index its lookup table is read with.
- 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
+ A value ``x`` is counted in bin ``(x * _level_scale(x.dtype, bins - 1)).long()``, computed in the dtype of
+ ``tiles`` as the tile lookups compute ``(x * _level_scale(x.dtype)).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.
@@ -175,7 +175,7 @@ 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)
+ idx = (tiles * _level_scale(tiles.dtype, 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
@@ -373,7 +373,9 @@ def _compute_equalized_tiles(interp_tiles: torch.Tensor, luts: torch.Tensor) ->
num_imgs, gh, gw, c, th, tw = interp_tiles.shape
# equalize tiles
- flatten_interp_tiles: torch.Tensor = (interp_tiles * 255).long().flatten(-2, -1) # B x GH x GW x 4 x C x (THxTW)
+ # The 8-bit level each pixel reads; ``_level_scale`` keeps ``k / 255`` rounded a unit low at level ``k``.
+ # B x GH x GW x 4 x C x (THxTW)
+ flatten_interp_tiles: torch.Tensor = (interp_tiles * _level_scale(interp_tiles.dtype)).long().flatten(-2, -1)
flatten_interp_tiles = flatten_interp_tiles.unsqueeze(-3).expand(num_imgs, gh, gw, 4, c, th * tw)
preinterp_tiles_equalized = (
torch.gather(mapped_luts, 5, flatten_interp_tiles) # B x GH x GW x 4 x C x TH x TW
@@ -456,7 +458,7 @@ def _equalize_clahe_odd_tiles(imgs: torch.Tensor, luts: torch.Tensor, tile_size:
wx = torch.where((x < 0) | (x > grid_w - 1), 0, wx).to(imgs.dtype)
luts = luts.to(imgs.dtype)
- pixel_bins = (imgs * 255).long()
+ pixel_bins = (imgs * _level_scale(imgs.dtype)).long()
batch_idx = torch.arange(batch_size, device=imgs.device).view(batch_size, 1, 1, 1)
channel_idx = torch.arange(channels, device=imgs.device).view(1, channels, 1, 1)
rows0, rows1 = y0.view(1, 1, height, 1), y1.view(1, 1, height, 1)
@@ -526,7 +528,10 @@ 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. 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;
+ level ``(x * 255).long()`` in the input dtype, as OpenCV counts and reads one level; both paths read
+ the lookup at that level. In float32 and float64 the 255 is raised by four float32 epsilons, relative, as in
+ :func:`kornia.enhance.equalize`, so ``k / 255`` reads level ``k`` even when its division was rounded a
+ unit low, as dividing by 255 on CUDA leaves it.
``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
@@ -561,13 +566,14 @@ def _equalize_clahe(
if grid_size[0] <= 0 or grid_size[1] <= 0:
raise ValueError(f"Input grid_size elements must be positive. Got {grid_size}")
- # The tile LUTs are gathered below with ``(interp_tiles * 255).long()``, which is in bounds
- # only for values in (-1/255, 256/255). Check that domain without ``.item()``, so there is no
+ # The tile LUTs are gathered below with ``(x * _level_scale(x.dtype)).long()``, which is in bounds
+ # only while that product 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 ``_check_async``). Inputs the lookup can index are unchanged. The check keeps the index in
# bounds, so it runs with checks disabled too: a compiled CPU gather out of range terminates the process.
+ levels = input * _level_scale(input.dtype)
_check_async(
- ((input * 255.0 > -1.0) & (input * 255.0 < 256.0)).all(),
+ ((levels > -1.0) & (levels < 256.0)).all(),
"equalize_clahe expects input values in [0, 1]. Scale the image into that range first, "
"for example image / 255.0 for 8-bit data.",
guard=True,
diff --git a/tests/enhance/test_adjust.py b/tests/enhance/test_adjust.py
index 6a48142bf..7565f4253 100644
--- a/tests/enhance/test_adjust.py
+++ b/tests/enhance/test_adjust.py
@@ -1400,10 +1400,11 @@ class TestEqualize3D(BaseTester):
_sync(kornia.enhance.equalize3d(x).device)
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.
+ # As the docstring states: the lookup step is an integer division by 255. Such a volume comes back as it is,
+ # not as (x * 255) / 255, which can be a unit in the last place off.
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)
+ assert torch.equal(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):
@@ -1926,7 +1927,8 @@ def _equalize_reference(input):
hist.cumsum(0) + torch.div(step, 2, rounding_mode="trunc"), step.clamp(min=1), rounding_mode="trunc"
)
lut = torch.cat([torch.zeros_like(lut[:1]), lut[:-1]]).clamp(0, 255).to(input.dtype)
- outputs.append(torch.where(step == 0, scaled, lut[scaled.long()]) / 255.0)
+ # A plane whose step is 0 comes back as it is.
+ outputs.append(torch.where(step == 0, plane, lut[scaled.long()] / 255.0))
return torch.stack(outputs).reshape(input.shape)
diff --git a/tests/enhance/test_conventions_enhance.py b/tests/enhance/test_conventions_enhance.py
index 4d9f6bf95..fcd92004e 100644
--- a/tests/enhance/test_conventions_enhance.py
+++ b/tests/enhance/test_conventions_enhance.py
@@ -15,6 +15,8 @@
# limitations under the License.
#
+import math
+
import pytest
import torch
@@ -283,7 +285,8 @@ class TestEnhanceConventions(BaseTester):
# 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).
+ # count it in floor(256 x), one bin above the entry it reads for every value in [k/256, k/255) (#6181). In float32
+ # and float64 the 255 is raised by four float32 epsilons, relative, so k / 255 rounded a unit low still reads k.
@pytest.mark.parametrize(
("op", "shape"),
[
@@ -296,7 +299,8 @@ class TestEnhanceConventions(BaseTester):
)
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
+ scale = 255 * (1 + 2**-21) if dtype in (torch.float32, torch.float64) else 255
+ levels = (image * scale).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
@@ -322,6 +326,42 @@ class TestEnhanceConventions(BaseTester):
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)
+ # An 8-bit image normalized as levels / 255 reads each pixel at its level k, however the division was rounded.
+ # CUDA divides by a Python number by multiplying with its rounded reciprocal, which leaves 24 of the 256 float64
+ # levels one unit in the last place below k / 255, and so does x * (1 / 255) on any device; (x * 255).long() read
+ # them as k - 1, so equalize of a random 8-bit image on CUDA differed from the CPU by up to 2 levels on 8% of the
+ # pixels, CLAHE by up to 16, and posterize(x, 7) by 2. In half precision a unit below k / 255 is up to an eighth of
+ # a level (float16) or a whole level (bfloat16), another value, so only float32 and float64 also try that one.
+ _LEVEL_READERS = {
+ "equalize": (kornia.enhance.equalize, (1, 1, 32, 32)),
+ "equalize3d": (kornia.enhance.equalize3d, (1, 1, 4, 16, 16)),
+ "clahe_even_tiles": (lambda x: kornia.enhance.equalize_clahe(x, 40.0, (2, 2)), (1, 1, 32, 32)),
+ "clahe_odd_tiles": (lambda x: kornia.enhance.equalize_clahe(x, 40.0, (2, 2)), (1, 1, 30, 30)),
+ "posterize_7": (lambda x: kornia.enhance.posterize(x, 7), (1, 1, 32, 32)),
+ "posterize_4": (lambda x: kornia.enhance.posterize(x, 4), (1, 1, 32, 32)),
+ }
+
+ @pytest.mark.parametrize("op", sorted(_LEVEL_READERS))
+ def test_convention_8bit_level_reads_k_however_k_over_255_was_rounded(self, op, device, dtype):
+ fn, shape = self._LEVEL_READERS[op]
+ levels = torch.arange(math.prod(shape), device=device).remainder(256).reshape(shape)
+ reference = (levels.cpu().double() / 255).to(dtype) # k / 255 rounded once to the dtype, on the CPU
+ variants = {
+ "divided on the device": levels.to(dtype) / 255,
+ "multiplied by 1 / 255": levels.to(dtype) * (1 / 255),
+ }
+ if dtype in (torch.float32, torch.float64):
+ variants["one unit below"] = torch.nextafter(reference, torch.zeros_like(reference)).to(device)
+ expected = fn(reference.to(device))
+ for name, image in variants.items():
+ assert torch.equal(fn(image), expected), name
+
+ def test_convention_equalize_of_every_8bit_level_once_is_the_identity(self, device, dtype):
+ # Every level occurring equally often gives the identity table, so the output names the level each pixel read.
+ levels = torch.arange(1024, device=device).remainder(256).reshape(1, 1, 32, 32)
+ out = kornia.enhance.equalize(levels.to(dtype) / 255)
+ assert torch.equal((out.cpu().double() * 255).round(), levels.cpu().double())
+
# 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.py
index 00a4d8abd..ecd71e5f3 100644
--- a/tests/enhance/test_equalization.py
+++ b/tests/enhance/test_equalization.py
@@ -35,6 +35,7 @@ def _clahe_interpolation_reference(img, luts, tile_size):
# these centres pixel by pixel, independently of production's half-tile indexing.
values = img.detach().cpu().double()
tables = luts.detach().cpu().double()
+ scale = 255 * (1 + 2**-21) if img.dtype in (torch.float32, torch.float64) else 255
expected = torch.zeros_like(values)
gh, gw = tables.shape[1:3]
for y in range(values.shape[-2]):
@@ -45,8 +46,9 @@ def _clahe_interpolation_reference(img, luts, tile_size):
fx = (x + 0.5) / tile_size[1] - 0.5
x0 = math.floor(fx)
ax = fx - x0
- # Preserve the input dtype's lookup quantization; this reference tests only interpolation.
- index = (img[..., y, x] * 255).long().cpu().unsqueeze(-1)
+ # Preserve the input dtype's lookup quantization, the 8-bit level with 255 raised by four float32
+ # epsilons in float32 and float64; this reference tests only interpolation.
+ index = (img[..., y, x] * scale).long().cpu().unsqueeze(-1)
for row, wy in [(y0, 1 - ay), (y0 + 1, ay)]:
for col, wx in [(x0, 1 - ax), (x0 + 1, ax)]:
lut = tables[:, min(max(row, 0), gh - 1), min(max(col, 0), gw - 1)]
@@ -575,9 +577,11 @@ class TestEqualization(BaseTester):
clip = torch.tensor([40.0], device=device) if clip_as_tensor else 40.0
luts = enhance.equalization._compute_luts(tiles, clip=clip)
count_dtype = torch.float64 if dtype == torch.float64 else torch.float32
- # 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
+ # A pixel is counted in the level it reads, (x * 255).long() in the image dtype, with the 255 raised by four
+ # float32 epsilons, relative, in float32 and float64; float16 can round 255 x to another level than float32
+ # does, so the reference tiles hold those levels.
+ scale = 255 * (1 + 2**-21) if dtype in (torch.float32, torch.float64) else 255
+ levels = (tiles * scale).long().to(count_dtype) / 255
expected = enhance.equalization._compute_luts(levels, clip=clip)
assert luts.dtype == dtype
assert torch.equal(luts.to(count_dtype), expected)
@@ -587,8 +591,10 @@ class TestEqualization(BaseTester):
@pytest.mark.parametrize("clip_limit", [40.0, 300.0])
@pytest.mark.parametrize("slow_and_differentiable", [False, True])
def test_clahe_half_precision_tile_of_65536_pixels(self, slow_and_differentiable, clip_limit, device, dtype):
- torch.manual_seed(5374)
- img = torch.rand(1, 1, 256, 256, device=device, dtype=dtype)
+ # Drawn on the CPU, so every device equalizes the same values. The level a pixel reads is computed in its own
+ # dtype: a float32 value just outside the 2**-21 margin below a level boundary can round into it and read the
+ # level above the one float64 reads. About 3 in 10 uniform images this size hold such a value; this one none.
+ img = torch.rand(1, 1, 256, 256, dtype=dtype, generator=torch.Generator().manual_seed(5374)).to(device)
out = enhance.equalize_clahe(img, clip_limit, (1, 1), slow_and_differentiable)
assert out.dtype == dtype
assert torch.isfinite(out).all()