π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Fix CLAHE output for odd tile sizes (#5845)
Lakshay Aggarwal265354b6d352
diff --git a/changelog.d/5716.breaking.md b/changelog.d/5716.breaking.mdindex 35d41bfd5..342a61704 100644--- a/changelog.d/5716.breaking.md+++ b/changelog.d/5716.breaking.md@@ -1 +1 @@-`equalize_clahe` and `RandomClahe` now blend neighbouring tile lookup tables with weight steps of `1 / tile_size`, instead of `1 / (tile_size - 1)`, anchored at each tile's actual centre. This changes interpolated output values in both the fast and differentiable paths. Kornia intentionally anchors the blend half a pixel before OpenCV/scikit-image's historical phase to preserve flip symmetry on unpadded grids. For the same tiles and lookup tables, the phase difference is at most half an interpolation step per axis; exact `cv2.createCLAHE` parity is not the contract. On the images we measured with an 8 x 8 grid and even tiles (64 x 80 to 512 x 512, clip limits 2 and 40), the largest difference from `cv2.createCLAHE` fell to between one half and two thirds of what it was (21 instead of 39 gray levels on a smooth 64 x 80 image at clip limit 40, 3 instead of 5 on the 512 x 512 `camera` image), while the mean difference stayed close to what it was (7.0 instead of 7.6 and 0.54 instead of 0.57 levels), because the half-pixel offset from OpenCV's phase changes every blended pixel. Border regions still clamp to the nearest tile along the border axis. LUT calculation and quantization are unchanged; Kornia's existing even-tile sizing and padding can cause additional differences from OpenCV.+`equalize_clahe` and `RandomClahe` now blend neighbouring tile lookup tables with weight steps of `1 / tile_size`, instead of `1 / (tile_size - 1)`, anchored at each tile's actual centre. This changes interpolated output values in both the fast and differentiable paths. Kornia intentionally anchors the blend half a pixel before OpenCV/scikit-image's historical phase to preserve flip symmetry on unpadded grids. For the same tiles and lookup tables, the phase difference is at most half an interpolation step per axis; exact `cv2.createCLAHE` parity is not the contract. On the images we measured with an 8 x 8 grid and even tiles (64 x 80 to 512 x 512, clip limits 2 and 40), the largest difference from `cv2.createCLAHE` fell to between one half and two thirds of what it was (21 instead of 39 gray levels on a smooth 64 x 80 image at clip limit 40, 3 instead of 5 on the 512 x 512 `camera` image), while the mean difference stayed close to what it was (7.0 instead of 7.6 and 0.54 instead of 0.57 levels), because the half-pixel offset from OpenCV's phase changes every blended pixel. Border regions still clamp to the nearest tile along the border axis. LUT calculation and quantization are unchanged.diff --git a/changelog.d/5845.breaking.md b/changelog.d/5845.breaking.mdnew file mode 100644index 000000000..0187e0a91--- /dev/null+++ b/changelog.d/5845.breaking.md@@ -0,0 +1 @@+`equalize_clahe` and `RandomClahe` now use tiles of ceil(H / grid_size[0]) by ceil(W / grid_size[1]) pixels, odd or even, and reflect-pad only as needed to complete the grid. Previously, odd tile sizes were rounded up to the next even size and the image was padded to fit, even when the grid divided it. For example, an 8 x 8 grid on a 72 x 88 image used 10 x 12 tiles over an 80 x 96 padded image, shifting tile boundaries and changing output values. These are OpenCV's tiles when the grid divides both image axes or neither. When it divides only one, OpenCV also pads that axis, by one pixel per tile, and Kornia does not, so on such images the difference from `cv2.createCLAHE` can grow. On the smooth images we measured with an 8 x 8 grid at clip limit 2, the mean / max difference from `cv2.createCLAHE` fell from 8.0 / 47 to 3.2 / 10 gray levels at 72 x 88 and from 18.8 / 82 to 1.0 / 3 at 100 x 150, and odd tiles on a grid that divides the image are now flip-symmetric.diff --git a/kornia/enhance/equalization.py b/kornia/enhance/equalization.pyindex 741210539..65245d16a 100644--- a/kornia/enhance/equalization.py+++ b/kornia/enhance/equalization.py@@ -52,6 +52,13 @@ def _compute_tiles(# compute stride and kernel sizeh, w = batch.shape[-2:]+ if even_tile_size and (h <= grid_size[0] or w <= grid_size[1]):+ raise ValueError(+ "Cannot compute tiles on the image according to the given grid size. "+ f"Got image size ({h}, {w}) and grid size {tuple(grid_size)}. "+ f"The smallest image this grid admits is ({grid_size[0] + 1}, {grid_size[1] + 1})."+ )+kernel_vert: int = math.ceil(h / grid_size[0])kernel_horz: int = math.ceil(w / grid_size[1])@@ -408,6 +415,48 @@ def _compute_equalized_tiles(interp_tiles: torch.Tensor, luts: torch.Tensor) ->return tiles_equalized.div(255.0)+def _equalize_clahe_odd_tiles(imgs: torch.Tensor, luts: torch.Tensor, tile_size: Tuple[int, int]) -> torch.Tensor:+ """Equalize odd-sized CLAHE tiles by interpolating LUTs at tile centres."""+ batch_size, channels, height, width = imgs.shape+ grid_h, grid_w = luts.shape[1:3]+ tile_h, tile_w = tile_size++ coord_dtype = torch.float64 if imgs.dtype == torch.float64 else torch.float32+ y = (torch.arange(height, device=imgs.device, dtype=coord_dtype) - (tile_h - 1) / 2) / tile_h+ x = (torch.arange(width, device=imgs.device, dtype=coord_dtype) - (tile_w - 1) / 2) / tile_w++ y_floor = y.floor()+ x_floor = x.floor()+ y0 = y_floor.long().clamp(0, grid_h - 1)+ y1 = (y_floor.long() + 1).clamp(0, grid_h - 1)+ x0 = x_floor.long().clamp(0, grid_w - 1)+ x1 = (x_floor.long() + 1).clamp(0, grid_w - 1)++ wy = (y - y_floor).clamp(0, 1)+ wx = (x - x_floor).clamp(0, 1)+ wy = torch.where((y < 0) | (y > grid_h - 1), 0, wy).to(imgs.dtype)+ wx = torch.where((x < 0) | (x > grid_w - 1), 0, wx).to(imgs.dtype)++ luts = luts.to(imgs.dtype)+ pixel_bins = (imgs * 255).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)+ cols0, cols1 = x0.view(1, 1, 1, width), x1.view(1, 1, 1, width)++ top_left = luts[batch_idx, rows0, cols0, channel_idx, pixel_bins]+ top_right = luts[batch_idx, rows0, cols1, channel_idx, pixel_bins]+ bottom_left = luts[batch_idx, rows1, cols0, channel_idx, pixel_bins]+ bottom_right = luts[batch_idx, rows1, cols1, channel_idx, pixel_bins]++ wy = wy.view(1, 1, height, 1)+ wx = wx.view(1, 1, 1, width)++ top = top_right + (top_left - top_right) * (1 - wx)+ bottom = bottom_right + (bottom_left - bottom_right) * (1 - wx)+ return (top + (bottom - top) * wy) / 255.0++@perform_keep_shape_imagedef equalize_clahe(input: torch.Tensor,@@ -425,12 +474,15 @@ def equalize_clahe(.. image:: _static/img/equalize_clahe.pngNOTE: The fast path uses OpenCV-style LUT calculation and round-to-nearest quantization.- Both paths blend LUTs with weight steps of ``1 / tile_size``, anchored at each tile's actual centre,- with border LUTs clamped. This is half a pixel before OpenCV/scikit-image's historical phase:- Kornia intentionally uses ``(p + 0.5) / tile_size - 0.5`` to preserve flip symmetry on unpadded grids.- For the same tiles and LUTs, the phase difference is at most half an interpolation step per axis;- exact ``cv2.createCLAHE`` parity is not the contract. Tiles are rounded up to even sizes and reflect-padded,- which can differ from OpenCV's tile/padding convention, and output values are not rounded to 8-bit integers.+ Tiles are ``ceil(H / grid_size[0])`` by ``ceil(W / grid_size[1])`` pixels, odd or even, and the image is+ reflect-padded at its end only along an axis the grid does not divide. OpenCV uses the same tiles when the+ grid divides both axes or neither. When it divides only one, OpenCV pads that axis too, by one pixel per+ tile; Kornia tiles each axis on its own and does not. Both paths blend LUTs with weight steps of+ ``1 / tile_size``, anchored at each tile's actual centre, with border LUTs clamped. This is half a pixel+ before OpenCV/scikit-image's historical phase: Kornia intentionally uses ``(p + 0.5) / tile_size - 0.5``+ to preserve flip symmetry on unpadded grids. For the same tiles and LUTs, the phase difference is at most+ half an interpolation step per axis; exact ``cv2.createCLAHE`` parity is not the contract, and output+ values are not rounded to 8-bit integers.Args:input: images tensor to equalize with values in the range [0, 1] and shape :math:`(*, C, H, W)`.@@ -498,22 +550,32 @@ def _equalize_clahe(imgs: torch.Tensor = input # B x C x H x W- # hist_tiles: torch.Tensor # B x GH x GW x C x TH x TW # not supported by JIT- # img_padded: torch.Tensor # B x C x H' x W' # not supported by JIT- # the size of the tiles must be even in order to divide them into 4 tiles for the interpolation- hist_tiles, img_padded = _compute_tiles(imgs, grid_size, True)+ height, width = imgs.shape[-2:]+ grid_h, grid_w = grid_size+ if height <= grid_h or width <= grid_w:+ raise ValueError(+ "Cannot compute tiles on the image according to the given grid size. "+ f"Got image size ({height}, {width}) and grid size {tuple(grid_size)}. "+ f"The smallest image this grid admits is ({grid_h + 1}, {grid_w + 1})."+ )++ natural_tile_h = -(-height // grid_h)+ natural_tile_w = -(-width // grid_w)+ use_odd_tiles = natural_tile_h % 2 == 1 or natural_tile_w % 2 == 1++ hist_tiles, img_padded = _compute_tiles(imgs, grid_size, not use_odd_tiles)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, diff=slow_and_differentiable- ) # B x GH x GW x C x 256- 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- # try permute + contiguous + view- eq_imgs: torch.Tensor = equalized_tiles.permute(0, 3, 1, 4, 2, 5).reshape_as(img_padded)+ luts: torch.Tensor = _compute_luts(hist_tiles, clip=clip_limit, diff=slow_and_differentiable)++ if use_odd_tiles:+ eq_imgs = _equalize_clahe_odd_tiles(img_padded, luts, tile_size)+ else:+ interp_tiles = _compute_interpolation_tiles(img_padded, tile_size)+ equalized_tiles = _compute_equalized_tiles(interp_tiles, luts)+ eq_imgs = equalized_tiles.permute(0, 3, 1, 4, 2, 5).reshape_as(img_padded)+h, w = imgs.shape[-2:]- eq_imgs = eq_imgs[..., :h, :w] # crop imgs if they were padded+ eq_imgs = eq_imgs[..., :h, :w]# remove batch if the input was not in batch formif input.dim() != eq_imgs.dim():diff --git a/tests/augmentation/test_conventions_intensity_values.py b/tests/augmentation/test_conventions_intensity_values.pyindex 9680019f9..1f3cb5a62 100644--- a/tests/augmentation/test_conventions_intensity_values.py+++ b/tests/augmentation/test_conventions_intensity_values.py@@ -1367,19 +1367,20 @@ class TestIntensityColourConventions(BaseTester):with pytest.raises(RuntimeError, match=r"equalize_clahe expects input values in \[0, 1\]"):_sync(K.RandomClahe(p=1.0)(image).device)- # Issue #2531: each axis of `grid_size` is tiled on its own and padded up to a whole number of tiles,- # so a grid works whether or not it divides the image, and an exactly dividing grid can still pad (the- # tile is rounded up to an even size). The padding is reflect at the end of each axis, so the- # pre-padded image cropped back reproduces the output bitwise.+ # Issue #2531: each axis of `grid_size` is tiled on its own, with tiles of ceil(size / grid) pixels, odd or+ # even (#5812), so a grid works whether or not it divides the image, and only an axis the grid does not+ # divide is padded. The padding is reflect at the end of each axis, so the pre-padded image cropped back+ # reproduces the output bitwise.@pytest.mark.parametrize(("grid_size", "size", "pad"),[((3, 3), 10, (2, 2)),- ((4, 4), 20, (4, 4)),+ ((4, 4), 18, (2, 2)),+ ((4, 4), 20, (0, 0)),((5, 5), 20, (0, 0)),- ((4, 5), 20, (4, 0)),+ ((4, 5), 18, (2, 2)),((3, 5), 30, (0, 0)),- ((1, 2), 10, (0, 2)),+ ((1, 2), 11, (0, 1)),],)def test_convention_random_clahe_grid_pads_each_axis_to_whole_tiles_2531(self, device, dtype, grid_size, size, pad):diff --git a/tests/enhance/test_equalization.py b/tests/enhance/test_equalization.pyindex b5205b9ae..8543aa849 100644--- a/tests/enhance/test_equalization.py+++ b/tests/enhance/test_equalization.py@@ -205,8 +205,8 @@ class TestEqualization(BaseTester):[((4, 10), (8, 6), (5, 4)), ((10, 3), (5, 6), (3, 4))],)def test_compute_tiles_odd_tiles_names_its_own_limit_4783(self, size, grid, smallest):- # equalize_clahe always asks for even tiles; with odd ones an axis only has to exceed half its- # grid size, and the limit the message names must be accepted.+ # equalize_clahe rejects an axis no larger than its grid before it tiles; _compute_tiles called with odd+ # tiles only needs an axis above half its grid size, and the limit the message names must be accepted.with pytest.raises(ValueError) as errinfo:_compute_tiles(torch.rand(1, 1, *size), grid, even_tile_size=False)assert f"smallest image this grid admits is {smallest}" in str(errinfo.value)@@ -388,115 +388,57 @@ class TestEqualization(BaseTester):clip_limit: float = 0.0grid_size: Tuple = (8, 8)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.251,- 0.502,- 0.6554,- 0.625,- 0.5319,- 0.5642,- 0.6554,- 0.4681,- 0.5319,- 0.3446,- 0.6554,- 0.4681,- 0.5319,- 0.3446,- 0.4392,- 0.4681,- 0.375,- 0.3446,- 0.5328,- 1.0,- ]- ]- ],- dtype=res.dtype,- device=res.device,- ),- low_tolerance=True,- )++ tiles, padded = _compute_tiles(img, grid_size, even_tile_size=False)+ luts = enhance.equalization._compute_luts(tiles, clip=clip_limit, diff=False)+ expected = _clahe_interpolation_reference(padded, luts, tiles.shape[-2:])+ expected = expected[..., : img.shape[-2], : img.shape[-1]]++ self.assert_close(res, expected)def test_clahe(self, img):clip_limit: float = 2.0grid_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- # Each 4 x 4 tile holds 4 columns of one value each, so with the clip limit of 1 count per bin the 12- # clipped counts are spread over every 21st bin, as in OpenCV, and the gradient keeps its range; piling- # them into the first 12 bins mapped every pixel but the first above 0.81.- expected = torch.tensor(- [- [- [- 0.1255,- 0.1882,- 0.2902,- 0.2824,- 0.3216,- 0.3922,- 0.4157,- 0.4314,- 0.5083,- 0.4623,- 0.6005,- 0.6172,- 0.6314,- 0.6471,- 0.6706,- 0.7412,- 0.7804,- 0.7725,- 0.8824,- 1.0,- ]- ]- ],+ res_diff = enhance.equalize_clahe(+ img,+ clip_limit=clip_limit,+ grid_size=grid_size,+ slow_and_differentiable=True,+ )++ tiles, padded = _compute_tiles(img, grid_size, even_tile_size=False)++ luts = enhance.equalization._compute_luts(tiles, clip=clip_limit, diff=False)+ expected = _clahe_interpolation_reference(padded, luts, tiles.shape[-2:])+ expected = expected[..., : img.shape[-2], : img.shape[-1]]+ self.assert_close(res, expected)++ luts_diff = enhance.equalization._compute_luts(tiles, clip=clip_limit, diff=True)+ expected_diff = _clahe_interpolation_reference(padded, luts_diff, tiles.shape[-2:])+ expected_diff = expected_diff[..., : img.shape[-2], : img.shape[-1]]+ self.assert_close(res_diff, expected_diff)++ # The references above take their lookup tables from _compute_luts, so they cannot see a wrong table: pin+ # the first row as well. Each 3 x 3 tile holds 3 columns of one value each, so with the clip limit of 1+ # count per bin the 6 clipped counts are spread over every 42nd bin, as in OpenCV, and the gradient keeps+ # 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],dtype=res.dtype,device=res.device,)- exp_diff = torch.tensor(- [- [- [- 0.125,- 0.1877,- 0.2599,- 0.2995,- 0.3006,- 0.3492,- 0.4077,- 0.4644,- 0.4662,- 0.4893,- 0.6152,- 0.5853,- 0.6513,- 0.6471,- 0.7116,- 0.7706,- 0.7431,- 0.8321,- 0.8574,- 1.0,- ]- ]- ],+ expected_row_diff = torch.tensor(+ [0.2222, 0.3335, 0.2841, 0.3087, 0.3545, 0.4586, 0.388, 0.4, 0.6001, 0.479]+ + [0.6712, 0.6155, 0.6411, 0.6371, 0.7207, 0.7493, 0.6889, 0.8889, 0.8387, 1.0],dtype=res.dtype,device=res.device,)- self.assert_close(res[..., 0, :], expected, low_tolerance=True)- self.assert_close(res_diff[..., 0, :], exp_diff, low_tolerance=True)+ self.assert_close(res[0, 0, 0], expected_row, low_tolerance=True)+ self.assert_close(res_diff[0, 0, 0], expected_row_diff, low_tolerance=True)@pytest.mark.parametrize("count, expected_level", [(100, 100), (128, 128)])@pytest.mark.parametrize("clip_as_tensor", [False, True])@@ -631,6 +573,90 @@ class TestEqualization(BaseTester):out_t = enhance.equalize_clahe(img.transpose(-2, -1), 40.0, grid_size[::-1], slow_and_differentiable)self.assert_close(out_t, out.transpose(-2, -1))+ @pytest.mark.parametrize(+ ("size", "grid", "expected_tile", "expected_padded"),+ [+ ((13, 15), (2, 3), (7, 5), (14, 15)),+ ((100, 150), (8, 8), (13, 19), (104, 152)),+ ],+ )+ def test_clahe_ceil_tile_sizes_for_non_divisible_images_5812(self, size, grid, expected_tile, expected_padded):+ img = torch.rand(1, 1, *size)+ tiles, padded = _compute_tiles(img, grid)++ assert tuple(tiles.shape[-2:]) == expected_tile+ assert tuple(padded.shape[-2:]) == expected_padded++ @pytest.mark.parametrize("slow_and_differentiable", [False, True])+ def test_clahe_odd_tile_sizes(self, slow_and_differentiable, device):+ # Regression test: odd 9 x 11 tiles must not be expanded to 10 x 12.+ torch.manual_seed(5812)+ img = torch.randint(0, 256, (1, 1, 72, 88), dtype=torch.uint8).float().div(255.0).to(device)+ grid_size = (8, 8)+ clip_limit = 2.0++ out = enhance.equalize_clahe(+ img,+ clip_limit=clip_limit,+ grid_size=grid_size,+ slow_and_differentiable=slow_and_differentiable,+ )++ tiles, padded = _compute_tiles(img, grid_size, even_tile_size=False)+ luts = enhance.equalization._compute_luts(tiles, clip=clip_limit, diff=slow_and_differentiable)+ expected = _clahe_interpolation_reference(padded, luts, tiles.shape[-2:])+ expected = expected[..., : img.shape[-2], : img.shape[-1]]+ self.assert_close(out, expected)++ out_t = enhance.equalize_clahe(+ img.transpose(-2, -1),+ clip_limit=clip_limit,+ grid_size=grid_size,+ slow_and_differentiable=slow_and_differentiable,+ ).transpose(-2, -1)+ self.assert_close(out, out_t)++ @pytest.mark.parametrize("slow_and_differentiable", [False, True])+ @pytest.mark.parametrize(+ ("size", "grid", "tile"),+ [+ ((36, 44), (4, 4), (9, 11)),+ ((27, 40), (3, 4), (9, 10)),+ ((13, 15), (2, 3), (7, 5)),+ ((25, 23), (2, 2), (13, 12)),+ ((16, 25), (2, 4), (8, 7)),+ ],+ )+ def test_clahe_tiles_are_ceil_n_over_g_5812(self, size, grid, tile, slow_and_differentiable, device, dtype):+ # Tiles are ceil(n / g) pixels, odd or even, on each axis: odd, mixed, and three grids that do not divide+ # the image and pad it, two of them along one axis only, where OpenCV would also pad the axis the grid+ # divides. Two samples and two channels, each blended from its own lookup tables.+ torch.manual_seed(5812)+ img = torch.rand(2, 2, *size, device=device, dtype=dtype)+ tiles, padded = _compute_tiles(img, grid)+ assert tuple(tiles.shape[-2:]) == tile+ luts = enhance.equalization._compute_luts(tiles, clip=2.0, diff=slow_and_differentiable)+ expected = _clahe_interpolation_reference(padded, luts, tile)[..., : size[0], : size[1]]+ out = enhance.equalize_clahe(img, 2.0, grid, slow_and_differentiable)+ assert out.dtype == dtype+ self.assert_close(out, expected)++ @pytest.mark.parametrize("dim", [-1, -2])+ @pytest.mark.parametrize("slow_and_differentiable", [False, True])+ def test_clahe_flip_symmetry_odd_tiles_5812(self, dim, slow_and_differentiable, device, dtype):+ # A grid that divides the image does not pad it, so odd tiles keep the flip symmetry of even ones.+ y = torch.arange(15, device=device, dtype=dtype)[:, None]+ x = torch.arange(27, device=device, dtype=dtype)[None, :]+ img = ((2 * y + x) / 64)[None, None]+ out = enhance.equalize_clahe(img, 2.0, (3, 3), slow_and_differentiable)+ flipped = enhance.equalize_clahe(img.flip(dim), 2.0, (3, 3), slow_and_differentiable)+ self.assert_close(flipped, out.flip(dim))++ def test_clahe_odd_tiles_gradcheck_5812(self, device):+ torch.manual_seed(4)+ img = torch.rand(1, 1, 9, 15, device=device, dtype=torch.float64)+ self.gradcheck(enhance.equalize_clahe, (img, 40.0, (3, 3), True), nondet_tol=1e-4)+def test_clahe_transpose_equivariance_4632(self):torch.manual_seed(28)img = torch.rand(1, 1, 12, 12, dtype=torch.float32)