Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Add Random Gamma and test (#1837)

duc121117048616c283c
diff --git a/docs/source/augmentation.module.rst b/docs/source/augmentation.module.rst
index cda750b1b..45903c9e3 100644
--- a/docs/source/augmentation.module.rst
+++ b/docs/source/augmentation.module.rst
@@ -20,6 +20,7 @@ Intensity
.. autoclass:: RandomBoxBlur
.. autoclass:: RandomChannelShuffle
.. autoclass:: RandomEqualize
+.. autoclass:: RandomGamma
.. autoclass:: RandomGrayscale
.. autoclass:: RandomGaussianBlur
.. autoclass:: RandomGaussianNoise
diff --git a/kornia/augmentation/_2d/intensity/__init__.py b/kornia/augmentation/_2d/intensity/__init__.py
index b168f9deb..afc28dee9 100644
--- a/kornia/augmentation/_2d/intensity/__init__.py
+++ b/kornia/augmentation/_2d/intensity/__init__.py
@@ -5,6 +5,7 @@ from kornia.augmentation._2d.intensity.color_jitter import ColorJitter
from kornia.augmentation._2d.intensity.denormalize import Denormalize
from kornia.augmentation._2d.intensity.equalize import RandomEqualize
from kornia.augmentation._2d.intensity.erasing import RandomErasing
+from kornia.augmentation._2d.intensity.gamma import RandomGamma
from kornia.augmentation._2d.intensity.gaussian_blur import RandomGaussianBlur
from kornia.augmentation._2d.intensity.gaussian_noise import RandomGaussianNoise
from kornia.augmentation._2d.intensity.grayscale import RandomGrayscale
diff --git a/kornia/augmentation/_2d/intensity/gamma.py b/kornia/augmentation/_2d/intensity/gamma.py
new file mode 100644
index 000000000..16bbcf441
--- /dev/null
+++ b/kornia/augmentation/_2d/intensity/gamma.py
@@ -0,0 +1,76 @@
+from typing import Any, Dict, Optional, Tuple, cast
+
+from torch import Tensor
+
+from kornia.augmentation import random_generator as rg
+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
+from kornia.enhance.adjust import adjust_gamma
+
+
+class RandomGamma(IntensityAugmentationBase2D):
+ r"""Apply a random transformation to the gamma of a tensor image.
+
+ This implementation aligns PIL. Hence, the output is close to TorchVision.
+
+ .. image:: _static/img/RandomGamma.png
+
+ Args:
+ p: probability of applying the transformation.
+ gamma: the gamma factor to apply
+ gain: the gain factor to apply
+ silence_instantiation_warning: if True, silence the warning at instantiation.
+ same_on_batch: apply the same transformation across the batch.
+ keepdim: whether to keep the output shape the same as input (True) or broadcast it
+ to the batch form (False).
+ Shape:
+ - Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
+ - Output: :math:`(B, C, H, W)`
+
+ .. note::
+ This function internally uses :func:`kornia.enhance.adjust_gamma`
+
+ Examples:
+ >>> rng = torch.manual_seed(0)
+ >>> inputs = torch.rand(1, 3, 3, 3)
+ >>> aug = RandomGamma((0.5,2.),(1.5,1.5),p=1.)
+ >>> aug(inputs)
+ tensor([[[[1.0000, 1.0000, 0.3912],
+ [0.4883, 0.7801, 1.0000],
+ [1.0000, 1.0000, 0.9702]],
+ <BLANKLINE>
+ [[1.0000, 0.8368, 0.9048],
+ [0.1824, 0.5597, 0.7609],
+ [1.0000, 1.0000, 1.0000]],
+ <BLANKLINE>
+ [[0.5452, 0.7441, 1.0000],
+ [1.0000, 0.8990, 1.0000],
+ [0.9267, 1.0000, 1.0000]]]])
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.rand(1, 3, 32, 32)
+ >>> aug = RandomGamma((0.8,1.2), p=1.)
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
+ """
+
+ def __init__(
+ self,
+ gamma: Tuple[float, float] = (1.0, 1.0),
+ gain: Tuple[float, float] = (1.0, 1.0),
+ same_on_batch: bool = False,
+ p: float = 1.0,
+ keepdim: bool = False,
+ return_transform: Optional[bool] = None,
+ ) -> None:
+ super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
+ self._param_generator = cast(
+ rg.PlainUniformGenerator,
+ rg.PlainUniformGenerator((gamma, "gamma_factor", None, None), (gain, "gain_factor", None, None)),
+ )
+
+ def apply_transform(
+ self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
+ ) -> Tensor:
+ gamma_factor = params["gamma_factor"].to(input)
+ gain_factor = params["gain_factor"].to(input)
+ return adjust_gamma(input, gamma_factor, gain_factor)
diff --git a/kornia/augmentation/__init__.py b/kornia/augmentation/__init__.py
index b9d8f5661..22c50e4bc 100644
--- a/kornia/augmentation/__init__.py
+++ b/kornia/augmentation/__init__.py
@@ -16,6 +16,7 @@ from kornia.augmentation._2d import (
RandomEqualize,
RandomErasing,
RandomFisheye,
+ RandomGamma,
RandomGaussianBlur,
RandomGaussianNoise,
RandomGrayscale,
@@ -80,6 +81,7 @@ __all__ = [
"RandomErasing",
"RandomElasticTransform",
"RandomFisheye",
+ "RandomGamma",
"RandomGrayscale",
"RandomGaussianBlur",
"RandomGaussianNoise",
diff --git a/test/augmentation/test_augmentation.py b/test/augmentation/test_augmentation.py
index cbc4dab2d..1a172a314 100644
--- a/test/augmentation/test_augmentation.py
+++ b/test/augmentation/test_augmentation.py
@@ -22,6 +22,7 @@ from kornia.augmentation import (
RandomEqualize,
RandomErasing,
RandomFisheye,
+ RandomGamma,
RandomGaussianBlur,
RandomGaussianNoise,
RandomGrayscale,
@@ -1697,6 +1698,132 @@ class TestRectangleRandomErasing(BaseTester):
pass
+class TestRandomGamma(BaseTester):
+
+ # return values such a Tensor variable.
+ @pytest.mark.xfail(reason="might fail under windows OS due to printing preicision.")
+ def test_smoke(self):
+ f = RandomGamma(gamma=(0.5, 2.0), gain=(0.5, 0.5))
+ repr = (
+ "RandomGamma(gamma=tensor([0.5000, 2.5000]), gain=tensor([0.5000, 1.5000]), "
+ "p=1.0, p_batch=1.0, same_on_batch=False)"
+ )
+ assert str(f) == repr
+
+ def test_same_on_batch(self, device, dtype):
+ f = RandomGamma(gamma=(0.5, 2.0), gain=(0.5, 0.5), same_on_batch=True)
+ input = torch.eye(3).unsqueeze(dim=0).unsqueeze(dim=0).repeat(2, 3, 1, 1)
+ res = f(input)
+ assert (res[0] == res[1]).all()
+
+ def _get_expected_gamma(self, device, dtype):
+ return torch.tensor(
+ [
+ [
+ [[0.0703, 0.1564, 0.2496], [0.5549, 0.4497, 0.3477], [0.6628, 0.7732, 1.0000]],
+ [[1.0000, 0.4497, 0.5549], [0.5549, 0.2496, 0.1564], [0.7732, 0.0703, 0.1564]],
+ [[0.5549, 0.7732, 0.6628], [0.8856, 0.2496, 0.1564], [0.7732, 0.3477, 0.4497]],
+ ],
+ [
+ [[0.0682, 0.1531, 0.2457], [0.5512, 0.4457, 0.3436], [0.6598, 0.7709, 1.0000]],
+ [[1.0000, 0.4457, 0.5512], [0.5512, 0.2457, 0.1531], [0.7709, 0.0682, 0.1531]],
+ [[0.5512, 0.7709, 0.6598], [0.8844, 0.2457, 0.1531], [0.7709, 0.3436, 0.4457]],
+ ],
+ ],
+ device=device,
+ dtype=dtype,
+ )
+
+ def test_random_gamma(self, device, dtype):
+ torch.manual_seed(42)
+ f = RandomGamma(gamma=(0.8, 1.2))
+ input = torch.tensor(
+ [
+ [
+ [[0.1, 0.2, 0.3], [0.6, 0.5, 0.4], [0.7, 0.8, 1.0]],
+ [[1.0, 0.5, 0.6], [0.6, 0.3, 0.2], [0.8, 0.1, 0.2]],
+ [[0.6, 0.8, 0.7], [0.9, 0.3, 0.2], [0.8, 0.4, 0.5]],
+ ]
+ ],
+ device=device,
+ dtype=dtype,
+ ) # 1 x 3 x 3 x 3
+
+ input = input.repeat(2, 1, 1, 1) # 2 x 3 x 3 x 3
+
+ expected = self._get_expected_gamma(device, dtype)
+
+ self.assert_close(f(input), expected, low_tolerance=True)
+
+ def test_random_gamma_tuple(self, device, dtype):
+ torch.manual_seed(42)
+
+ f = RandomGamma(gamma=(0.8, 1.2))
+
+ input = torch.tensor(
+ [
+ [
+ [[0.1, 0.2, 0.3], [0.6, 0.5, 0.4], [0.7, 0.8, 1.0]],
+ [[1.0, 0.5, 0.6], [0.6, 0.3, 0.2], [0.8, 0.1, 0.2]],
+ [[0.6, 0.8, 0.7], [0.9, 0.3, 0.2], [0.8, 0.4, 0.5]],
+ ]
+ ],
+ device=device,
+ dtype=dtype,
+ ) # 1 x 3 x 3 x 3
+
+ input = input.repeat(2, 1, 1, 1) # 2 x 3 x 3 x 3
+
+ expected = self._get_expected_gamma(device, dtype)
+
+ self.assert_close(f(input), expected, low_tolerance=True)
+
+ def test_sequential(self, device, dtype):
+ if dtype == torch.float16:
+ pytest.skip('not work for half-precision')
+ torch.manual_seed(27)
+
+ f = AugmentationSequential(RandomGamma(gamma=(0.5, 0.5)), RandomGamma(gamma=(2.0, 2.0)))
+
+ input = torch.rand(3, 5, 5, device=device, dtype=dtype).unsqueeze(0) # 1 x 3 x 5 x 5
+
+ expected = input
+
+ self.assert_close(f(input), expected)
+
+ def test_random_gamma_batch_sequential(self, device, dtype):
+ if dtype == torch.float16:
+ pytest.skip('not work for half-precision')
+
+ f = AugmentationSequential(RandomGamma(gamma=(0.5, 0.5)), RandomGamma(gamma=(2.0, 2.0)))
+
+ input = torch.rand(2, 3, 5, 5, device=device, dtype=dtype) # 2 x 3 x 5 x 5
+ expected = input
+
+ self.assert_close(f(input), expected, low_tolerance=True)
+
+ def test_gradcheck(self, device, dtype):
+ input = torch.rand((3, 5, 5), device=device, dtype=dtype).unsqueeze(0) # 3 x 3
+ input = utils.tensor_to_gradcheck_var(input) # to var
+ assert gradcheck(RandomGamma(p=1.0), (input,), raise_exception=True)
+
+ @pytest.mark.skip(reason="not implemented yet")
+ def test_cardinality(self, device, dtype):
+ pass
+
+ @pytest.mark.skip(reason="not implemented yet")
+ def test_exception(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 TestRandomGrayscale(BaseTester):
# TODO: improve and implement more meaningful smoke tests e.g check for a consistent