π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
[Feat] Add more augmentations (#960)
Edgar Riba4736ddd38f80
diff --git a/docs/source/augmentation.module.rst b/docs/source/augmentation.module.rstindex ca824b514..2b911f8bc 100644--- a/docs/source/augmentation.module.rst+++ b/docs/source/augmentation.module.rst@@ -25,6 +25,9 @@ Set of operators to perform data augmentation on 2D image tensors... autoclass:: RandomEqualize.. autoclass:: RandomMixUp.. autoclass:: RandomCutMix+.. autoclass:: RandomInvert+.. autoclass:: RandomChannelShuffle+.. autoclass:: RandomGaussianNoise.. automodule:: kornia.augmentation.functional.functional:members:diff --git a/docs/source/enhance.rst b/docs/source/enhance.rstindex eb9644d39..41076d465 100644--- a/docs/source/enhance.rst+++ b/docs/source/enhance.rst@@ -18,6 +18,7 @@ The functions in this section perform normalisations and intensity transformatio.. autofunction:: zca_mean.. autofunction:: zca_whiten.. autofunction:: linear_transform+.. autofunction:: invert.. autofunction:: histogram.. autofunction:: histogram2d@@ -44,3 +45,5 @@ Modules.. autoclass:: AdjustHue.. autoclass:: AdjustGamma.. autoclass:: AddWeighted++.. autoclass:: Invertdiff --git a/kornia/augmentation/__init__.py b/kornia/augmentation/__init__.pyindex 110a5ee21..b1e7d7f7e 100644--- a/kornia/augmentation/__init__.py+++ b/kornia/augmentation/__init__.py@@ -22,6 +22,9 @@ from .augmentation import (RandomMotionBlur,Normalize,Denormalize,+ RandomInvert,+ RandomChannelShuffle,+ RandomGaussianNoise,)from .augmentation3d import (RandomHorizontalFlip3D,diff --git a/kornia/augmentation/augmentation.py b/kornia/augmentation/augmentation.pyindex 8e35980e3..a684ab8e7 100644--- a/kornia/augmentation/augmentation.py+++ b/kornia/augmentation/augmentation.py@@ -22,6 +22,7 @@ from kornia.geometry import (rotate,warp_affine,warp_perspective,+ resize,)from kornia.geometry.transform.affwarp import _compute_rotation_matrix, _compute_tensor_centerfrom kornia.color import rgb_to_grayscale@@ -35,10 +36,11 @@ from kornia.enhance import (adjust_saturation,adjust_hue,adjust_gamma,+ Invert,)from kornia.utils import _extract_device_dtypefrom kornia.enhance.normalize import normalize, denormalize-from kornia.geometry import resize+from kornia.enhance import Invertfrom . import random_generator as rgfrom .utils import (@@ -1583,3 +1585,141 @@ class GaussianBlur(AugmentationBase2D):self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None) -> torch.Tensor:return gaussian_blur2d(input, self.kernel_size, self.sigma, self.border_type.name.lower())+++class RandomInvert(AugmentationBase2D):++ r"""Invert the tensor images values randomly.++ Args:+ max_val (torch.Tensor): The expected maximum value in the input tensor. The shape has to+ according to the input tensor shape, or at least has to work with broadcasting. Default: 1.0.+ return_transform (bool): if ``True`` return the matrix describing the transformation applied to each+ input tensor. If ``False`` and the input is a tuple the applied transformation wont be concatenated.+ same_on_batch (bool): apply the same transformation across the batch. Default: False.+ p (float): probability of applying the transformation. Default value is 0.5.++ Examples:+ >>> rng = torch.manual_seed(0)+ >>> img = torch.rand(1, 1, 5, 5)+ >>> inv = RandomInvert()+ >>> inv(img)+ 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]]]])+ """++ def __init__(self,+ max_val: torch.Tensor = torch.tensor(1.),+ return_transform: bool = False,+ same_on_batch: bool = False,+ p: float = 0.5) -> None:+ super(RandomInvert, self).__init__(+ p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.)+ self.transform = Invert(max_val)++ def __repr__(self) -> str:+ return self.__class__.__name__ + f"({super().__repr__()})"++ def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:+ return self.identity_matrix(input)++ def apply_transform(+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None+ ) -> torch.Tensor:+ return self.transform(input)+++class RandomChannelShuffle(AugmentationBase2D):+ r"""Shuffles the channels of a batch of multi-dimensional images.++ Args:+ return_transform (bool): if ``True`` return the matrix describing the transformation applied to each+ input tensor. If ``False`` and the input is a tuple the applied transformation wont be concatenated.+ same_on_batch (bool): apply the same transformation across the batch. Default: False.+ p (float): probability of applying the transformation. Default value is 0.5.++ Examples:+ >>> rng = torch.manual_seed(0)+ >>> img = torch.arange(1*2*2*2.).view(1,2,2,2)+ >>> RandomChannelShuffle()(img)+ tensor([[[[4., 5.],+ [6., 7.]],+ <BLANKLINE>+ [[0., 1.],+ [2., 3.]]]])+ """++ def __init__(self,+ return_transform: bool = False,+ same_on_batch: bool = False,+ p: float = 0.5) -> None:+ super(RandomChannelShuffle, self).__init__(+ p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.)++ def __repr__(self) -> str:+ return self.__class__.__name__ + f"({super().__repr__()})"++ def generate_parameters(self, shape: torch.Size) -> Dict[str, torch.Tensor]:+ B, C, _, _ = shape+ channels = torch.rand(B, C).argsort(dim=1)+ return dict(channels=channels)++ def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:+ return self.identity_matrix(input)++ def apply_transform(+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None+ ) -> torch.Tensor:+ out = torch.empty_like(input)+ for i in range(out.shape[0]):+ out[i] = input[i, params['channels'][i]]+ return out+++class RandomGaussianNoise(AugmentationBase2D):+ r"""Add gaussian noise to a batch of multi-dimensional images.++ Args:+ mean (float): The mean of the gaussian distribution. Default: 0.+ std (float): The standard deviation of the gaussian distribution. Default: 1.+ return_transform (bool): if ``True`` return the matrix describing the transformation applied to each+ input tensor. If ``False`` and the input is a tuple the applied transformation wont be concatenated.+ same_on_batch (bool): apply the same transformation across the batch. Default: False.+ p (float): probability of applying the transformation. Default value is 0.5.++ Examples:+ >>> rng = torch.manual_seed(0)+ >>> img = torch.ones(1, 1, 2, 2)+ >>> RandomGaussianNoise(mean=0., std=1., p=1.)(img)+ tensor([[[[ 2.5410, 0.7066],+ [-1.1788, 1.5684]]]])+ """++ def __init__(self,+ mean: float = 0.,+ std: float = 1.,+ return_transform: bool = False,+ same_on_batch: bool = False,+ p: float = 0.5) -> None:+ super(RandomGaussianNoise, self).__init__(+ p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.)+ self.mean = mean+ self.std = std++ def __repr__(self) -> str:+ return self.__class__.__name__ + f"({super().__repr__()})"++ def generate_parameters(self, shape: torch.Size) -> Dict[str, torch.Tensor]:+ noise = torch.randn(shape)+ return dict(noise=noise)++ def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:+ return self.identity_matrix(input)++ def apply_transform(+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None+ ) -> torch.Tensor:+ return input + params['noise'].to(input.device) * self.std + self.meandiff --git a/kornia/enhance/adjust.py b/kornia/enhance/adjust.pyindex a0ed4be42..9c0ac5e25 100644--- a/kornia/enhance/adjust.py+++ b/kornia/enhance/adjust.py@@ -24,11 +24,13 @@ __all__ = ["equalize3d","posterize","sharpness",+ "invert","AdjustBrightness","AdjustContrast","AdjustGamma","AdjustHue","AdjustSaturation",+ "Invert",]@@ -748,6 +750,32 @@ def equalize3d(input: torch.Tensor) -> torch.Tensor:return torch.stack(res)+def invert(input: torch.Tensor, max_val: torch.Tensor = torch.tensor(1.0)) -> torch.Tensor:+ r"""Inverts the values of an input tensor by its maximum value.++ Args:+ input (torch.Tensor): The input tensor to invert with an arbitatry shape.+ max_val (torch.Tensor): The expected maximum value in the input tensor. The shape has to+ according to the input tensor shape, or at least has to work with broadcasting. Default: 1.0.++ Example:+ >>> img = torch.rand(1, 2, 4, 4)+ >>> invert(img).shape+ torch.Size([1, 2, 4, 4])++ >>> img = 255. * torch.rand(1, 2, 3, 4, 4)+ >>> invert(img, torch.tensor(255.)).shape+ torch.Size([1, 2, 3, 4, 4])++ >>> img = torch.rand(1, 3, 4, 4)+ >>> invert(img, torch.tensor([[[[1.]]]])).shape+ torch.Size([1, 3, 4, 4])+ """+ assert isinstance(input, torch.Tensor), f"Input is not a torch.Tensor. Got: {type(input)}"+ assert isinstance(max_val, torch.Tensor), f"max_val is not a torch.Tensor. Got: {type(max_val)}"+ return max_val.to(input.dtype) - input++class AdjustSaturation(nn.Module):r"""Adjust color saturation of an image.@@ -944,3 +972,36 @@ class AdjustBrightness(nn.Module):def forward(self, input: torch.Tensor) -> torch.Tensor:return adjust_brightness(input, self.brightness_factor)+++class Invert(nn.Module):+ r"""Inverts the values of an input tensor by its maximum value.++ Args:+ input (torch.Tensor): The input tensor to invert with an arbitatry shape.+ max_val (torch.Tensor): The expected maximum value in the input tensor. The shape has to+ according to the input tensor shape, or at least has to work with broadcasting. Default: 1.0.++ Example:+ >>> img = torch.rand(1, 2, 4, 4)+ >>> Invert()(img).shape+ torch.Size([1, 2, 4, 4])++ >>> img = 255. * torch.rand(1, 2, 3, 4, 4)+ >>> Invert(torch.tensor(255.))(img).shape+ torch.Size([1, 2, 3, 4, 4])++ >>> img = torch.rand(1, 3, 4, 4)+ >>> Invert(torch.tensor([[[[1.]]]]))(img).shape+ torch.Size([1, 3, 4, 4])+ """++ def __init__(self, max_val: torch.Tensor = torch.tensor(1.)) -> None:+ super(Invert, self).__init__()+ if not isinstance(max_val, nn.Parameter):+ self.register_buffer("max_val", max_val)+ else:+ self.max_val = max_val++ def forward(self, input: torch.Tensor) -> torch.Tensor:+ return invert(input, self.max_val)diff --git a/test/augmentation/test_augmentation.py b/test/augmentation/test_augmentation.pyindex 6b07ace7e..d05f9d90e 100644--- a/test/augmentation/test_augmentation.py+++ b/test/augmentation/test_augmentation.py@@ -24,7 +24,10 @@ from kornia.augmentation import (RandomCrop,RandomResizedCrop,Normalize,- Denormalize+ Denormalize,+ RandomInvert,+ RandomChannelShuffle,+ RandomGaussianNoise,)@@ -2412,6 +2415,42 @@ class TestGaussianBlur:assert str(f) == repr+class TestRandomInvert:++ def test_smoke(self, device, dtype):+ img = torch.ones(1, 3, 4, 5, device=device, dtype=dtype)+ assert_allclose(RandomInvert(p=1.0)(img), torch.zeros_like(img))+++class TestRandomChannelShuffle:++ def test_smoke(self, device, dtype):+ torch.manual_seed(0)+ img = torch.arange(1 * 3 * 2 * 2, device=device, dtype=dtype).view(1, 3, 2, 2)++ out_expected = torch.tensor([[+ [[8., 9.],+ [10., 11.]],+ [[0., 1.],+ [2., 3.]],+ [[4., 5.],+ [6., 7.]]]+ ], device=device, dtype=dtype)++ aug = RandomChannelShuffle(p=1.)+ out = aug(img)+ assert_allclose(out, out_expected)+++class TestRandomGaussianNoise:++ def test_smoke(self, device, dtype):+ torch.manual_seed(0)+ img = torch.rand(1, 1, 2, 2, device=device, dtype=dtype)+ aug = RandomGaussianNoise(p=1.)+ assert img.shape == aug(img).shape++class TestNormalize:# TODO: improve and implement more meaningful smoke tests e.g check for a consistent# return values such a torch.Tensor variable.diff --git a/test/enhance/test_adjust.py b/test/enhance/test_adjust.pyindex 33aa06107..3f7acf660 100644--- a/test/enhance/test_adjust.py+++ b/test/enhance/test_adjust.py@@ -10,6 +10,53 @@ from torch.autograd import gradcheckfrom torch.testing import assert_allclose+class TestInvert:+ def test_smoke(self, device, dtype):+ img = torch.rand(1, 3, 4, 4, device=device, dtype=dtype)+ assert kornia.enhance.invert(img) is not None++ @pytest.mark.parametrize("shape", [+ (3, 4, 4), (2, 4, 3, 3), (1, 3, 2, 1, 1)+ ])+ def test_cardinality(self, device, dtype, shape):+ img = torch.rand(shape, device=device, dtype=dtype)+ out = kornia.enhance.invert(img, torch.tensor(1.))+ assert out.shape == shape++ def test_max_val_1(self, device, dtype):+ img = torch.ones(1, 3, 4, 4, device=device, dtype=dtype)+ out = kornia.enhance.invert(img, torch.tensor(1.0))+ assert_allclose(out, torch.zeros_like(out))++ def test_max_val_255(self, device, dtype):+ img = 255. * torch.ones(1, 3, 4, 4, device=device, dtype=dtype)+ out = kornia.enhance.invert(img, torch.tensor(255.))+ assert_allclose(out, torch.zeros_like(out))++ @pytest.mark.grad+ def test_gradcheck(self, device, dtype):+ B, C, H, W = 1, 3, 4, 4+ img = torch.ones(B, C, H, W, device=device, dtype=torch.float64, requires_grad=True)+ max_val = torch.tensor(1., device=device, dtype=torch.float64, requires_grad=True)+ assert gradcheck(kornia.enhance.invert, (img, max_val), raise_exception=True)++ @pytest.mark.jit+ def test_jit(self, device, dtype):+ B, C, H, W = 2, 3, 4, 4+ img = torch.ones(B, C, H, W, device=device, dtype=dtype)+ op = kornia.enhance.invert+ op_jit = torch.jit.script(op)+ assert_allclose(op(img), op_jit(img))++ @pytest.mark.nn+ def test_module(self, device, dtype):+ B, C, H, W = 2, 3, 4, 4+ img = torch.ones(B, C, H, W, device=device, dtype=dtype)+ op = kornia.enhance.invert+ op_mod = kornia.enhance.Invert()+ assert_allclose(op(img), op_mod(img))++class TestAdjustSaturation:def test_saturation_one(self, device, dtype):data = torch.tensor([[[.5, .5],