π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(augmentation): apply CLAHE clip limits per image (#4582)
Keshav Chhabraa707859d12a3
diff --git a/changelog.d/4582.fixed.md b/changelog.d/4582.fixed.mdnew file mode 100644index 000000000..e15951e80--- /dev/null+++ b/changelog.d/4582.fixed.md@@ -0,0 +1 @@+`RandomClahe` now applies each sampled clip limit to its corresponding image in a batch.diff --git a/kornia/augmentation/_2d/intensity/base.py b/kornia/augmentation/_2d/intensity/base.pyindex 2fdbbc0b8..d3043783f 100644--- a/kornia/augmentation/_2d/intensity/base.py+++ b/kornia/augmentation/_2d/intensity/base.py@@ -67,12 +67,10 @@ class IntensityAugmentationBase2D(RigidAffineAugmentationBase2D):out-of-range image even at ``p=0.0`` -- and a skipped sample's gradient can be NaN where thetransform's derivative is infinite (`#4576 <https://github.com/kornia/kornia/issues/4576>`_).- the scalar factors a concrete class draws are per sample -- one value, or one per channel- per sample where the class's own docstring says so. Two classes draw per sample and then- apply one draw to the whole batch. :class:`RandomMotionBlur` fills ``_params["ksize_factor"]`` with- one kernel size per sample and blurs the batch with the one at ``_params["idx"]``, an index drawn- uniformly over the batch rather than the first sample's; :class:`RandomClahe` draws ``clip_limit``- per sample and applies the first sample's- (`#4572 <https://github.com/kornia/kornia/issues/4572>`_); and :class:`RandomDissolving`+ per sample where the class's own docstring says so. One class draws per sample and then+ applies one draw to the whole batch: :class:`RandomMotionBlur` fills ``_params["ksize_factor"]``+ with one kernel size per sample and blurs the batch with the one at ``_params["idx"]``, an index+ drawn uniformly over the batch rather than the first sample's. :class:`RandomDissolving`hard-codes ``same_on_batch=True``. Several classes also draw a whole-image field --``gaussian_noise``, ``gradient``, ``plasma``, and :class:`RandomSaltAndPepperNoise`'s boolean``mask_salt`` and ``mask_pepper`` -- whose stored shape normally follows the original batcheddiff --git a/kornia/augmentation/_2d/intensity/clahe.py b/kornia/augmentation/_2d/intensity/clahe.pyindex eb611839f..ceb2b1c2e 100644--- a/kornia/augmentation/_2d/intensity/clahe.py+++ b/kornia/augmentation/_2d/intensity/clahe.py@@ -36,6 +36,7 @@ class RandomClahe(IntensityAugmentationBase2D):Args:clip_limit: the ``(low, high)`` range the per-sample contrast-limiting threshold is drawn from.+ A value is drawn for each image, or once and shared across the batch when ``same_on_batch=True``.Unlike :func:`kornia.enhance.equalize_clahe`'s scalar argument of the same name this must be atwo-element tuple -- a scalar raises ``ValueError: `center` and `bounds` cannot be None forsingle number`` at construction -- and ``(0.0, 0.0)`` is what disables clipping. The bound is@@ -61,9 +62,11 @@ class RandomClahe(IntensityAugmentationBase2D):``gather`` error (`#4600 <https://github.com/kornia/kornia/issues/4600>`_), while ``2.5.1``leaves the gather unchecked and returns an in-range image as if the input had been valid.- .. warning::- ``clip_limit`` is drawn per sample, but the first sample's value is applied to the whole batch.- Tracked in `#4572 <https://github.com/kornia/kornia/issues/4572>`_.+ Convention:+ - ``clip_limit`` is drawn per sample and each image is equalized with its own draw. When every+ draw is equal -- which ``same_on_batch=True`` guarantees, and an unlucky batch can produce on+ its own -- the batch takes a single :func:`kornia.enhance.equalize_clahe` call instead of one+ per image; the result is the same either way... warning::``grid_size`` is unvalidated past its positivity check. Its two@@ -122,5 +125,13 @@ class RandomClahe(IntensityAugmentationBase2D):flags: dict[str, Any],transform: Optional[torch.Tensor] = None,) -> torch.Tensor:- clip_limit = float(params["clip_limit_factor"][0])- return equalize_clahe(input, clip_limit, flags["grid_size"], flags["slow_and_differentiable"])+ clip_limits = params["clip_limit_factor"]+ if bool(torch.all(clip_limits == clip_limits[0])):+ return equalize_clahe(input, float(clip_limits[0]), flags["grid_size"], flags["slow_and_differentiable"])++ return torch.stack(+ [+ equalize_clahe(image, float(clip_limit), flags["grid_size"], flags["slow_and_differentiable"])+ for image, clip_limit in zip(input, clip_limits)+ ]+ )diff --git a/tests/augmentation/test_augmentation.py b/tests/augmentation/test_augmentation.pyindex 73c442832..0fa219af8 100644--- a/tests/augmentation/test_augmentation.py+++ b/tests/augmentation/test_augmentation.py@@ -4236,6 +4236,44 @@ class TestRandomClahe(BaseTester):output_data = RandomClahe(p=1.0, grid_size=(2, 2))(input_data)assert output_data.shape == batch_shape+ @pytest.mark.parametrize("batch_prob", [(True, True), (False, True), (False, False)])+ @pytest.mark.parametrize("slow_and_differentiable", [False, True])+ def test_per_sample_clip_limit_replay(self, batch_prob, slow_and_differentiable, device, dtype):+ torch.manual_seed(0)+ input_data = torch.rand(2, 1, 32, 32).pow(3).to(device=device, dtype=dtype)+ clip_limits = torch.tensor([0.5, 40.0])+ aug = RandomClahe(+ clip_limit=(0.5, 40.0),+ grid_size=(2, 2),+ slow_and_differentiable=slow_and_differentiable,+ p=0.5,+ )+ params = aug.forward_parameters(input_data.shape)+ params["clip_limit_factor"] = clip_limits+ params["batch_prob"] = torch.tensor(batch_prob)++ transformed = torch.cat(+ [+ kornia.enhance.equalize_clahe(+ input_data[index : index + 1], float(clip_limit), (2, 2), slow_and_differentiable+ )+ for index, clip_limit in enumerate(clip_limits)+ ]+ )+ expected = torch.where(torch.tensor(batch_prob, device=device).view(-1, 1, 1, 1), transformed, input_data)++ self.assert_close(aug(input_data, params=params), expected)++ def test_same_on_batch(self, device, dtype):+ torch.manual_seed(0)+ input_data = torch.rand(1, 1, 32, 32).to(device=device, dtype=dtype).repeat(2, 1, 1, 1)+ aug = RandomClahe(clip_limit=(0.5, 40.0), grid_size=(2, 2), same_on_batch=True, p=1.0)++ output = aug(input_data)++ self.assert_close(aug._params["clip_limit_factor"][0], aug._params["clip_limit_factor"][1])+ self.assert_close(output[0], output[1])+class TestRandomGaussianNoise(BaseTester):def test_dynamo(self, device, dtype, torch_optimizer):diff --git a/tests/augmentation/test_conventions_intensity_values.py b/tests/augmentation/test_conventions_intensity_values.pyindex f747aa74a..d9bf8cca0 100644--- a/tests/augmentation/test_conventions_intensity_values.py+++ b/tests/augmentation/test_conventions_intensity_values.py@@ -1982,31 +1982,58 @@ class TestIntensityColourConventions(BaseTester):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])`).+ # RandomClahe equalizes each image with its OWN `clip_limit_factor` draw (the fix for #4572; the+ # whole batch used to take `float(params["clip_limit_factor"][0])`, the first sample's value).# Snippet used to generate expected:- # torch.manual_seed(1234); x = torch.rand(2, 1, 32, 32) ** 3+ # torch.manual_seed(1234); x = torch.rand(8, 1, 32, 32) ** 3# torch.manual_seed(0); aug = K.RandomClahe(clip_limit=(0.5, 40.0), grid_size=(2, 2), p=1.0); y = aug(x)- # c = aug._params["clip_limit_factor"]; print(c)- # for i in (1, 0):- # print(torch.equal(y[1:], equalize_clahe(x[1:], float(c[i]), (2, 2))))- # executed 2026-09-15 (torch 2.14.0, cpu) -> `[20.1021, 30.8448]`, `False True`.+ # c = aug._params["clip_limit_factor"]+ # print([torch.equal(y[i:i+1], equalize_clahe(x[i:i+1], float(c[i]), (2, 2))) for i in range(8)])+ # print([torch.equal(y[i:i+1], equalize_clahe(x[i:i+1], float(c[0]), (2, 2))) for i in range(8)])+ # executed 2026-09-16 (torch 2.14.0, cpu) -> clips `[20.10, 30.84, 4.00, 5.72, 12.64, 25.55, 19.86,+ # 35.91]`; own-clip all True; first-clip True only for row 0.@pytest.mark.device_agnostic- def test_wart_random_clahe_applies_the_first_clip_limit_to_the_batch_4572(self):+ def test_convention_random_clahe_applies_each_clip_limit_to_its_own_image_4572(self):# B is 8, not 2: two draws from (0.5, 40.0) land within 1.0 of each other about 5% of the time,- # and at B=2 this node failed on 12 of seeds 0..199. Over 8 draws the spread was at least 9.4 on- # every one of those seeds, and the sample farthest from the first is the one that shows the wart.+ # and at B=2 the pin this replaces failed on 12 of seeds 0..199. A wide batch also makes the+ # "every row got the FIRST clip limit" arm below a real discriminator rather than a coincidence.torch.manual_seed(_FIXTURE_SEED)image = torch.rand(8, 1, 32, 32) ** 3torch.manual_seed(_FORWARD_SEED)aug = K.RandomClahe(clip_limit=(0.5, 40.0), grid_size=(2, 2), p=1.0)out = aug(image)clip = aug._params["clip_limit_factor"]- far = int((clip - clip[0]).abs().argmax())- assert abs(float(clip[far]) - float(clip[0])) > 1.0- # The whole batch is equalized with the first sample's clip limit, not with its own.- assert torch.equal(out[far : far + 1], equalize_clahe(image[far : far + 1], float(clip[0]), (2, 2)))- assert not torch.equal(out[far : far + 1], equalize_clahe(image[far : far + 1], float(clip[far]), (2, 2)))+ assert float((clip - clip[0]).abs().max()) > 1.0, clip.tolist()+ for row in range(image.shape[0]):+ own = equalize_clahe(image[row : row + 1], float(clip[row]), (2, 2))+ assert torch.equal(out[row : row + 1], own), row+ # ... and not with the first sample's, which is what the defect did. Row 0 is excluded because+ # its own limit IS the first one, so it agrees under both contracts.+ first = int((clip - clip[0]).abs().argmax())+ assert not torch.equal(out[first : first + 1], equalize_clahe(image[first : first + 1], float(clip[0]), (2, 2)))++ # When every draw is equal the class takes a single `equalize_clahe` call for the batch instead of+ # one per image. `same_on_batch=True` is the way to reach that branch on purpose; the result must be+ # indistinguishable from the per-image path, so this pins equivalence and not merely finiteness.+ # Snippet used to generate expected:+ # torch.manual_seed(0)+ # aug = K.RandomClahe(clip_limit=(0.5, 40.0), grid_size=(2, 2), p=1.0, same_on_batch=True)+ # y = aug(x); c = aug._params["clip_limit_factor"]+ # print((c == c[0]).all(), torch.equal(y, equalize_clahe(x, float(c[0]), (2, 2))))+ # executed 2026-09-16 (torch 2.14.0, cpu) -> `True True`.+ @pytest.mark.device_agnostic+ def test_convention_random_clahe_equal_clip_limits_take_the_batched_path_4572(self):+ torch.manual_seed(_FIXTURE_SEED)+ image = torch.rand(8, 1, 32, 32) ** 3+ torch.manual_seed(_FORWARD_SEED)+ aug = K.RandomClahe(clip_limit=(0.5, 40.0), grid_size=(2, 2), p=1.0, same_on_batch=True)+ out = aug(image)+ clip = aug._params["clip_limit_factor"]+ assert bool((clip == clip[0]).all())+ assert torch.equal(out, equalize_clahe(image, float(clip[0]), (2, 2)))+ # The per-image path must agree with it row by row, so the fast path is an optimization only.+ for row in range(image.shape[0]):+ assert torch.equal(out[row : row + 1], equalize_clahe(image[row : row + 1], float(clip[0]), (2, 2)))# Every class whose path goes through rgb_to_hsv is finite for a black pixel in every dtype,# float16 included (the fix for #4560: the saturation divisor was `max_rgb + eps` with `eps=1e-8`,