π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(enhance): reject a CLAHE grid the image cannot pad against (#4907)
Miral Aminf115871622bf
diff --git a/changelog.d/4907.fixed.md b/changelog.d/4907.fixed.mdnew file mode 100644index 000000000..6335bf279--- /dev/null+++ b/changelog.d/4907.fixed.md@@ -0,0 +1,4 @@+`enhance.equalize_clahe` and `augmentation.RandomClahe` now raise kornia's `ValueError` when either image+axis is not larger than its `grid_size` entry, and the message names the smallest image the grid admits.+An image exactly as large as the grid, such as `8 x 8` at the default `grid_size=(8, 8)`, previously passed+the size check and failed inside the reflect padding with torch's raw `RuntimeError`. Closes #4783.diff --git a/kornia/augmentation/_2d/intensity/clahe.py b/kornia/augmentation/_2d/intensity/clahe.pyindex e6bc9f5f0..39b613dee 100644--- a/kornia/augmentation/_2d/intensity/clahe.py+++ b/kornia/augmentation/_2d/intensity/clahe.py@@ -54,11 +54,8 @@ class RandomClahe(IntensityAugmentationBase2D):``(input * 255).long()``, so a value less than one 8-bit code outside ``[0, 1]`` is still admitted, upto the rounding of ``input * 255`` in the input's dtype.- ``grid_size`` tiles the two axes independently, and a grid that does not divide the image pads it, so- ``grid_size=(3, 3)`` works on a ``10 x 10`` image. A grid larger than the image raises a ``ValueError``.-- .. warning::- An image as large as the grid, such as ``8 x 8`` at the default ``grid_size=(8, 8)``, raises a raw padding- error instead of the ``ValueError``. Tracked in `#4783 <https://github.com/kornia/kornia/issues/4783>`_.+ ``grid_size=(3, 3)`` works on a ``10 x 10`` image. Each axis must be larger than its grid size, so a+ grid as large as the image, or larger, raises a ``ValueError`` naming the smallest image it admits... note::This function internally uses :func:`kornia.enhance.equalize_clahe`.diff --git a/kornia/enhance/equalization.py b/kornia/enhance/equalization.pyindex 8d3484f7e..fd09d6327 100644--- a/kornia/enhance/equalization.py+++ b/kornia/enhance/equalization.py@@ -64,8 +64,19 @@ def _compute_tiles(pad_horz = kernel_horz * grid_size[1] - w# add the padding in the last coluns and rows- if pad_vert > batch.shape[-2] or pad_horz > batch.shape[-1]:- raise ValueError("Cannot compute tiles on the image according to the given grid size")+ # reflect padding needs the pad strictly below the axis it reflects, so >= is the bound: an+ # 8 x 8 image on an 8 x 8 grid pads by 8 on an axis of 8 and fails inside F.pad otherwise.+ if pad_vert >= batch.shape[-2] or pad_horz >= batch.shape[-1]:+ # An even tile has to cover more than one grid cell, so the axis must exceed the grid;+ # an odd one only has to exceed half of it.+ min_vert = grid_size[0] + 1 if even_tile_size else grid_size[0] // 2 + 1+ min_horz = grid_size[1] + 1 if even_tile_size else grid_size[1] // 2 + 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)}, which needs "+ f"({pad_vert}, {pad_horz}) of reflect padding, more than the image has to reflect. "+ f"The smallest image this grid admits is ({min_vert}, {min_horz})."+ )if pad_vert > 0 or pad_horz > 0:batch = F.pad(batch, [0, pad_horz, 0, pad_vert], mode="reflect") # B x C x H' x W'@@ -385,7 +396,8 @@ def equalize_clahe(Args: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).+ grid_size: number of tiles to be cropped in each direction (GH, GW). Each image axis must be larger+ than its grid size; otherwise a ``ValueError`` names the smallest image the grid admits.slow_and_differentiable: flag to select implementationReturns:diff --git a/tests/augmentation/test_conventions_intensity_values.py b/tests/augmentation/test_conventions_intensity_values.pyindex afea22752..cabf6eb3c 100644--- a/tests/augmentation/test_conventions_intensity_values.py+++ b/tests/augmentation/test_conventions_intensity_values.py@@ -1351,7 +1351,7 @@ class TestIntensityColourConventions(BaseTester):assert torch.equal(out, reference)# At the default grid (8, 8) an image smaller than the grid gets kornia's named ValueError, and 9 x 9 is- # admitted. The 8 x 8 case in between is the #4783 wart below.+ # admitted. The 8 x 8 case in between is covered by the #4783 pin below.def test_convention_random_clahe_default_grid_rejects_a_smaller_image(self, device, dtype):if not supports_reflect_padding(device, dtype):pytest.skip("reflection_pad2d is unavailable for this device/dtype")@@ -1361,16 +1361,18 @@ 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 #4783: an image exactly as large as the grid passes the named size check and then fails in- # the reflect padding with torch's raw error. A fix that handles it, or names it, flips this pin.- def test_wart_random_clahe_grid_sized_image_raises_a_raw_padding_error_4783(self, device, dtype):+ # Issue #4783: an image exactly as large as the grid used to pass the named size check and fail in the+ # reflect padding with torch's raw error. It now gets kornia's ValueError, naming the smallest image+ # the grid admits.+ def test_convention_random_clahe_grid_sized_image_is_rejected_by_name_4783(self, device, dtype):if not supports_reflect_padding(device, dtype):pytest.skip("reflection_pad2d is unavailable for this device/dtype")torch.manual_seed(_FORWARD_SEED)- with pytest.raises(RuntimeError) as info:+ with pytest.raises(ValueError) as info:_sync(K.RandomClahe(p=1.0)(torch.rand(1, 1, 8, 8, device=device, dtype=dtype)).device)- # A kornia error would name the grid or its tiles; torch's padding error does not.- assert not any(word in str(info.value).lower() for word in ("grid", "tile"))+ # The error names the argument the caller passed, unlike torch's padding error.+ assert "Cannot compute tiles" in str(info.value)+ assert "smallest image this grid admits is (9, 9)" in str(info.value)# Issue #4572: each image is equalized with its own `clip_limit_factor` draw, not the first sample's.@pytest.mark.device_agnosticdiff --git a/tests/enhance/test_equalization.py b/tests/enhance/test_equalization.pyindex fcebc8731..d52b8aecc 100644--- a/tests/enhance/test_equalization.py+++ b/tests/enhance/test_equalization.py@@ -22,6 +22,7 @@ import torchfrom kornia import enhancefrom kornia.core._compat import torch_version_ge+from kornia.enhance.equalization import _compute_tilesfrom kornia.geometry import rotatefrom testing.base import BaseTester@@ -100,6 +101,46 @@ class TestEqualization(BaseTester):enhance.equalize_clahe(img, clip, grid)assert expected_error_msg in str(errinfo)+ @pytest.mark.parametrize(+ ("size", "grid"),+ [+ ((8, 8), (8, 8)), # kornia#4783: an image as large as the grid+ ((8, 16), (8, 8)), # only the vertical axis is too small+ ((16, 8), (8, 8)), # only the horizontal axis is too small+ ((4, 4), (8, 8)), # already rejected before, message now names the limit+ ((4, 10), (4, 6)), # a non-square grid: the limit is named per axis, in (H, W) order+ ],+ )+ def test_exception_image_too_small_for_grid_4783(self, size, grid):+ # kornia#4783: reflect padding needs the pad below the axis it reflects, so an image that+ # only matches the grid used to reach F.pad and fail with a raw padding error.+ img = torch.rand(1, 1, *size)+ with pytest.raises(ValueError) as errinfo:+ enhance.equalize_clahe(img, grid_size=grid)+ assert "Cannot compute tiles" in str(errinfo.value)+ assert f"Got image size {size} and grid size {grid}" in str(errinfo.value)+ assert f"smallest image this grid admits is ({grid[0] + 1}, {grid[1] + 1})" in str(errinfo.value)++ @pytest.mark.parametrize(+ ("size", "grid", "smallest"),+ [((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.+ 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)+ tiles, _ = _compute_tiles(torch.rand(1, 1, *smallest), grid, even_tile_size=False)+ assert tiles.shape[1:3] == grid++ @pytest.mark.parametrize("grid", [(2, 2), (4, 4), (8, 8)])+ def test_smallest_image_the_grid_admits_is_accepted_4783(self, grid, device, dtype):+ # The size the message names must work, so the bound it reports is exact.+ img = torch.rand(1, 1, grid[0] + 1, grid[1] + 1, device=device, dtype=dtype)+ out = enhance.equalize_clahe(img, grid_size=grid)+ assert out.shape == img.shape+@pytest.mark.parametrize("dims", [(1, 1, 1, 1, 1), (1, 1)])def test_exception_tensor_dims(self, dims):img = torch.rand(dims)