π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(enhance): support non-square grid_size in equalize_clahe and RandomClahe (#4628)
awss607869e2d0a1
diff --git a/changelog.d/4628.fixed.md b/changelog.d/4628.fixed.mdnew file mode 100644index 000000000..3d091a6bc--- /dev/null+++ b/changelog.d/4628.fixed.md@@ -0,0 +1,3 @@+`equalize_clahe` and `RandomClahe` accept a `grid_size` whose two entries differ. Such a grid used to raise+`IndexError: shape mismatch: indexing tensors could not be broadcast together` on every image (#2531). Output+for square grids is unchanged.diff --git a/kornia/augmentation/_2d/intensity/clahe.py b/kornia/augmentation/_2d/intensity/clahe.pyindex 8e4f422b6..27e39b49e 100644--- a/kornia/augmentation/_2d/intensity/clahe.py+++ b/kornia/augmentation/_2d/intensity/clahe.py@@ -67,17 +67,14 @@ class RandomClahe(IntensityAugmentationBase2D):Tracked in `#4572 <https://github.com/kornia/kornia/issues/4572>`_... warning::- ``grid_size`` is unvalidated past its positivity check in the same way the value range is, and only a- **square** grid works. Any ``grid_size`` whose two entries differ raises a raw ``IndexError``- (``shape mismatch: indexing tensors could not be broadcast together``) on every image, whether or not- the grid tiles it: ``(4, 5)`` fails on a ``20 x 20`` image that both entries divide exactly, and so- does ``(1, 2)`` on a ``10 x 10`` one. Reported in- `#2531 <https://github.com/kornia/kornia/issues/2531>`_. Divisibility is a separate axis: a square- grid that does not tile the image is padded instead, so ``grid_size=(3, 3)`` works on a ``10 x 10``- image, and because :func:`kornia.enhance.equalize_clahe` rounds the tile up to an even size an- exactly dividing grid can still pad. An image too small for the grid raises a raw ``RuntimeError``- from the padding -- at the default ``grid_size=(8, 8)`` the smallest admissible square image is- ``9 x 9``, and ``8 x 8`` raises. A grid larger than the image gets the named ``ValueError`` instead.+ ``grid_size`` is unvalidated past its positivity check. Its two+ entries tile the two axes independently, and a grid that does not tile the image is padded instead, so+ ``grid_size=(3, 3)`` works on a ``10 x 10`` image. Because :func:`kornia.enhance.equalize_clahe` rounds+ the tile up to an even size along each axis, an exactly dividing grid can still pad: ``(4, 5)`` pads 4+ rows and no columns of a ``20 x 20`` image. An image too small for the grid raises a raw+ ``RuntimeError`` from the padding; at the default ``grid_size=(8, 8)`` the smallest admissible square+ image is ``9 x 9``, and ``8 x 8`` raises. A grid larger than the image gets the named ``ValueError``+ instead... note::This function internally uses :func:`kornia.enhance.equalize_clahe`.diff --git a/kornia/enhance/equalization.py b/kornia/enhance/equalization.pyindex ed85583c4..474260843 100644--- a/kornia/enhance/equalization.py+++ b/kornia/enhance/equalization.py@@ -242,7 +242,7 @@ def _map_luts(interp_tiles: torch.Tensor, luts: torch.Tensor) -> torch.Tensor:luts_x_interp_tiles[:, 0 :: gh - 1, 1:-1, 1] = luts[:, 0 :: max(gh // 2 - 1, 1), i_idxs[:, 1]]# internal regionluts_x_interp_tiles[:, 1:-1, 1:-1, :] = luts[- :, j_idxs.repeat(max(gh - 2, 1), 1, 1).permute(1, 0, 2), i_idxs.repeat(max(gw - 2, 1), 1, 1)+ :, j_idxs.repeat(max(gw - 2, 1), 1, 1).permute(1, 0, 2), i_idxs.repeat(max(gh - 2, 1), 1, 1)]return luts_x_interp_tiles@@ -315,14 +315,14 @@ def _compute_equalized_tiles(interp_tiles: torch.Tensor, luts: torch.Tensor) -># border region (h)t, b, _, _ = preinterp_tiles_equalized[:, 1:-1, 0].unbind(2)tiles_equalized[:, 1:-1, 0] = torch.addcmul(b, tih.squeeze(1), torch.sub(t, b))- t, b, _, _ = preinterp_tiles_equalized[:, 1:-1, gh - 1].unbind(2)- tiles_equalized[:, 1:-1, gh - 1] = torch.addcmul(b, tih.squeeze(1), torch.sub(t, b))+ t, b, _, _ = preinterp_tiles_equalized[:, 1:-1, gw - 1].unbind(2)+ tiles_equalized[:, 1:-1, gw - 1] = torch.addcmul(b, tih.squeeze(1), torch.sub(t, b))# border region (w)left, right, _, _ = preinterp_tiles_equalized[:, 0, 1:-1].unbind(2)tiles_equalized[:, 0, 1:-1] = torch.addcmul(right, tiw, torch.sub(left, right))- left, right, _, _ = preinterp_tiles_equalized[:, gw - 1, 1:-1].unbind(2)- tiles_equalized[:, gw - 1, 1:-1] = torch.addcmul(right, tiw, torch.sub(left, right))+ left, right, _, _ = preinterp_tiles_equalized[:, gh - 1, 1:-1].unbind(2)+ tiles_equalized[:, gh - 1, 1:-1] = torch.addcmul(right, tiw, torch.sub(left, right))# same type as the inputreturn tiles_equalized.div(255.0)diff --git a/tests/augmentation/test_conventions_intensity_values.py b/tests/augmentation/test_conventions_intensity_values.pyindex 3c7de2256..1678903f0 100644--- a/tests/augmentation/test_conventions_intensity_values.py+++ b/tests/augmentation/test_conventions_intensity_values.py@@ -1929,35 +1929,38 @@ class TestIntensityColourConventions(BaseTester):torch.manual_seed(_FORWARD_SEED)assert K.RandomClahe(p=1.0)(torch.rand(1, 1, 9, 9, device=device, dtype=dtype)).shape == (1, 1, 9, 9)- # Issue #2531: every NON-square `grid_size` raises, on every image, whether or not it tiles. The- # `(4, 5)` / `20 x 20` row is the exactly dividing case, `(1, 2)` / `10 x 10` the one that pads, and- # `(3, 5)` / `30 x 30` rules out a mismatch between odd and even grid entries as the cause.+ # Issue #2531: a NON-square `grid_size` works like a square one, and each axis is tiled on its own.+ # The `(4, 5)` / `20 x 20` row pads 4 rows and no columns although both entries divide the image,+ # `(1, 2)` / `10 x 10` pads 2 columns only, and `(3, 5)` / `30 x 30` pads nothing. As in the square+ # test above, the pre-padded image run through the same call and cropped back reproduces the output+ # bitwise, which pins the padding of each axis separately. Values are checked against an exact+ # reference in `tests/enhance/test_equalization.py`.# Snippet used to generate expected:- # import itertools- # for gh, gw in itertools.product(range(1, 7), repeat=2):- # for h, w in ((24, 24), (30, 30), (24, 30), (35, 42), (60, 60)):- # torch.manual_seed(0); K.RandomClahe(grid_size=(gh, gw), p=1.0)(torch.rand(1, 1, h, w))- # executed 2026-09-16 (torch 2.14.0, cpu) -> all 150 rows follow `raises == (gh != gw)`; a further- # 40 random non-square grids from {1,2,3,4,5,7,8,9,12,16}^2 over three image shapes raised in- # 120/120 cases and the 30 square controls all passed.+ # for gs, n, pad in (((4, 5), 20, (4, 0)), ((3, 5), 30, (0, 0)), ((1, 2), 10, (0, 2))):+ # x = torch.linspace(0, 1, n * n).reshape(1, 1, n, n)+ # torch.manual_seed(0); out = K.RandomClahe(grid_size=gs, p=1.0)(x)+ # p = torch.nn.functional.pad(x, [0, pad[1], 0, pad[0]], mode="reflect")+ # torch.manual_seed(0); print(torch.equal(out, K.RandomClahe(grid_size=gs, p=1.0)(p)[..., :n, :n]))+ # executed 2026-09-17 (torch 2.14.0, cpu, all four dtypes) -> `True` for all three rows; before the+ # fix each row raised `IndexError: shape mismatch: indexing tensors could not be broadcast together`.@pytest.mark.parametrize(- ("grid_size", "size", "pads"), [((4, 5), 20, True), ((3, 5), 30, False), ((1, 2), 10, True)]+ ("grid_size", "size", "pad"), [((4, 5), 20, (4, 0)), ((3, 5), 30, (0, 0)), ((1, 2), 10, (0, 2))])- def test_wart_random_clahe_non_square_grid_always_raises_2531(self, device, dtype, grid_size, size, pads):- if pads and not supports_reflect_padding(device, dtype):- # A padding row would die of "reflection_pad2d not implemented for 'Half'" on the torch 2.5.1- # floor before reaching the lookup; the `(3, 5)` row pads nothing, so it keeps the pin alive- # on every dtype.+ def test_convention_random_clahe_non_square_grid_works_2531(self, device, dtype, grid_size, size, pad):+ pad_rows, pad_cols = pad+ if (pad_rows or pad_cols) and not supports_reflect_padding(device, dtype):pytest.skip("reflection_pad2d is unavailable for this device/dtype")- if device.type == "cuda":- # The broadcast of the lookup indices is computed on the host, so this should raise before- # any kernel launches -- but that is untested on CUDA, and being wrong here poisons the- # context for every later test, exactly as the #4564 pin above guards against.- pytest.skip("not on CUDA: the raise site ahead of the device-side lookup is unverified there")image = torch.linspace(0, 1, size * size, device=device, dtype=dtype).reshape(1, 1, size, size)torch.manual_seed(_FORWARD_SEED)- with pytest.raises(IndexError, match="shape mismatch: indexing tensors could not be broadcast together"):- K.RandomClahe(grid_size=grid_size, p=1.0)(image)+ out = K.RandomClahe(grid_size=grid_size, p=1.0)(image)+ assert out.shape == image.shape+ assert bool(out.isfinite().all())+ assert not torch.equal(out, image)+ if pad_rows or pad_cols:+ padded = torch.nn.functional.pad(image, [0, pad_cols, 0, pad_rows], mode="reflect")+ torch.manual_seed(_FORWARD_SEED)+ reference = K.RandomClahe(grid_size=grid_size, p=1.0)(padded)[..., :size, :size]+ assert torch.equal(out, reference)# Issue #4572: RandomClahe draws `clip_limit_factor` per sample but equalizes the whole batch with# the first sample's value (`float(params["clip_limit_factor"][0])`).diff --git a/tests/enhance/test_equalization.py b/tests/enhance/test_equalization.pyindex d11f4a05f..b46c6bc20 100644--- a/tests/enhance/test_equalization.py+++ b/tests/enhance/test_equalization.py@@ -46,6 +46,10 @@ class TestEqualization(BaseTester):(4, 1, (2, 2)),(4, 3, (2, 2)),(2, 2, (8, 8)),+ (None, 1, (2, 4)),+ (1, 3, (4, 2)),+ (4, 1, (1, 3)),+ (2, 2, (3, 1)),],)def test_cardinality(self, B, C, grid_size, device, dtype):@@ -98,7 +102,8 @@ class TestEqualization(BaseTester):with pytest.raises(TypeError):enhance.equalize_clahe([1, 2, 3])- def test_gradcheck(self, device):+ @pytest.mark.parametrize("grid_size", [(2, 2), (2, 3), (3, 2)])+ def test_gradcheck(self, device, grid_size):torch.random.manual_seed(4)bs, channels, height, width = 1, 1, 11, 11inputs = torch.rand(bs, channels, height, width, device=device, dtype=torch.float64)@@ -107,7 +112,7 @@ class TestEqualization(BaseTester):rot = rotate(data, torch.tensor(30.0, dtype=data.dtype, device=device))return enhance.equalize_clahe(rot, a, b, c)- self.gradcheck(grad_rot, (inputs, 40.0, (2, 2), True), nondet_tol=1e-4)+ self.gradcheck(grad_rot, (inputs, 40.0, grid_size, True), nondet_tol=1e-4)@pytest.mark.skip(reason="args and kwargs in decorator")def test_jit(self, device, dtype):@@ -280,3 +285,56 @@ class TestEqualization(BaseTester):)self.assert_close(res[..., 0, :], expected, low_tolerance=True)self.assert_close(res_diff[..., 0, :], exp_diff, low_tolerance=True)++ def test_clahe_non_square_grid(self, device, dtype):+ # Pixel values are 0 and powers of two, exact in every dtype. With 4 x 4 tiles every interpolation weight+ # is a multiple of 1/3, so 9 * 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+ # redistribute, floor(cumsum*255/P), axis blend weight (T-1-k)/(T-1)); it is posted in full on #4628.+ codes = torch.tensor(+ [+ [1, 2, 6, 7, 1, 7, 1, 5, 4, 8, 4, 6],+ [2, 7, 7, 8, 0, 4, 7, 2, 5, 0, 2, 1],+ [3, 3, 5, 5, 7, 2, 4, 8, 5, 5, 4, 4],+ [6, 5, 0, 4, 5, 3, 2, 8, 1, 3, 7, 7],+ [2, 1, 0, 7, 2, 8, 8, 3, 2, 2, 4, 4],+ [8, 2, 0, 3, 8, 4, 6, 0, 2, 5, 0, 7],+ [8, 8, 2, 3, 8, 6, 6, 3, 1, 4, 8, 4],+ [2, 7, 8, 7, 5, 7, 7, 5, 0, 0, 6, 0],+ ],+ device=device,+ )+ levels = torch.tensor([0.0] + [2.0**-k for k in range(7, -1, -1)], device=device, dtype=dtype)+ img = levels[codes][None, None]+ expected = torch.tensor(+ [+ [423, 567, 1575, 1815, 423, 1719, 423, 1431, 1143, 2295, 1143, 1719],+ [567, 1863, 1863, 2295, 279, 1143, 1719, 759, 1431, 279, 855, 423],+ [855, 855, 1287, 1335, 1767, 711, 1143, 2295, 1431, 1431, 1143, 1143],+ [1623, 1431, 327, 1255, 1367, 903, 663, 2295, 455, 1143, 1911, 1911],+ [855, 519, 375, 1751, 695, 2295, 2295, 967, 839, 951, 1335, 1335],+ [2295, 999, 423, 1191, 2295, 999, 1431, 327, 855, 1719, 423, 2007],+ [2295, 2295, 999, 1191, 2295, 1431, 1431, 951, 519, 1431, 2295, 1431],+ [999, 1719, 2295, 1719, 1335, 1719, 1719, 1335, 375, 423, 1863, 423],+ ],+ dtype=torch.float64,+ )+ expected = expected.div(9 * 255).to(dtype).to(device)[None, None]+ # Both orientations: the two border regions are indexed by the grid size of different axes.+ self.assert_close(enhance.equalize_clahe(img, 40.0, (2, 3)), expected)+ self.assert_close(enhance.equalize_clahe(img.transpose(-2, -1), 40.0, (3, 2)), expected.transpose(-2, -1))++ @pytest.mark.parametrize("slow_and_differentiable", [False, True])+ @pytest.mark.parametrize("grid_size", [(1, 2), (2, 3), (3, 4), (2, 6), (6, 2)])+ def test_clahe_non_square_grid_transpose(self, grid_size, slow_and_differentiable, device, dtype):+ # Transposing the image and the grid transposes the output. Every grid tiles 12 x 24 without padding.+ # The slow path runs unclipped: below float64 its clip step can turn a rounding residue of the soft+ # histogram sum into a whole count, which moves the output under transposition on square grids too.+ clip_limit = 0.0 if slow_and_differentiable else 40.0+ torch.manual_seed(2531)+ img = torch.rand(1, 2, 12, 24, device=device, dtype=dtype)+ out = enhance.equalize_clahe(img, clip_limit, grid_size, slow_and_differentiable)+ out_t = enhance.equalize_clahe(img.transpose(-2, -1), clip_limit, grid_size[::-1], slow_and_differentiable)+ self.assert_close(out_t, out.transpose(-2, -1))