Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

:construction_worker: Fix clahe differentiability and tests (#1356)

Dmytro Mishkin93c0bdda743f
diff --git a/kornia/enhance/equalization.py b/kornia/enhance/equalization.py
index 0f5251274..b025379fe 100644
--- a/kornia/enhance/equalization.py
+++ b/kornia/enhance/equalization.py
@@ -149,9 +149,10 @@ def _compute_luts(
max_val: float = max(clip * pixels // num_bins, 1)
histos.clamp_(max=max_val)
clipped: torch.Tensor = pixels - histos.sum(1)
- redist: torch.Tensor = clipped // num_bins
+ remainder: torch.Tensor = torch.remainder(clipped, num_bins)
+ redist: torch.Tensor = (clipped - remainder) / num_bins
histos += redist[None].transpose(0, 1)
- residual: torch.Tensor = clipped - redist * num_bins
+ residual: torch.Tensor = remainder
# trick to avoid using a loop to assign the residual
v_range: torch.Tensor = torch.arange(num_bins, device=histos.device)
mat_range: torch.Tensor = v_range.repeat(histos.shape[0], 1)
@@ -159,7 +160,9 @@ def _compute_luts(
lut_scale: float = (num_bins - 1) / pixels
luts: torch.Tensor = torch.cumsum(histos, 1) * lut_scale
- luts = luts.clamp(0, num_bins - 1).floor() # to get the same values as converting to int maintaining the type
+ luts = luts.clamp(0, num_bins - 1)
+ if not diff:
+ luts = luts.floor() # to get the same values as converting to int maintaining the type
luts = luts.view((b, gh, gw, c, num_bins))
return luts
@@ -299,7 +302,10 @@ def _compute_equalized_tiles(interp_tiles: torch.Tensor, luts: torch.Tensor) ->
@perform_keep_shape_image
-def equalize_clahe(input: torch.Tensor, clip_limit: float = 40.0, grid_size: Tuple[int, int] = (8, 8)) -> torch.Tensor:
+def equalize_clahe(input: torch.Tensor,
+ clip_limit: float = 40.0,
+ grid_size: Tuple[int, int] = (8, 8),
+ slow_and_differentiable: bool = False) -> torch.Tensor:
r"""Apply clahe equalization on the input tensor.
.. image:: _static/img/equalize_clahe.png
@@ -310,6 +316,7 @@ def equalize_clahe(input: torch.Tensor, clip_limit: float = 40.0, grid_size: Tup
input: images tensor to equalize with values in the range [0, 1] and shape :math:`(*, C, H, W)`.
clip_limit: threshold value for contrast limiting. If 0 clipping is disabled.
grid_size: number of tiles to be cropped in each direction (GH, GW).
+ slow_and_differentiable: flag to select implementation
Returns:
Equalized image or images with shape as the input.
@@ -350,7 +357,7 @@ def equalize_clahe(input: torch.Tensor, clip_limit: float = 40.0, grid_size: Tup
hist_tiles, img_padded = _compute_tiles(imgs, grid_size, True)
tile_size: Tuple[int, int] = (hist_tiles.shape[-2], hist_tiles.shape[-1])
interp_tiles: torch.Tensor = _compute_interpolation_tiles(img_padded, tile_size) # B x 2GH x 2GW x C x TH/2 x TW/2
- luts: torch.Tensor = _compute_luts(hist_tiles, clip=clip_limit) # B x GH x GW x C x B
+ luts: torch.Tensor = _compute_luts(hist_tiles, clip=clip_limit, diff=slow_and_differentiable) # B x GH x GW x C x B
equalized_tiles: torch.Tensor = _compute_equalized_tiles(interp_tiles, luts) # B x 2GH x 2GW x C x TH/2 x TW/2
# reconstruct the images form the tiles
diff --git a/test/enhance/test_equalization.py b/test/enhance/test_equalization.py
index 7775cfd58..aaf9253d6 100644
--- a/test/enhance/test_equalization.py
+++ b/test/enhance/test_equalization.py
@@ -4,7 +4,7 @@ import pytest
import torch
from torch.autograd import gradcheck
-from kornia import enhance
+from kornia import enhance, rotate
from kornia.testing import assert_close, BaseTester, tensor_to_gradcheck_var
@@ -68,15 +68,21 @@ class TestEqualization(BaseTester):
with pytest.raises(TypeError):
enhance.equalize_clahe([1, 2, 3])
- @pytest.mark.xfail(
- raises=RuntimeError,
- reason="Sometimes generates the error: 'Numerical gradient for function expected to be zero'",
- )
def test_gradcheck(self, device, dtype):
- bs, channels, height, width = 1, 1, 6, 6
+ torch.random.manual_seed(4)
+ bs, channels, height, width = 1, 1, 11, 11
inputs = torch.rand(bs, channels, height, width, device=device, dtype=dtype)
inputs = tensor_to_gradcheck_var(inputs)
- assert gradcheck(enhance.equalize_clahe, (inputs, 40.0, (2, 2)), raise_exception=True)
+
+ def grad_rot(input, a, b, c):
+ rot = rotate(input, torch.tensor(30.,
+ dtype=input.dtype,
+ device=device))
+ return enhance.equalize_clahe(rot, a, b, c)
+ assert gradcheck(grad_rot,
+ (inputs, 40.0, (2, 2), True),
+ nondet_tol=1e-4,
+ raise_exception=True)
@pytest.mark.skip(reason="args and kwargs in decorator")
def test_jit(self, device, dtype):
@@ -186,40 +192,61 @@ class TestEqualization(BaseTester):
clip_limit: float = 2.0
grid_size: Tuple = (8, 8)
res = enhance.equalize_clahe(img, clip_limit=clip_limit, grid_size=grid_size)
+ res_diff = enhance.equalize_clahe(img,
+ clip_limit=clip_limit,
+ grid_size=grid_size,
+ slow_and_differentiable=True)
# NOTE: for next versions we need to improve the computation of the LUT
# and test with a better image
+ expected = torch.tensor([[[0.1216,
+ 0.8745,
+ 0.9373,
+ 0.9163,
+ 0.8745,
+ 0.8745,
+ 0.9373,
+ 0.8745,
+ 0.8745,
+ 0.8118,
+ 0.9373,
+ 0.8745,
+ 0.8745,
+ 0.8118,
+ 0.8745,
+ 0.8745,
+ 0.8327,
+ 0.8118,
+ 0.8745,
+ 1.0000]]], dtype=res.dtype, device=res.device)
+ exp_diff = torch.tensor([[[0.1250,
+ 0.8752,
+ 0.9042,
+ 0.9167,
+ 0.8401,
+ 0.8852,
+ 0.9302,
+ 0.9120,
+ 0.8750,
+ 0.8370,
+ 0.9620,
+ 0.9077,
+ 0.8750,
+ 0.8754,
+ 0.9204,
+ 0.9167,
+ 0.8370,
+ 0.8806,
+ 0.9096,
+ 1.0000]]], dtype=res.dtype, device=res.device)
assert torch.allclose(
res[..., 0, :],
- torch.tensor(
- [
- [
- [
- 0.1216,
- 0.8745,
- 0.9373,
- 0.9163,
- 0.8745,
- 0.8745,
- 0.9373,
- 0.8745,
- 0.8745,
- 0.8118,
- 0.9373,
- 0.8745,
- 0.8745,
- 0.8118,
- 0.8745,
- 0.8745,
- 0.8327,
- 0.8118,
- 0.8745,
- 1.0000,
- ]
- ]
- ],
- dtype=res.dtype,
- device=res.device,
- ),
+ expected,
+ atol=1e-04,
+ rtol=1e-04,
+ )
+ assert torch.allclose(
+ res_diff[..., 0, :],
+ exp_diff,
atol=1e-04,
rtol=1e-04,
)