π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Added `RandomRGBShift` (#1694)
Oleksandra2020f625b1f7e291
diff --git a/docs/source/augmentation.module.rst b/docs/source/augmentation.module.rstindex 5ba2f63f6..1c07b21a1 100644--- a/docs/source/augmentation.module.rst+++ b/docs/source/augmentation.module.rst@@ -25,6 +25,7 @@ Intensity.. autoclass:: RandomGaussianNoise.. autoclass:: RandomMotionBlur.. autoclass:: RandomPosterize+.. autoclass:: RandomRGBShift.. autoclass:: RandomSharpness.. autoclass:: RandomSolarizediff --git a/kornia/augmentation/_2d/intensity/__init__.py b/kornia/augmentation/_2d/intensity/__init__.pyindex 25283dfff..b168f9deb 100644--- a/kornia/augmentation/_2d/intensity/__init__.py+++ b/kornia/augmentation/_2d/intensity/__init__.py@@ -14,5 +14,6 @@ from kornia.augmentation._2d.intensity.normalize import Normalizefrom kornia.augmentation._2d.intensity.planckian_jitter import RandomPlanckianJitterfrom kornia.augmentation._2d.intensity.plasma import RandomPlasmaBrightness, RandomPlasmaContrast, RandomPlasmaShadowfrom kornia.augmentation._2d.intensity.posterize import RandomPosterize+from kornia.augmentation._2d.intensity.random_rgb_shift import RandomRGBShiftfrom kornia.augmentation._2d.intensity.sharpness import RandomSharpnessfrom kornia.augmentation._2d.intensity.solarize import RandomSolarizediff --git a/kornia/augmentation/_2d/intensity/random_rgb_shift.py b/kornia/augmentation/_2d/intensity/random_rgb_shift.pynew file mode 100644index 000000000..91f98e6dd--- /dev/null+++ b/kornia/augmentation/_2d/intensity/random_rgb_shift.py@@ -0,0 +1,98 @@+from typing import Any, Dict, Optional, cast++from torch import Tensor++from kornia.augmentation import random_generator as rg+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D+from kornia.enhance import shift_rgb+++class RandomRGBShift(IntensityAugmentationBase2D):+ """Randomly shift each channel of an image.++ Args:+ r_shift_limit: maximum value up to which the shift value can be generated for red channel;+ recommended interval - [0, 1], should always be positive+ g_shift_limit: maximum value up to which the shift value can be generated for green channel;+ recommended interval - [0, 1], should always be positive+ b_shift_limit: maximum value up to which the shift value can be generated for blue channel;+ recommended interval - [0, 1], should always be positive+ 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:+ Input tensor must be float and normalized into [0, 1].++ Examples:+ >>> import torch+ >>> rng = torch.manual_seed(0)+ >>> inp = torch.rand(1, 3, 5, 5)+ >>> aug = RandomRGBShift(0, 0, 0)+ >>> ((inp == aug(inp)).double()).all()+ tensor(True)++ >>> rng = torch.manual_seed(0)+ >>> inp = torch.rand(1, 3, 5, 5)+ >>> inp+ tensor([[[[0.4963, 0.7682, 0.0885, 0.1320, 0.3074],+ [0.6341, 0.4901, 0.8964, 0.4556, 0.6323],+ [0.3489, 0.4017, 0.0223, 0.1689, 0.2939],+ [0.5185, 0.6977, 0.8000, 0.1610, 0.2823],+ [0.6816, 0.9152, 0.3971, 0.8742, 0.4194]],+ <BLANKLINE>+ [[0.5529, 0.9527, 0.0362, 0.1852, 0.3734],+ [0.3051, 0.9320, 0.1759, 0.2698, 0.1507],+ [0.0317, 0.2081, 0.9298, 0.7231, 0.7423],+ [0.5263, 0.2437, 0.5846, 0.0332, 0.1387],+ [0.2422, 0.8155, 0.7932, 0.2783, 0.4820]],+ <BLANKLINE>+ [[0.8198, 0.9971, 0.6984, 0.5675, 0.8352],+ [0.2056, 0.5932, 0.1123, 0.1535, 0.2417],+ [0.7262, 0.7011, 0.2038, 0.6511, 0.7745],+ [0.4369, 0.5191, 0.6159, 0.8102, 0.9801],+ [0.1147, 0.3168, 0.6965, 0.9143, 0.9351]]]])+ >>> aug = RandomRGBShift(p=1.)+ >>> aug(inp)+ tensor([[[[0.9374, 1.0000, 0.5297, 0.5732, 0.7486],+ [1.0000, 0.9313, 1.0000, 0.8968, 1.0000],+ [0.7901, 0.8429, 0.4635, 0.6100, 0.7351],+ [0.9597, 1.0000, 1.0000, 0.6022, 0.7234],+ [1.0000, 1.0000, 0.8383, 1.0000, 0.8606]],+ <BLANKLINE>+ [[0.6524, 1.0000, 0.1357, 0.2847, 0.4729],+ [0.4046, 1.0000, 0.2754, 0.3693, 0.2502],+ [0.1312, 0.3076, 1.0000, 0.8226, 0.8418],+ [0.6258, 0.3432, 0.6841, 0.1327, 0.2382],+ [0.3417, 0.9150, 0.8927, 0.3778, 0.5815]],+ <BLANKLINE>+ [[0.3850, 0.5623, 0.2636, 0.1328, 0.4005],+ [0.0000, 0.1584, 0.0000, 0.0000, 0.0000],+ [0.2914, 0.2663, 0.0000, 0.2163, 0.3397],+ [0.0021, 0.0843, 0.1811, 0.3754, 0.5453],+ [0.0000, 0.0000, 0.2617, 0.4795, 0.5003]]]])+ """++ def __init__(+ self,+ r_shift_limit: float = 0.5,+ g_shift_limit: float = 0.5,+ b_shift_limit: float = 0.5,+ same_on_batch: bool = False,+ p: float = 0.5,+ 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((r_shift_limit, "r_shift", 0, (-r_shift_limit, r_shift_limit)),+ (g_shift_limit, "g_shift", 0, (-g_shift_limit, g_shift_limit)),+ (b_shift_limit, "b_shift", 0, (-b_shift_limit, b_shift_limit)))+ )++ def apply_transform(+ self, inp: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None+ ) -> Tensor:+ return shift_rgb(inp, params['r_shift'], params['g_shift'], params['b_shift'])diff --git a/kornia/augmentation/__init__.py b/kornia/augmentation/__init__.pyindex 07a79f7d2..36ce491f9 100644--- a/kornia/augmentation/__init__.py+++ b/kornia/augmentation/__init__.py@@ -29,6 +29,7 @@ from kornia.augmentation._2d import (RandomPlasmaShadow,RandomPosterize,RandomResizedCrop,+ RandomRGBShift,RandomRotation,RandomSharpness,RandomSolarize,@@ -87,6 +88,7 @@ __all__ = ["RandomPlasmaContrast","RandomResizedCrop","RandomRotation",+ "RandomRGBShift","RandomSolarize","RandomSharpness","RandomPosterize",@@ -113,4 +115,5 @@ __all__ = ["ImageSequential","PatchSequential","VideoSequential",+ "RandomRGBShift",]diff --git a/kornia/enhance/__init__.py b/kornia/enhance/__init__.pyindex 8d2cb35ba..2b9d30dfc 100644--- a/kornia/enhance/__init__.py+++ b/kornia/enhance/__init__.py@@ -33,6 +33,7 @@ from .core import AddWeighted, add_weightedfrom .equalization import equalize_clahefrom .histogram import histogram, histogram2d, image_histogram2dfrom .normalize import Denormalize, Normalize, denormalize, normalize, normalize_min_max+from .shift_rgb import shift_rgbfrom .zca import ZCAWhitening, linear_transform, zca_mean, zca_whiten__all__ = [@@ -53,6 +54,7 @@ __all__ = ["equalize3d","posterize","sharpness",+ "shift_rgb","invert","AdjustBrightness","AdjustBrightnessAccumulative",diff --git a/kornia/enhance/shift_rgb.py b/kornia/enhance/shift_rgb.pynew file mode 100644index 000000000..3599f96ed--- /dev/null+++ b/kornia/enhance/shift_rgb.py@@ -0,0 +1,19 @@+import torch++from kornia.testing import KORNIA_CHECK_IS_COLOR, KORNIA_CHECK_IS_TENSOR+++def shift_rgb(image: torch.Tensor, r_shift: torch.Tensor, g_shift: torch.Tensor, b_shift: torch.Tensor) -> torch.Tensor:+ """Shift rgb channels.++ Shift each image's channel by either r_shift for red, g_shift for green and b_shift for blue channels.+ """++ KORNIA_CHECK_IS_TENSOR(image)+ KORNIA_CHECK_IS_COLOR(image, f"with shape {image.shape}")++ shifts = [r_shift, g_shift, b_shift]++ shifted = (image + torch.Tensor(shifts).view(1, 3, 1, 1).to(image)).clamp_(min=0, max=1)++ return shifteddiff --git a/test/augmentation/test_augmentation.py b/test/augmentation/test_augmentation.pyindex 25aef1972..28bd7771a 100644--- a/test/augmentation/test_augmentation.py+++ b/test/augmentation/test_augmentation.py@@ -33,6 +33,7 @@ from kornia.augmentation import (RandomPlasmaShadow,RandomPosterize,RandomResizedCrop,+ RandomRGBShift,RandomRotation,RandomThinPlateSpline,RandomVerticalFlip,@@ -3053,3 +3054,12 @@ class TestPlanckianJitter:f = RandomPlanckianJitter(select_from=select_from, same_on_batch=True, p=1.0).to(device, dtype)expected = self._get_expected_output_same_on_batch(device, dtype)assert_close(f(input), expected, atol=1e-4, rtol=1e-4)+++class TestRandomRGBShift:++ def test_smoke(self, device, dtype):+ img = torch.rand(1, 3, 4, 5, device=device, dtype=dtype)+ aug = RandomRGBShift(p=1.0).to(device)+ out = aug(img)+ assert out.shape == (1, 3, 4, 5)diff --git a/test/enhance/test_shift_rgb.py b/test/enhance/test_shift_rgb.pynew file mode 100644index 000000000..a83cdc61a--- /dev/null+++ b/test/enhance/test_shift_rgb.py@@ -0,0 +1,53 @@+import pytest+import torch+from torch.autograd import gradcheck++import kornia+import kornia.testing as utils # test utils+++class TestRGBShift:++ def test_rgb_shift_no_shift(self, device, dtype):+ r_shift, g_shift, b_shift = 0, 0, 0+ image = torch.rand(2, 3, 5, 5, device=device, dtype=dtype)+ expected = image+ shifted = kornia.enhance.shift_rgb(image, r_shift, g_shift, b_shift)++ utils.assert_close(shifted, expected)++ def test_rgb_shift_all_zeros(self, device, dtype):+ r_shift, g_shift, b_shift = -0.1, -0.1, -0.1+ image = torch.zeros(2, 3, 5, 5, device=device, dtype=dtype)+ expected = image+ shifted = kornia.enhance.shift_rgb(image, r_shift, g_shift, b_shift)++ utils.assert_close(shifted, expected)++ def test_rgb_shift_all_ones(self, device, dtype):+ r_shift, g_shift, b_shift = 1, 1, 1+ image = torch.rand(2, 3, 5, 5, device=device, dtype=dtype)+ expected = torch.ones(2, 3, 5, 5, device=device, dtype=dtype)+ shifted = kornia.enhance.shift_rgb(image, r_shift, g_shift, b_shift)++ utils.assert_close(shifted, expected)++ def test_rgb_shift_invalid_parameter_shape(self, device, dtype):+ r_shift, g_shift, b_shift = 0.5, 0.5, 0.5+ image = torch.randn(3, 3, device=device, dtype=dtype)+ with pytest.raises(TypeError):+ kornia.enhance.shift_rgb(image, r_shift, g_shift, b_shift)++ def test_rgb_shift_gradcheck(self, device, dtype):+ r_shift, g_shift, b_shift = 0.4, 0.5, 0.2+ image = torch.randn(2, 3, 5, 5, device=device, dtype=dtype)+ image = utils.tensor_to_gradcheck_var(image) # to var+ assert gradcheck(kornia.enhance.shift_rgb, (image, r_shift, g_shift, b_shift), raise_exception=True)++ def test_rgb_shift(self, device, dtype):+ r_shift, g_shift, b_shift = 0.1, 0.2, -0.3+ image = torch.tensor([[[[0.2, 0.]], [[0.3, 0.5]], [[0.4, 0.7]]]], device=device, dtype=dtype)+ shifted = kornia.enhance.shift_rgb(image, r_shift, g_shift, b_shift)+ expected = torch.tensor([[[[0.3, 0.1]], [[0.5, 0.7]], [[0.1, 0.4]]]], device=device, dtype=dtype)++ utils.assert_close(shifted, expected)