Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Feat/randombrightness contrast saturation hue (#1955)

hoaquin9072beb14622
diff --git a/docs/source/augmentation.module.rst b/docs/source/augmentation.module.rst
index 45903c9e3..e46f4abbd 100644
--- a/docs/source/augmentation.module.rst
+++ b/docs/source/augmentation.module.rst
@@ -18,15 +18,19 @@ Intensity
.. autoclass:: ColorJiggle
.. autoclass:: ColorJitter
.. autoclass:: RandomBoxBlur
+.. autoclass:: RandomBrightness
.. autoclass:: RandomChannelShuffle
+.. autoclass:: RandomContrast
.. autoclass:: RandomEqualize
.. autoclass:: RandomGamma
.. autoclass:: RandomGrayscale
.. autoclass:: RandomGaussianBlur
.. autoclass:: RandomGaussianNoise
+.. autoclass:: RandomHue
.. autoclass:: RandomMotionBlur
.. autoclass:: RandomPosterize
.. autoclass:: RandomRGBShift
+.. autoclass:: RnadomSaturation
.. autoclass:: RandomSharpness
.. autoclass:: RandomSolarize
diff --git a/kornia/augmentation/_2d/intensity/__init__.py b/kornia/augmentation/_2d/intensity/__init__.py
index afc28dee9..5b4923c54 100644
--- a/kornia/augmentation/_2d/intensity/__init__.py
+++ b/kornia/augmentation/_2d/intensity/__init__.py
@@ -1,7 +1,9 @@
from kornia.augmentation._2d.intensity.box_blur import RandomBoxBlur
+from kornia.augmentation._2d.intensity.brightness import RandomBrightness
from kornia.augmentation._2d.intensity.channel_shuffle import RandomChannelShuffle
from kornia.augmentation._2d.intensity.color_jiggle import ColorJiggle
from kornia.augmentation._2d.intensity.color_jitter import ColorJitter
+from kornia.augmentation._2d.intensity.contrast import RandomContrast
from kornia.augmentation._2d.intensity.denormalize import Denormalize
from kornia.augmentation._2d.intensity.equalize import RandomEqualize
from kornia.augmentation._2d.intensity.erasing import RandomErasing
@@ -9,6 +11,7 @@ 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
+from kornia.augmentation._2d.intensity.hue import RandomHue
from kornia.augmentation._2d.intensity.invert import RandomInvert
from kornia.augmentation._2d.intensity.motion_blur import RandomMotionBlur
from kornia.augmentation._2d.intensity.normalize import Normalize
@@ -16,5 +19,6 @@ from kornia.augmentation._2d.intensity.planckian_jitter import RandomPlanckianJi
from kornia.augmentation._2d.intensity.plasma import RandomPlasmaBrightness, RandomPlasmaContrast, RandomPlasmaShadow
from kornia.augmentation._2d.intensity.posterize import RandomPosterize
from kornia.augmentation._2d.intensity.random_rgb_shift import RandomRGBShift
+from kornia.augmentation._2d.intensity.saturation import RandomSaturation
from kornia.augmentation._2d.intensity.sharpness import RandomSharpness
from kornia.augmentation._2d.intensity.solarize import RandomSolarize
diff --git a/kornia/augmentation/_2d/intensity/brightness.py b/kornia/augmentation/_2d/intensity/brightness.py
new file mode 100644
index 000000000..c735d6b82
--- /dev/null
+++ b/kornia/augmentation/_2d/intensity/brightness.py
@@ -0,0 +1,77 @@
+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.augmentation.utils import _range_bound
+from kornia.enhance.adjust import adjust_brightness
+
+
+class RandomBrightness(IntensityAugmentationBase2D):
+ r"""Apply a random transformation to the brightness of a tensor image.
+
+ This implementation aligns PIL. Hence, the output is close to TorchVision.
+
+ .. image:: _static/img/RandomBrighness.png
+
+ Args:
+ p: probability of applying the transformation.
+ brightness: the brightness factor to apply
+ clip_output: if true clip output
+ 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_brightness`
+
+ Examples:
+ >>> rng = torch.manual_seed(0)
+ >>> inputs = torch.rand(1, 3, 3, 3)
+ >>> aug = RandomBrightness(brightness = (0.5,2.),p=1.)
+ >>> aug(inputs)
+ tensor([[[[0.0505, 0.3225, 0.0000],
+ [0.0000, 0.0000, 0.1883],
+ [0.0443, 0.4507, 0.0099]],
+ <BLANKLINE>
+ [[0.1866, 0.0000, 0.0000],
+ [0.0000, 0.0000, 0.0000],
+ [0.0728, 0.2519, 0.3543]],
+ <BLANKLINE>
+ [[0.0000, 0.0000, 0.2359],
+ [0.4694, 0.0000, 0.4284],
+ [0.0000, 0.1072, 0.5070]]]])
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.rand(1, 3, 32, 32)
+ >>> aug = RandomBrightness((0.8,1.2), p=1.)
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
+ """
+
+ def __init__(
+ self,
+ brightness: Tuple[float, float] = (1.0, 1.0),
+ clip_output: bool = True,
+ 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.brightness: Tensor = _range_bound(brightness, 'brightness', center=1.0, bounds=(0.0, 2.0))
+ self._param_generator = cast(
+ rg.PlainUniformGenerator, rg.PlainUniformGenerator((self.brightness, "brightness_factor", None, None))
+ )
+ self.clip_output = clip_output
+
+ def apply_transform(
+ self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
+ ) -> Tensor:
+ brightness_factor = params["brightness_factor"].to(input)
+ return adjust_brightness(input, brightness_factor - 1, self.clip_output)
diff --git a/kornia/augmentation/_2d/intensity/contrast.py b/kornia/augmentation/_2d/intensity/contrast.py
new file mode 100644
index 000000000..2954cfc89
--- /dev/null
+++ b/kornia/augmentation/_2d/intensity/contrast.py
@@ -0,0 +1,77 @@
+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.augmentation.utils import _range_bound
+from kornia.enhance.adjust import adjust_contrast
+
+
+class RandomContrast(IntensityAugmentationBase2D):
+ r"""Apply a random transformation to the contrast of a tensor image.
+
+ This implementation aligns PIL. Hence, the output is close to TorchVision.
+
+ .. image:: _static/img/RandomContrast.png
+
+ Args:
+ p: probability of applying the transformation.
+ contrast: the contrast factor to apply
+ clip_output: if true clip output
+ 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_contrast
+
+ Examples:
+ >>> rng = torch.manual_seed(0)
+ >>> inputs = torch.rand(1, 3, 3, 3)
+ >>> aug = RandomContrast(contrast = (0.5,2.),p=1.)
+ >>> aug(inputs)
+ tensor([[[[0.2750, 0.4258, 0.0490],
+ [0.0732, 0.1704, 0.3514],
+ [0.2716, 0.4969, 0.2525]],
+ <BLANKLINE>
+ [[0.3505, 0.1934, 0.2227],
+ [0.0124, 0.0936, 0.1629],
+ [0.2874, 0.3867, 0.4434]],
+ <BLANKLINE>
+ [[0.0893, 0.1564, 0.3778],
+ [0.5072, 0.2201, 0.4845],
+ [0.2325, 0.3064, 0.5281]]]])
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.rand(1, 3, 32, 32)
+ >>> aug = RandomContrast((0.8,1.2), p=1.)
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
+ """
+
+ def __init__(
+ self,
+ contrast: Tuple[float, float] = (1.0, 1.0),
+ clip_output: bool = True,
+ 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.contrast: Tensor = _range_bound(contrast, 'contrast', center=1.0)
+ self._param_generator = cast(
+ rg.PlainUniformGenerator, rg.PlainUniformGenerator((self.contrast, "contrast_factor", None, None))
+ )
+ self.clip_output = clip_output
+
+ def apply_transform(
+ self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
+ ) -> Tensor:
+ contrast_factor = params["contrast_factor"].to(input)
+ return adjust_contrast(input, contrast_factor, self.clip_output)
diff --git a/kornia/augmentation/_2d/intensity/hue.py b/kornia/augmentation/_2d/intensity/hue.py
new file mode 100644
index 000000000..32a4b4591
--- /dev/null
+++ b/kornia/augmentation/_2d/intensity/hue.py
@@ -0,0 +1,75 @@
+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.augmentation.utils import _range_bound
+from kornia.constants import pi
+from kornia.enhance.adjust import adjust_hue
+
+
+class RandomHue(IntensityAugmentationBase2D):
+ r"""Apply a random transformation to the hue of a tensor image.
+
+ This implementation aligns PIL. Hence, the output is close to TorchVision.
+
+ .. image:: _static/img/RandomHue.png
+
+ Args:
+ p: probability of applying the transformation.
+ hue: the saturation 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_hue
+
+ Examples:
+ >>> rng = torch.manual_seed(0)
+ >>> inputs = torch.rand(1, 3, 3, 3)
+ >>> aug = RandomHue(hue = (-0.5,0.5),p=1.)
+ >>> aug(inputs)
+ tensor([[[[0.3993, 0.2823, 0.6816],
+ [0.6117, 0.2090, 0.4081],
+ [0.4693, 0.5529, 0.9527]],
+ <BLANKLINE>
+ [[0.1610, 0.5962, 0.4971],
+ [0.9152, 0.3971, 0.8742],
+ [0.4194, 0.6771, 0.7162]],
+ <BLANKLINE>
+ [[0.6323, 0.7682, 0.0885],
+ [0.0223, 0.1689, 0.2939],
+ [0.5185, 0.8964, 0.4556]]]])
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.rand(1, 3, 32, 32)
+ >>> aug = RandomHue((-0.2,0.2), p=1.)
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
+ """
+
+ def __init__(
+ self,
+ hue: Tuple[float, float] = (0.0, 0.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.hue: Tensor = _range_bound(hue, 'hue', bounds=(-0.5, 0.5))
+ self._param_generator = cast(
+ rg.PlainUniformGenerator, rg.PlainUniformGenerator((self.hue, "hue_factor", None, None))
+ )
+
+ def apply_transform(
+ self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
+ ) -> Tensor:
+ hue_factor = params["hue_factor"].to(input)
+ return adjust_hue(input, hue_factor * 2 * pi)
diff --git a/kornia/augmentation/_2d/intensity/saturation.py b/kornia/augmentation/_2d/intensity/saturation.py
new file mode 100644
index 000000000..0edcfb0b0
--- /dev/null
+++ b/kornia/augmentation/_2d/intensity/saturation.py
@@ -0,0 +1,74 @@
+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.augmentation.utils import _range_bound
+from kornia.enhance.adjust import adjust_saturation
+
+
+class RandomSaturation(IntensityAugmentationBase2D):
+ r"""Apply a random transformation to the saturation of a tensor image.
+
+ This implementation aligns PIL. Hence, the output is close to TorchVision.
+
+ .. image:: _static/img/RandomSaturation.png
+
+ Args:
+ p: probability of applying the transformation.
+ saturation: the saturation 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_saturation
+
+ Examples:
+ >>> rng = torch.manual_seed(0)
+ >>> inputs = torch.rand(1, 3, 3, 3)
+ >>> aug = RandomSaturation(saturation = (0.5,2.),p=1.)
+ >>> aug(inputs)
+ tensor([[[[0.5569, 0.7682, 0.3529],
+ [0.4811, 0.3474, 0.7411],
+ [0.5028, 0.8964, 0.6772]],
+ <BLANKLINE>
+ [[0.6323, 0.5358, 0.5265],
+ [0.4203, 0.2706, 0.5525],
+ [0.5185, 0.7863, 0.8681]],
+ <BLANKLINE>
+ [[0.3711, 0.4989, 0.6816],
+ [0.9152, 0.3971, 0.8742],
+ [0.4636, 0.7060, 0.9527]]]])
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.rand(1, 3, 32, 32)
+ >>> aug = RandomSaturation((0.8,1.2), p=1.)
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
+ """
+
+ def __init__(
+ self,
+ saturation: 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.saturation: Tensor = _range_bound(saturation, 'saturation', center=1.0)
+ self._param_generator = cast(
+ rg.PlainUniformGenerator, rg.PlainUniformGenerator((self.saturation, "saturation_factor", None, None))
+ )
+
+ def apply_transform(
+ self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
+ ) -> Tensor:
+ saturation_factor = params["saturation_factor"].to(input)
+ return adjust_saturation(input, saturation_factor)
diff --git a/kornia/augmentation/__init__.py b/kornia/augmentation/__init__.py
index ac9f8c480..7a173dd42 100644
--- a/kornia/augmentation/__init__.py
+++ b/kornia/augmentation/__init__.py
@@ -8,7 +8,9 @@ from kornia.augmentation._2d import (
PadTo,
RandomAffine,
RandomBoxBlur,
+ RandomBrightness,
RandomChannelShuffle,
+ RandomContrast,
RandomCrop,
RandomCutMix,
RandomCutMixV2,
@@ -21,6 +23,7 @@ from kornia.augmentation._2d import (
RandomGaussianNoise,
RandomGrayscale,
RandomHorizontalFlip,
+ RandomHue,
RandomInvert,
RandomJigsaw,
RandomMixUp,
@@ -36,6 +39,7 @@ from kornia.augmentation._2d import (
RandomResizedCrop,
RandomRGBShift,
RandomRotation,
+ RandomSaturation,
RandomSharpness,
RandomSolarize,
RandomThinPlateSpline,
@@ -83,8 +87,10 @@ __all__ = [
"PadTo",
"RandomAffine",
"RandomBoxBlur",
- "RandomCrop",
+ "RandomBrightness",
"RandomChannelShuffle",
+ "RandomContrast",
+ "RandomCrop",
"RandomErasing",
"RandomElasticTransform",
"RandomFisheye",
@@ -93,6 +99,7 @@ __all__ = [
"RandomGaussianBlur",
"RandomGaussianNoise",
"RandomHorizontalFlip",
+ "RandomHue",
"RandomVerticalFlip",
"RandomPerspective",
"RandomPlanckianJitter",
@@ -102,6 +109,7 @@ __all__ = [
"RandomResizedCrop",
"RandomRotation",
"RandomRGBShift",
+ "RandomSaturation",
"RandomSolarize",
"RandomSharpness",
"RandomPosterize",
diff --git a/test/augmentation/test_augmentation.py b/test/augmentation/test_augmentation.py
index 1f0dea41a..58456b606 100644
--- a/test/augmentation/test_augmentation.py
+++ b/test/augmentation/test_augmentation.py
@@ -16,7 +16,9 @@ from kornia.augmentation import (
Normalize,
PadTo,
RandomBoxBlur,
+ RandomBrightness,
RandomChannelShuffle,
+ RandomContrast,
RandomCrop,
RandomElasticTransform,
RandomEqualize,
@@ -27,6 +29,7 @@ from kornia.augmentation import (
RandomGaussianNoise,
RandomGrayscale,
RandomHorizontalFlip,
+ RandomHue,
RandomInvert,
RandomPlanckianJitter,
RandomPlasmaBrightness,
@@ -36,6 +39,7 @@ from kornia.augmentation import (
RandomResizedCrop,
RandomRGBShift,
RandomRotation,
+ RandomSaturation,
RandomThinPlateSpline,
RandomVerticalFlip,
Resize,
@@ -1637,6 +1641,432 @@ class TestColorJitter(BaseTester):
pass
+class TestRandomBrightness(BaseTester):
+ @pytest.mark.xfail(reason="might fail under windows OS due to printing preicision.")
+ def test_smoke(self):
+ f = RandomBrightness(brightness=(0.5, 1.5))
+ repr = (
+ "RandomBrightness(brightness_factor=tensor([0.5000, 1.5000]), " "p=1.0, p_batch=1.0, same_on_batch=False))"
+ )
+ assert str(f.__repr__) == repr
+
+ def test_random_brighness_identity(self, device, dtype):
+
+ f = RandomBrightness()
+
+ input = torch.rand(3, 5, 5, device=device, dtype=dtype).unsqueeze(0) # 3 x 5 x 5
+ expected = input
+
+ expected_transform = torch.eye(3, device=device, dtype=dtype).unsqueeze(0) # 3 x 3
+
+ self.assert_close(f(input), expected, low_tolerance=True)
+ self.assert_close(f.transform_matrix, expected_transform, low_tolerance=True)
+
+ def test_same_on_batch(self, device, dtype):
+ f = RandomBrightness(brightness=(0.5, 1.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_brightness(self, device, dtype):
+ return torch.tensor(
+ [
+ [
+ [[0.2529, 0.3529, 0.4529], [0.7529, 0.6529, 0.5529], [0.8529, 0.9529, 1.0000]],
+ [[0.2529, 0.3529, 0.4529], [0.7529, 0.6529, 0.5529], [0.8529, 0.9529, 1.0000]],
+ [[0.2529, 0.3529, 0.4529], [0.7529, 0.6529, 0.5529], [0.8529, 0.9529, 1.0000]],
+ ],
+ [
+ [[0.2660, 0.3660, 0.4660], [0.7660, 0.6660, 0.5660], [0.8660, 0.9660, 1.0000]],
+ [[0.2660, 0.3660, 0.4660], [0.7660, 0.6660, 0.5660], [0.8660, 0.9660, 1.0000]],
+ [[0.2660, 0.3660, 0.4660], [0.7660, 0.6660, 0.5660], [0.8660, 0.9660, 1.0000]],
+ ],
+ ],
+ device=device,
+ dtype=dtype,
+ )
+
+ def test_random_brightness(self, device, dtype):
+ torch.manual_seed(42)
+ f = RandomBrightness(brightness=(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]]]], device=device, dtype=dtype
+ ) # 1 x 1 x 3 x 3
+ input = input.repeat(2, 3, 1, 1) # 2 x 3 x 3
+
+ expected = self._get_expected_brightness(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(RandomBrightness())
+
+ 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_brightness_batch_sequential(self, device, dtype):
+ if dtype == torch.float16:
+ pytest.skip('not work for half-precision')
+
+ f = AugmentationSequential(RandomBrightness(), RandomBrightness())
+
+ 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(RandomBrightness(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 TestRandomContrast(BaseTester):
+ @pytest.mark.xfail(reason="might fail under windows OS due to printing preicision.")
+ def test_smoke(self):
+ f = RandomContrast(contrast=(0.7, 1.3))
+ repr = "RandomContrast(contrast=tensor([0.7000, 1.3000]), " "p=1.0, p_batch=1.0, same_on_batch=False)"
+ assert str(f) == repr
+
+ def test_random_contrast_identity(self, device, dtype):
+
+ f = RandomContrast()
+
+ input = torch.rand(3, 5, 5, device=device, dtype=dtype).unsqueeze(0) # 3 x 5 x 5
+ expected = input
+
+ expected_transform = torch.eye(3, device=device, dtype=dtype).unsqueeze(0) # 3 x 3
+
+ self.assert_close(f(input), expected, low_tolerance=True)
+ self.assert_close(f.transform_matrix, expected_transform, low_tolerance=True)
+
+ def test_same_on_batch(self, device, dtype):
+ f = RandomContrast(contrast=(0.5, 1.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_contrast(self, device, dtype):
+ return torch.tensor(
+ [
+ [
+ [[0.1153, 0.2306, 0.3459], [0.6917, 0.5765, 0.4612], [0.8070, 0.9225, 1.0000]],
+ [[0.1153, 0.2306, 0.3459], [0.6917, 0.5765, 0.4612], [0.8070, 0.9225, 1.0000]],
+ [[0.1153, 0.2306, 0.3459], [0.6917, 0.5765, 0.4612], [0.8070, 0.9225, 1.0000]],
+ ],
+ [
+ [[0.1166, 0.2332, 0.3498], [0.6996, 0.5830, 0.4664], [0.8162, 0.9328, 1.0000]],
+ [[0.1166, 0.2332, 0.3498], [0.6996, 0.5830, 0.4664], [0.8162, 0.9328, 1.0000]],
+ [[0.1166, 0.2332, 0.3498], [0.6996, 0.5830, 0.4664], [0.8162, 0.9328, 1.0000]],
+ ],
+ ],
+ device=device,
+ dtype=dtype,
+ )
+
+ def test_random_contrast(self, device, dtype):
+ torch.manual_seed(42)
+ f = RandomContrast(contrast=(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]]]], device=device, dtype=dtype
+ ) # 1 x 1 x 3 x 3
+ input = input.repeat(2, 3, 1, 1) # 2 x 3 x 3
+
+ expected = self._get_expected_contrast(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(RandomContrast())
+
+ 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_contrast_batch_sequential(self, device, dtype):
+ if dtype == torch.float16:
+ pytest.skip('not work for half-precision')
+
+ f = AugmentationSequential(RandomContrast(), RandomContrast())
+
+ 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(RandomContrast(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 TestRandomHue(BaseTester):
+ @pytest.mark.xfail(reason="might fail under windows OS due to printing preicision.")
+ def test_smoke(self):
+ f = RandomHue(hue=(-0.2, 0.3))
+ repr = "RandomHue(hue=tensor([-0.2000, 0.3000]), " "p=1.0, p_batch=1.0, same_on_batch=False)"
+ assert str(f) == repr
+
+ def test_random_hue_identity(self, device, dtype):
+
+ f = RandomHue(hue=(0.0, 0.0))
+
+ input = torch.rand(3, 5, 5, device=device, dtype=dtype).unsqueeze(0) # 3 x 5 x 5
+ expected = input
+
+ expected_transform = torch.eye(3, device=device, dtype=dtype).unsqueeze(0) # 3 x 3
+
+ self.assert_close(f(input), expected, low_tolerance=True)
+ self.assert_close(f.transform_matrix, expected_transform, low_tolerance=True)
+
+ def test_same_on_batch(self, device, dtype):
+ f = RandomHue(hue=(-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_hue(self, device, dtype):
+ return torch.tensor(
+ [
+ [
+ [[0.1000, 0.2000, 0.3000], [0.6438, 0.5000, 0.4000], [0.7000, 0.8000, 1.0000]],
+ [[1.0000, 0.4124, 0.5416], [0.6000, 0.3292, 0.2292], [0.7854, 0.1000, 0.2000]],
+ [[0.7314, 0.8000, 0.7000], [0.9000, 0.3000, 0.2000], [0.8000, 0.2978, 0.3832]],
+ ],
+ [
+ [[0.1000, 0.2000, 0.3000], [0.6476, 0.5000, 0.4000], [0.7000, 0.8000, 1.0000]],
+ [[1.0000, 0.4049, 0.5366], [0.6000, 0.3317, 0.2317], [0.7841, 0.1000, 0.2000]],
+ [[0.7427, 0.8000, 0.7000], [0.9000, 0.3000, 0.2000], [0.8000, 0.2890, 0.3732]],
+ ],
+ ],
+ device=device,
+ dtype=dtype,
+ )
+
+ def test_random_hue(self, device, dtype):
+ torch.manual_seed(42)
+ f = RandomHue(hue=(-0.1 / pi, 0.1 / pi))
+
+ 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 1 x 3 x 3
+ input = input.repeat(2, 1, 1, 1) # 2 x 3 x 3
+
+ expected = self._get_expected_hue(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(RandomHue())
+
+ 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_hue_batch_sequential(self, device, dtype):
+ if dtype == torch.float16:
+ pytest.skip('not work for half-precision')
+
+ f = AugmentationSequential(RandomHue(), RandomHue())
+
+ 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(RandomHue(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 TestRandomSaturation(BaseTester):
+ @pytest.mark.xfail(reason="might fail under windows OS due to printing preicision.")
+ def test_smoke(self):
+ f = RandomSaturation(saturation=(0.5, 1.5))
+ repr = "RandomSaturation(hue=tensor([0.5000, 1.5000]), " "p=1.0, p_batch=1.0, same_on_batch=False)"
+ assert str(f) == repr
+
+ def test_random_saturation_identity(self, device, dtype):
+
+ f = RandomSaturation(saturation=(1.0, 1.0))
+
+ input = torch.rand(3, 5, 5, device=device, dtype=dtype).unsqueeze(0) # 3 x 5 x 5
+ expected = input
+
+ expected_transform = torch.eye(3, device=device, dtype=dtype).unsqueeze(0) # 3 x 3
+
+ self.assert_close(f(input), expected, low_tolerance=True)
+ self.assert_close(f.transform_matrix, expected_transform, low_tolerance=True)
+
+ def test_same_on_batch(self, device, dtype):
+ f = RandomSaturation(saturation=(0.5, 1.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_saturation(self, device, dtype):
+ return torch.tensor(
+ [
+ [
+ [[0.0000, 0.0000, 0.1471], [0.4853, 0.5000, 0.4000], [0.6618, 0.8000, 1.0000]],
+ [[1.0000, 0.4000, 0.5618], [0.4853, 0.2235, 0.1235], [0.8000, 0.0000, 0.0000]],
+ [[0.5556, 0.8000, 0.7000], [0.9000, 0.2235, 0.1235], [0.8000, 0.3429, 0.3750]],
+ ],
+ [
+ [[0.0000, 0.0000, 0.1340], [0.4755, 0.5000, 0.4000], [0.6585, 0.8000, 1.0000]],
+ [[1.0000, 0.4000, 0.5585], [0.4755, 0.2170, 0.1170], [0.8000, 0.0000, 0.0000]],
+ [[0.5556, 0.8000, 0.7000], [0.9000, 0.2170, 0.1170], [0.8000, 0.3429, 0.3750]],
+ ],
+ ],
+ device=device,
+ dtype=dtype,
+ )
+
+ def test_random_saturation(self, device, dtype):
+ torch.manual_seed(42)
+ f = RandomSaturation(saturation=(0.5, 1.5))
+
+ 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 1 x 3 x 3
+ input = input.repeat(2, 1, 1, 1) # 2 x 3 x 3
+
+ expected = self._get_expected_saturation(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(RandomSaturation())
+
+ 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_saturation_batch_sequential(self, device, dtype):
+ if dtype == torch.float16:
+ pytest.skip('not work for half-precision')
+
+ f = AugmentationSequential(RandomSaturation(), RandomSaturation())
+
+ 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(RandomSaturation(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 TestRectangleRandomErasing(BaseTester):
@pytest.mark.parametrize("erase_scale_range", [(0.001, 0.001), (1.0, 1.0)])
@pytest.mark.parametrize("aspect_ratio_range", [(0.1, 0.1), (10.0, 10.0)])