π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Feat: add Gradient Illumination augmentations (gaussian) (#2780)
Vicent Gilabert04434501a403
diff --git a/docs/generate_examples.py b/docs/generate_examples.pyindex 41e40ed86..e402fcffe 100644--- a/docs/generate_examples.py+++ b/docs/generate_examples.py@@ -143,6 +143,7 @@ def main():"RandomFisheye": ((torch.tensor([-0.3, 0.3]), torch.tensor([-0.3, 0.3]), torch.tensor([0.9, 1.0])), 2, 2020),"RandomGamma": (((0.0, 1.0),), 2, 2022),"RandomGaussianBlur": (((3, 3), (0.1, 2.0)), 1, 2020),+ "RandomGaussianIllumination": (((0.5, 0.5), (0.5, 0.5), (0.5, 0.5), (-1.0, 1.0)), 2, 2021),"RandomGaussianNoise": ((0.0, 0.05), 1, 2020),"RandomGrayscale": ((), 1, 2020),"RandomHue": (((-0.5, 0.5),), 2, 2022),diff --git a/kornia/augmentation/_2d/intensity/__init__.py b/kornia/augmentation/_2d/intensity/__init__.pyindex 54d631489..5b6b4ba13 100644--- a/kornia/augmentation/_2d/intensity/__init__.py+++ b/kornia/augmentation/_2d/intensity/__init__.py@@ -11,6 +11,7 @@ from kornia.augmentation._2d.intensity.equalize import RandomEqualizefrom kornia.augmentation._2d.intensity.erasing import RandomErasingfrom kornia.augmentation._2d.intensity.gamma import RandomGammafrom kornia.augmentation._2d.intensity.gaussian_blur import RandomGaussianBlur+from kornia.augmentation._2d.intensity.gaussian_illumination import RandomGaussianIlluminationfrom kornia.augmentation._2d.intensity.gaussian_noise import RandomGaussianNoisefrom kornia.augmentation._2d.intensity.grayscale import RandomGrayscalefrom kornia.augmentation._2d.intensity.hue import RandomHuediff --git a/kornia/augmentation/_2d/intensity/gaussian_illumination.py b/kornia/augmentation/_2d/intensity/gaussian_illumination.pynew file mode 100644index 000000000..48705be65--- /dev/null+++ b/kornia/augmentation/_2d/intensity/gaussian_illumination.py@@ -0,0 +1,153 @@+from typing import Any, Dict, Optional, Tuple, Union++from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D+from kornia.augmentation.random_generator._2d import GaussianIlluminationGenerator+from kornia.core import Tensor+from kornia.core.check import KORNIA_CHECK+++class RandomGaussianIllumination(IntensityAugmentationBase2D):+ r"""Applies random 2D Gaussian illumination patterns to a batch of images.++ .. image:: _static/img/RandomGaussianIllumination.png++ Args:+ gain: Range for the gain factor (intensity) applied to the generated illumination.+ center: The center coordinates of the Gaussian distribution are expressed as a+ percentage of the spatial dimensions :math:(H, W).+ sigma: The sigma values (standard deviation) of the Gaussian distribution are expressed as a+ percentage of the spatial dimensions :math:(H, W).+ sign: Range for the sign of the Gaussian distribution. If only one sign is needed,+ insert only as a tuple or float.+ p: Probability of applying the transformation.+ same_on_batch: If True, apply the same transformation across the entire batch. Default is False.+ 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)`+ - Output: :math:`(B, C, H, W)`++ .. note::+ The generated random numbers are not reproducible across different devices and dtypes. By default,+ the parameters will be generated on CPU. This can be changed by calling+ ``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``.++ Examples:+ >>> rng = torch.manual_seed(1)+ >>> input = torch.ones(1, 3, 3, 3) * 0.5+ >>> aug = RandomGaussianIllumination(gain=0.5, p=1.)+ >>> aug(input)+ tensor([[[[0.7266, 1.0000, 0.7266],+ [0.6621, 0.9121, 0.6621],+ [0.5000, 0.6911, 0.5000]],+ <BLANKLINE>+ [[0.7266, 1.0000, 0.7266],+ [0.6621, 0.9121, 0.6621],+ [0.5000, 0.6911, 0.5000]],+ <BLANKLINE>+ [[0.7266, 1.0000, 0.7266],+ [0.6621, 0.9121, 0.6621],+ [0.5000, 0.6911, 0.5000]]]])++ To apply the exact augmenation again, you may take the advantage of the previous parameter state:+ >>> input = torch.rand(1, 3, 32, 32)+ >>> aug = RandomGaussianIllumination(p=1.)+ >>> (aug(input) == aug(input, params=aug._params)).all()+ tensor(True)+ """++ def __init__(+ self,+ gain: Optional[Union[float, Tuple[float, float]]] = (0.01, 0.15),+ center: Optional[Union[float, Tuple[float, float]]] = (0.1, 0.9),+ sigma: Optional[Union[float, Tuple[float, float]]] = (0.2, 1.0),+ sign: Optional[Union[float, Tuple[float, float]]] = (-1.0, 1.0),+ p: float = 0.5,+ same_on_batch: bool = False,+ keepdim: bool = False,+ ) -> None:+ super().__init__(p=p, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim)++ # Validation and initialization of amount parameter.+ if isinstance(gain, (tuple, float)):+ if isinstance(gain, float):+ gain = (gain, gain)+ elif len(gain) == 1:+ gain = (gain[0], gain[0])+ elif len(gain) > 2 or len(gain) <= 0:+ raise ValueError(+ "The length of gain must be greater than 0 \+ and less than or equal to 2, and it should be a tuple or a float."+ )+ else:+ raise ValueError("gain must be a tuple or a float")+ KORNIA_CHECK(+ all(0 <= el <= 1 for el in gain),+ "gain values must be between 0 and 1. Recommended values less than 0.2.",+ )++ if isinstance(center, (tuple, float)):+ if isinstance(center, float):+ center = (center, center)+ elif len(center) == 1:+ center = (center[0], center[0])+ elif len(center) > 2 or len(center) <= 0:+ raise ValueError(+ "The length of center must be greater than 0 \+ and less than or equal to 2, and it should be a tuple or a float."+ )+ else:+ raise ValueError("center must be a tuple or a float")+ KORNIA_CHECK(+ all(0 <= el <= 1 for el in center),+ "center of gaussian value must be between 0 and 1.",+ )++ if isinstance(sigma, (tuple, float)):+ if isinstance(sigma, float):+ sigma = (sigma, sigma)+ elif len(sigma) == 1:+ sigma = (sigma[0], sigma[0])+ elif len(sigma) > 2 or len(sigma) <= 0:+ raise ValueError(+ "The length of sigma must be greater than 0 \+ and less than or equal to 2, and it should be a tuple or a float."+ )+ else:+ raise ValueError("sigma must be a tuple or a float")+ KORNIA_CHECK(+ all(0 <= el <= 1 for el in sigma),+ "sigma of gaussian value must be between 0 and 1.",+ )++ if isinstance(sign, (tuple, float)):+ if isinstance(sign, float):+ sign = (sign, sign)+ elif len(sign) == 1:+ sign = (sign[0], sign[0])+ elif len(sign) > 2 or len(sign) <= 0:+ raise ValueError(+ "The length of sign must be greater than 0 \+ and less than or equal to 2, and it should be a tuple or a float."+ )+ else:+ raise ValueError("sign must be a tuple or a float")+ KORNIA_CHECK(+ all(-1 <= el <= 1 for el in sign),+ "sign of gaussian value must be between -1 and 1.",+ )++ # Generator of random parameters and masks.+ self._param_generator = GaussianIlluminationGenerator(gain, center, sigma, sign)++ def apply_transform(+ self,+ input: Tensor,+ params: Dict[str, Tensor],+ flags: Dict[str, Any],+ transform: Optional[Tensor] = None,+ ) -> Tensor:+ r"""Apply random gaussian gradient illumination to the input image."""++ return input.add(params["gradient"].to(input)).clamp(0, 1)diff --git a/kornia/augmentation/__init__.py b/kornia/augmentation/__init__.pyindex 6c4d02d15..df6ff7199 100644--- a/kornia/augmentation/__init__.py+++ b/kornia/augmentation/__init__.py@@ -23,6 +23,7 @@ from kornia.augmentation._2d import (RandomFisheye,RandomGamma,RandomGaussianBlur,+ RandomGaussianIllumination,RandomGaussianNoise,RandomGrayscale,RandomHorizontalFlip,@@ -116,6 +117,7 @@ __all__ = ["RandomGamma","RandomGrayscale","RandomGaussianBlur",+ "RandomGaussianIllumination","RandomGaussianNoise","RandomHorizontalFlip","RandomHue",diff --git a/kornia/augmentation/random_generator/_2d/__init__.py b/kornia/augmentation/random_generator/_2d/__init__.pyindex 5ff0cc2a8..cd683adf8 100644--- a/kornia/augmentation/random_generator/_2d/__init__.py+++ b/kornia/augmentation/random_generator/_2d/__init__.py@@ -4,6 +4,7 @@ from kornia.augmentation.random_generator._2d.color_jitter import *from kornia.augmentation.random_generator._2d.crop import *from kornia.augmentation.random_generator._2d.cutmix import *from kornia.augmentation.random_generator._2d.gaussian_blur import *+from kornia.augmentation.random_generator._2d.gaussian_illumination import *from kornia.augmentation.random_generator._2d.jigsaw import *from kornia.augmentation.random_generator._2d.mixup import *from kornia.augmentation.random_generator._2d.mosaic import *diff --git a/kornia/augmentation/random_generator/_2d/gaussian_illumination.py b/kornia/augmentation/random_generator/_2d/gaussian_illumination.pynew file mode 100644index 000000000..207919d36--- /dev/null+++ b/kornia/augmentation/random_generator/_2d/gaussian_illumination.py@@ -0,0 +1,113 @@+from __future__ import annotations++import torch++from kornia.augmentation.random_generator.base import RandomGeneratorBase, UniformDistribution+from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _range_bound+from kornia.core import Tensor+from kornia.enhance import normalize_min_max+from kornia.filters.kernels import gaussian+from kornia.utils import _extract_device_dtype+++class GaussianIlluminationGenerator(RandomGeneratorBase):+ r"""Generates random 2D Gaussian illumination patterns for image augmentation.++ Args:+ gain: Range for the gain factor applied to the generated illumination.+ center: Range for the center coordinates of the Gaussian distribution.+ sigma: Range for the standard deviation of the Gaussian distribution.+ sign: Range for the sign of the Gaussian distribution.++ Returns:+ A dictionary of parameters to be passed for transformation.+ - gradient: : Generated 2D Gaussian illumination pattern with shape (B, C, H, W).++ Note:+ The generated random numbers are not reproducible across different devices and dtypes. By default,+ the parameters will be generated on CPU. This can be changed by calling+ ``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``.+ """++ def __init__(+ self,+ gain: tuple[float, float],+ center: tuple[float, float],+ sigma: tuple[float, float],+ sign: tuple[float, float],+ ) -> None:+ super().__init__()+ self.gain = gain+ self.center = center+ self.sigma = sigma+ self.sign = sign++ def __repr__(self) -> str:+ r"""Return a string representation of the object."""+ repr = f"gain={self.gain}, center={self.center}, sigma={self.sigma}, sign={self.sign}"+ return repr++ def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:+ r"""Create samplers for generating random gaussian illumination parameters."""++ gain = _range_bound(+ self.gain,+ "gain",+ ).to(device, dtype)+ self.gain_sampler = UniformDistribution(gain[0], gain[1], validate_args=False)++ center = _range_bound(+ self.center,+ "center",+ ).to(device, dtype)+ self.center_sampler = UniformDistribution(center[0], center[1], validate_args=False)++ sigma = _range_bound(+ self.sigma,+ "sigma",+ ).to(device, dtype)+ self.sigma_sampler = UniformDistribution(sigma[0], sigma[1], validate_args=False)++ sign = _range_bound(self.sign, "sign", bounds=(-1.0, 1.0), center=0.0).to(device, dtype)+ self.sign_sampler = UniformDistribution(sign[0], sign[1], validate_args=False)++ def forward(self, batch_shape: tuple[int, ...], same_on_batch: bool = False) -> dict[str, Tensor]:+ r"""Generate random 2D Gaussian illumination patterns."""+ batch_size, channels, height, width = batch_shape+ _common_param_check(batch_size, same_on_batch)+ _device, _dtype = _extract_device_dtype([self.gain, self.center, self.sigma])++ gain_factor = _adapted_rsampling((batch_size, 1, 1, 1), self.gain_sampler, same_on_batch).to(+ device=_device, dtype=_dtype+ )+ sigma_x = width * _adapted_rsampling((batch_size, 1), self.sigma_sampler, same_on_batch).to(+ device=_device, dtype=_dtype+ )+ center_x = torch.round(width * _adapted_rsampling((batch_size, 1), self.center_sampler, same_on_batch)).to(+ device=_device, dtype=_dtype+ )+ sigma_y = height * _adapted_rsampling((batch_size, 1), self.sigma_sampler, same_on_batch).to(+ device=_device, dtype=_dtype+ )+ center_y = torch.round(height * _adapted_rsampling((batch_size, 1), self.center_sampler, same_on_batch)).to(+ device=_device, dtype=_dtype+ )+ sign = torch.where(+ _adapted_rsampling((batch_size, 1, 1, 1), self.sign_sampler, same_on_batch) >= 0.0,+ torch.tensor(1),+ torch.tensor(-1),+ ).to(device=_device, dtype=_dtype)++ # Generate random gaussian for create a 2D gaussian image.+ gauss_x = gaussian(width, sigma_x, mean=center_x).unsqueeze(1)+ gauss_y = gaussian(height, sigma_y, mean=center_y).unsqueeze(2)+ # gradient = (batch_size, channels, height, width)+ gradient = torch.matmul(gauss_y, gauss_x).unsqueeze(1).repeat(1, channels, 1, 1)++ # Normalize between 0-1 to apply the gain factor.+ gradient = normalize_min_max(gradient, min_val=0.0, max_val=1.0)+ gradient = sign * gain_factor * gradient++ return {+ "gradient": gradient.to(device=_device, dtype=_dtype),+ }diff --git a/kornia/filters/kernels.py b/kornia/filters/kernels.pyindex aa97103a3..ff40d32b1 100644--- a/kornia/filters/kernels.py+++ b/kornia/filters/kernels.py@@ -2,7 +2,7 @@ from __future__ import annotationsimport mathfrom math import sqrt-from typing import Any, Optional+from typing import Any, Optional, Unionimport torch@@ -60,13 +60,20 @@ def normalize_kernel2d(input: Tensor) -> Tensor:def gaussian(- window_size: int, sigma: Tensor | float, *, device: Optional[Device] = None, dtype: Optional[Dtype] = None+ window_size: int,+ sigma: Tensor | float,+ *,+ mean: Optional[Union[Tensor, float]] = None,+ device: Optional[Device] = None,+ dtype: Optional[Dtype] = None,) -> Tensor:"""Compute the gaussian values based on the window and sigma values.Args:window_size: the size which drives the filter amount.sigma: gaussian standard deviation. If a tensor, should be in a shape :math:`(B, 1)`+ mean: Mean of the Gaussian function (center). If not provided, it defaults to window_size // 2.+ If a tensor, should be in a shape :math:`(B, 1)`device: This value will be used if sigma is a float. Device desired to compute.dtype: This value will be used if sigma is a float. Dtype desired for compute.Returns:@@ -80,7 +87,14 @@ def gaussian(KORNIA_CHECK_SHAPE(sigma, ["B", "1"])batch_size = sigma.shape[0]- x = (torch.arange(window_size, device=sigma.device, dtype=sigma.dtype) - window_size // 2).expand(batch_size, -1)+ mean = float(window_size // 2) if mean is None else mean+ if isinstance(mean, float):+ mean = tensor([[mean]], device=device, dtype=dtype)++ KORNIA_CHECK_IS_TENSOR(mean)+ KORNIA_CHECK_SHAPE(mean, ["B", "1"])++ x = (torch.arange(window_size, device=sigma.device, dtype=sigma.dtype) - mean).expand(batch_size, -1)if window_size % 2 == 0:x = x + 0.5diff --git a/tests/augmentation/test_augmentation.py b/tests/augmentation/test_augmentation.pyindex dfab8a5d7..9c28f0f93 100644--- a/tests/augmentation/test_augmentation.py+++ b/tests/augmentation/test_augmentation.py@@ -27,6 +27,7 @@ from kornia.augmentation import (RandomFisheye,RandomGamma,RandomGaussianBlur,+ RandomGaussianIllumination,RandomGaussianNoise,RandomGrayscale,RandomHorizontalFlip,@@ -3291,6 +3292,81 @@ class TestRandomSaltAndPepperNoise(BaseTester):self.assert_close(output_tensor[0], output_tensor[1])+class TestRandomGaussianIllumination(BaseTester):+ def _get_expected(self, device, dtype):+ return torch.tensor(+ [+ [+ [+ [0.726599991321564, 1.000000000000000, 0.726599991321564],+ [0.662100017070770, 0.912100017070770, 0.662100017070770],+ [0.500000000000000, 0.691100001335144, 0.500000000000000],+ ],+ [+ [0.726599991321564, 1.000000000000000, 0.726599991321564],+ [0.662100017070770, 0.912100017070770, 0.662100017070770],+ [0.500000000000000, 0.691100001335144, 0.500000000000000],+ ],+ [+ [0.726599991321564, 1.000000000000000, 0.726599991321564],+ [0.662100017070770, 0.912100017070770, 0.662100017070770],+ [0.500000000000000, 0.691100001335144, 0.500000000000000],+ ],+ ]+ ],+ device=device,+ dtype=dtype,+ )++ def test_smoke(self, device, dtype):+ torch.manual_seed(1)+ input_tensor = torch.ones(1, 3, 3, 3, device=device, dtype=dtype) * 0.5+ expected = self._get_expected(device=device, dtype=dtype)+ aug = RandomGaussianIllumination(gain=0.5, p=1.0)+ res = aug(input_tensor)+ assert input_tensor.shape == res.shape+ self.assert_close(res, expected, rtol=1e-4, atol=1e-4)++ def test_exception(self, device, dtype):+ with pytest.raises(ValueError, match="sign must be a tuple or a float"):+ RandomGaussianIllumination(sign=3)++ with pytest.raises(ValueError, match="center must be a tuple or a float"):+ RandomGaussianIllumination(center=3)++ with pytest.raises(ValueError, match="sigma must be a tuple or a float"):+ RandomGaussianIllumination(sigma=[0.01, 0.06])++ with pytest.raises(ValueError, match="gain must be a tuple or a float"):+ RandomGaussianIllumination(gain=[0.01, 0.06])++ with pytest.raises(Exception, match="gain values must be between 0 and 1. Recommended values less than 0.2."):+ RandomGaussianIllumination(gain=(0.01, 2))++ with pytest.raises(Exception, match="sigma of gaussian value must be between 0 and 1."):+ RandomGaussianIllumination(sigma=(0.01, 2))++ with pytest.raises(Exception, match="center of gaussian value must be between 0 and 1."):+ RandomGaussianIllumination(center=(0.01, 2))++ with pytest.raises(Exception, match="sign of gaussian value must be between -1 and 1."):+ RandomGaussianIllumination(sign=(0.01, 2))++ @pytest.mark.parametrize("channel_shape, batch_shape", [(1, 1), (3, 2), (5, 3)])+ def test_cardinality(self, batch_shape, channel_shape, device, dtype):+ input_tensor = torch.ones(batch_shape, channel_shape, 16, 16, device=device, dtype=dtype) * 0.5+ transform = RandomGaussianIllumination(p=1.0)+ output_tensor = transform(input_tensor)+ assert input_tensor.shape[0] == output_tensor.shape[0]+ assert input_tensor.shape[1] == output_tensor.shape[1]++ def test_same_on_batch(self, device, dtype):+ input_tensor = torch.ones(2, 1, 5, 5, device=device, dtype=dtype) * 0.5+ transform = RandomGaussianIllumination(p=1.0, same_on_batch=True)+ output_tensor = transform(input_tensor)+ self.assert_close(output_tensor[0], output_tensor[1])++class TestNormalize(BaseTester):# TODO: improve and implement more meaningful smoke tests e.g check for a consistent# return values such a Tensor variable.diff --git a/tests/filters/test_gaussian.py b/tests/filters/test_gaussian.pyindex a8d2608bc..da6f71979 100644--- a/tests/filters/test_gaussian.py+++ b/tests/filters/test_gaussian.py@@ -3,6 +3,7 @@ import torchfrom kornia.filters import (GaussianBlur2d,+ gaussian,gaussian_blur2d,get_gaussian_discrete_kernel1d,get_gaussian_erf_kernel1d,@@ -14,6 +15,36 @@ from kornia.filters import (from testing.base import BaseTester, assert_close+ "window_size, sigma, mean, expected",+ [+ (5, 1.0, None, torch.tensor([[0.0545, 0.2442, 0.4026, 0.2442, 0.0545]])),+ (+ 11,+ 5.0,+ None,+ [[0.0663, 0.0794, 0.0914, 0.1010, 0.1072, 0.1094, 0.1072, 0.1010, 0.0914, 0.0794, 0.0663]],+ ),+ (+ 11,+ 5.0,+ 8.0,+ [[0.0343, 0.0463, 0.0600, 0.0747, 0.0895, 0.1029, 0.1138, 0.1208, 0.1232, 0.1208, 0.1138]],+ ),+ (+ 11,+ 11.0,+ 3.0,+ [[0.0926, 0.0946, 0.0957, 0.0961, 0.0957, 0.0946, 0.0926, 0.0900, 0.0867, 0.0828, 0.0785]],+ ),+ ],+)+def test_gaussian(window_size, sigma, mean, expected, device, dtype):+ expected = torch.tensor(expected, device=device, dtype=dtype)+ result = gaussian(window_size, sigma, mean=mean, device=device, dtype=dtype)+ assert_close(result, expected, atol=1e-4, rtol=1e-4)++@pytest.mark.parametrize("window_size", [5, 11])@pytest.mark.parametrize("sigma", [1.5, 5.0])def test_get_gaussian_kernel1d_float(window_size, sigma, device, dtype):