π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
add RandomClahe (#2614)
Mykhailo Bondarenkobe4874e4d79e
diff --git a/docs/source/augmentation.module.rst b/docs/source/augmentation.module.rstindex 31b2d0634..577a53477 100644--- a/docs/source/augmentation.module.rst+++ b/docs/source/augmentation.module.rst@@ -36,6 +36,7 @@ Intensity.. autoclass:: RandomMedianBlur.. autoclass:: RandomSnow.. autoclass:: RandomRain+.. autoclass:: RandomClaheGeometric~~~~~~~~~diff --git a/kornia/augmentation/_2d/intensity/__init__.py b/kornia/augmentation/_2d/intensity/__init__.pyindex b16faef7f..b3fc0ca59 100644--- a/kornia/augmentation/_2d/intensity/__init__.py+++ b/kornia/augmentation/_2d/intensity/__init__.py@@ -2,6 +2,7 @@ from kornia.augmentation._2d.intensity.auto_contrast import RandomAutoContrastfrom kornia.augmentation._2d.intensity.box_blur import RandomBoxBlurfrom kornia.augmentation._2d.intensity.brightness import RandomBrightnessfrom kornia.augmentation._2d.intensity.channel_shuffle import RandomChannelShuffle+from kornia.augmentation._2d.intensity.clahe import RandomClahefrom kornia.augmentation._2d.intensity.color_jiggle import ColorJigglefrom kornia.augmentation._2d.intensity.color_jitter import ColorJitterfrom kornia.augmentation._2d.intensity.contrast import RandomContrastdiff --git a/kornia/augmentation/_2d/intensity/clahe.py b/kornia/augmentation/_2d/intensity/clahe.pynew file mode 100644index 000000000..162f0caf1--- /dev/null+++ b/kornia/augmentation/_2d/intensity/clahe.py@@ -0,0 +1,65 @@+from __future__ import annotations++from typing import Any, Optional++from kornia.augmentation import random_generator as rg+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D+from kornia.core import Tensor+from kornia.enhance import equalize_clahe+++class RandomClahe(IntensityAugmentationBase2D):+ r"""Apply CLAHE equalization on the input tensor randomly.++ .. image:: _static/img/equalize_clahe.png++ Args:+ 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+ same_on_batch: apply the same transformation across the batch.+ p: probability of applying the transformation.+ keepdim: whether to keep the output shape the same as input (True) or broadcast it+ to the batch form (False).+ .. note::+ This function internally uses :func:`kornia.enhance.equalize_clahe`.++ Examples:+ >>> img = torch.rand(1, 10, 20)+ >>> aug = RandomClahe()+ >>> res = aug(img)+ >>> res.shape+ torch.Size([1, 1, 10, 20])++ >>> img = torch.rand(2, 3, 10, 20)+ >>> aug = RandomClahe()+ >>> res = aug(img)+ >>> res.shape+ torch.Size([2, 3, 10, 20])++ To apply the exact augmenation again, you may take the advantage of the previous parameter state:+ >>> input = torch.rand(1, 3, 32, 32)+ >>> aug = RandomClahe(p=1.)+ >>> (aug(input) == aug(input, params=aug._params)).all()+ tensor(True)+ """++ def __init__(+ self,+ clip_limit: tuple[float, float] = (40.0, 40.0),+ grid_size: tuple[int, int] = (8, 8),+ slow_and_differentiable: bool = False,+ same_on_batch: bool = False,+ p: float = 0.5,+ keepdim: bool = False,+ ) -> None:+ super().__init__(p=p, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim)+ self.clip_limit = clip_limit+ self._param_generator = rg.PlainUniformGenerator((self.clip_limit, "clip_limit_factor", None, None))+ self.flags = {"grid_size": grid_size, "slow_and_differentiable": slow_and_differentiable}++ def apply_transform(+ self, input: Tensor, params: dict[str, Tensor], flags: dict[str, Any], transform: Optional[Tensor] = None+ ) -> Tensor:+ clip_limit = float(params["clip_limit_factor"][0])+ return equalize_clahe(input, clip_limit, flags["grid_size"], flags["slow_and_differentiable"])diff --git a/kornia/augmentation/__init__.py b/kornia/augmentation/__init__.pyindex d487958ca..3144be43e 100644--- a/kornia/augmentation/__init__.py+++ b/kornia/augmentation/__init__.py@@ -13,6 +13,7 @@ from kornia.augmentation._2d import (RandomBoxBlur,RandomBrightness,RandomChannelShuffle,+ RandomClahe,RandomContrast,RandomCrop,RandomCutMixV2,diff --git a/kornia/enhance/equalization.py b/kornia/enhance/equalization.pyindex 1a5e95e46..f537867ff 100644--- a/kornia/enhance/equalization.py+++ b/kornia/enhance/equalization.py@@ -362,7 +362,9 @@ def equalize_clahe(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, diff=slow_and_differentiable) # 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 256equalized_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 tilesdiff --git a/test/augmentation/test_augmentation.py b/test/augmentation/test_augmentation.pyindex 66294d44a..47fbfcce5 100644--- a/test/augmentation/test_augmentation.py+++ b/test/augmentation/test_augmentation.py@@ -22,6 +22,7 @@ from kornia.augmentation import (RandomBoxBlur,RandomBrightness,RandomChannelShuffle,+ RandomClahe,RandomContrast,RandomCrop,RandomCrop3D,@@ -3521,6 +3522,34 @@ class TestRandomChannelShuffle(BaseTester):pass+class TestRandomClahe(BaseTester):+ def test_smoke(self, device, dtype):+ img = (torch.arange(36).reshape(2, 2, 3, 3) / 36).to(device=device, dtype=dtype)+ self.assert_close(RandomClahe(p=1.0, grid_size=(2, 2))(img).sum(), torch.tensor(22.4588, dtype=dtype))++ @pytest.mark.parametrize("batch_shape", [(1, 3, 5, 7), (3, 1, 5, 7)])+ def test_cardinality(self, batch_shape, device, dtype):+ input_data = (torch.arange(105).reshape(*batch_shape) / 105).to(device=device, dtype=dtype)+ output_data = RandomClahe(p=1.0, grid_size=(2, 2))(input_data)+ assert output_data.shape == batch_shape++ @pytest.mark.skip(reason="not implemented yet")+ def test_exception(self, device, dtype):+ pass++ @pytest.mark.skip(reason="not implemented yet")+ def test_gradcheck(self, device, dtype):+ pass++ @pytest.mark.skip(reason="not implemented yet")+ def test_jit(self, device, dtype):+ pass++ @pytest.mark.skip(reason="not implemented yet")+ def test_module(self, device, dtype):+ pass++class TestRandomGaussianNoise:def test_smoke(self, device, dtype):torch.manual_seed(0)