Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

feat: RandomLinearIllumination and RandomLinearCornerIllumination (#2823)

Vicent Gilabert086a97b71364
diff --git a/docs/generate_examples.py b/docs/generate_examples.py
index e7b22fced..945f2aa05 100644
--- a/docs/generate_examples.py
+++ b/docs/generate_examples.py
@@ -150,6 +150,8 @@ def main():
"RandomHorizontalFlip": ((), 1, 2020),
"RandomInvert": ((), 1, 2020),
"RandomJPEG": (((1.0, 5.0),), 1, 2024),
+ "RandomLinearCornerIllumination": (((0.5, 0.5), (-1.0, 1.0)), 2, 2021),
+ "RandomLinearIllumination": (((0.5, 0.5), (-1.0, 1.0)), 2, 2021),
"RandomMedianBlur": (((3, 3),), 1, 2023),
"RandomMotionBlur": ((7, 35.0, 0.5), 2, 2020),
"RandomPerspective": ((0.2,), 2, 2020),
diff --git a/kornia/augmentation/_2d/intensity/__init__.py b/kornia/augmentation/_2d/intensity/__init__.py
index 2c6fb82ab..d8c9fff6e 100644
--- a/kornia/augmentation/_2d/intensity/__init__.py
+++ b/kornia/augmentation/_2d/intensity/__init__.py
@@ -17,6 +17,10 @@ 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.jpeg import RandomJPEG
+from kornia.augmentation._2d.intensity.linear_illumination import (
+ RandomLinearCornerIllumination,
+ RandomLinearIllumination,
+)
from kornia.augmentation._2d.intensity.median_blur import RandomMedianBlur
from kornia.augmentation._2d.intensity.motion_blur import RandomMotionBlur
from kornia.augmentation._2d.intensity.normalize import Normalize
diff --git a/kornia/augmentation/_2d/intensity/linear_illumination.py b/kornia/augmentation/_2d/intensity/linear_illumination.py
new file mode 100644
index 000000000..c16278dfb
--- /dev/null
+++ b/kornia/augmentation/_2d/intensity/linear_illumination.py
@@ -0,0 +1,219 @@
+from typing import Any, Dict, Optional, Tuple, Union
+
+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
+from kornia.augmentation.random_generator._2d import LinearCornerIlluminationGenerator, LinearIlluminationGenerator
+from kornia.core import Tensor
+from kornia.core.check import KORNIA_CHECK
+
+
+class RandomLinearIllumination(IntensityAugmentationBase2D):
+ r"""Applies random 2D Linear illumination patterns to a batch of images.
+
+ .. image:: _static/img/RandomLinearIllumination.png
+
+ Args:
+ gain: Range for the gain factor (intensity) applied to the generated illumination.
+ sign: Range for the sign of the 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 = RandomLinearIllumination(gain=0.25, p=1.)
+ >>> aug(input)
+ tensor([[[[0.2500, 0.2500, 0.2500],
+ [0.3750, 0.3750, 0.3750],
+ [0.5000, 0.5000, 0.5000]],
+ <BLANKLINE>
+ [[0.2500, 0.2500, 0.2500],
+ [0.3750, 0.3750, 0.3750],
+ [0.5000, 0.5000, 0.5000]],
+ <BLANKLINE>
+ [[0.2500, 0.2500, 0.2500],
+ [0.3750, 0.3750, 0.3750],
+ [0.5000, 0.5000, 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 = RandomLinearIllumination(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.2),
+ 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(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 linear value must be between -1 and 1.",
+ )
+
+ # Generator of random parameters and masks.
+ self._param_generator = LinearIlluminationGenerator(gain, 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)
+
+
+class RandomLinearCornerIllumination(IntensityAugmentationBase2D):
+ r"""Applies random 2D Linear from corner illumination patterns to a batch of images.
+
+ .. image:: _static/img/RandomLinearCornerIllumination.png
+
+ Args:
+ gain: Range for the gain factor (intensity) applied to the generated illumination.
+ sign: Range for the sign of the 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 = RandomLinearCornerIllumination(gain=0.25, p=1.)
+ >>> aug(input)
+ tensor([[[[0.3750, 0.4375, 0.5000],
+ [0.3125, 0.3750, 0.4375],
+ [0.2500, 0.3125, 0.3750]],
+ <BLANKLINE>
+ [[0.3750, 0.4375, 0.5000],
+ [0.3125, 0.3750, 0.4375],
+ [0.2500, 0.3125, 0.3750]],
+ <BLANKLINE>
+ [[0.3750, 0.4375, 0.5000],
+ [0.3125, 0.3750, 0.4375],
+ [0.2500, 0.3125, 0.3750]]]])
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.rand(1, 3, 32, 32)
+ >>> aug = RandomLinearCornerIllumination(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.2),
+ 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(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 linear value must be between -1 and 1.",
+ )
+
+ # Generator of random parameters and masks.
+ self._param_generator = LinearCornerIlluminationGenerator(gain, 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__.py
index e642a3e05..bd71f94b5 100644
--- a/kornia/augmentation/__init__.py
+++ b/kornia/augmentation/__init__.py
@@ -31,6 +31,8 @@ from kornia.augmentation._2d import (
RandomInvert,
RandomJigsaw,
RandomJPEG,
+ RandomLinearCornerIllumination,
+ RandomLinearIllumination,
RandomMedianBlur,
RandomMixUpV2,
RandomMosaic,
@@ -139,6 +141,8 @@ __all__ = [
"RandomRain",
"RandomPosterize",
"RandomEqualize",
+ "RandomLinearCornerIllumination",
+ "RandomLinearIllumination",
"RandomMotionBlur",
"RandomInvert",
"RandomThinPlateSpline",
diff --git a/kornia/augmentation/random_generator/_2d/__init__.py b/kornia/augmentation/random_generator/_2d/__init__.py
index 6d8855dc7..3b4c6e4eb 100644
--- a/kornia/augmentation/random_generator/_2d/__init__.py
+++ b/kornia/augmentation/random_generator/_2d/__init__.py
@@ -7,6 +7,7 @@ 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.jpeg import *
+from kornia.augmentation.random_generator._2d.linear_illumination import *
from kornia.augmentation.random_generator._2d.mixup import *
from kornia.augmentation.random_generator._2d.mosaic import *
from kornia.augmentation.random_generator._2d.motion_blur import *
diff --git a/kornia/augmentation/random_generator/_2d/linear_illumination.py b/kornia/augmentation/random_generator/_2d/linear_illumination.py
new file mode 100644
index 000000000..627eaf3aa
--- /dev/null
+++ b/kornia/augmentation/random_generator/_2d/linear_illumination.py
@@ -0,0 +1,176 @@
+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.normalize import normalize_min_max
+from kornia.utils import _extract_device_dtype
+
+
+class LinearIlluminationGenerator(RandomGeneratorBase):
+ r"""Generates random 2D Linear illumination patterns for image augmentation.
+
+ Args:
+ gain: Range for the gain factor applied to the generated illumination.
+ sign: Range for the sign of the Linear distribution.
+
+ Returns:
+ A dictionary of parameters to be passed for transformation.
+ - gradient: : Generated 2D Linear 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],
+ sign: tuple[float, float],
+ ) -> None:
+ super().__init__()
+ self.gain = gain
+ self.sign = sign
+
+ def __repr__(self) -> str:
+ r"""Return a string representation of the object."""
+ repr = f"gain={self.gain}, 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)
+
+ 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)
+
+ self.directions_sampler = UniformDistribution(0, 4, 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.sign])
+
+ gain_factor = _adapted_rsampling((batch_size, 1, 1, 1), self.gain_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)
+
+ directions = _adapted_rsampling((batch_size, 1, 1, 1), self.directions_sampler, same_on_batch).to(
+ device=_device,
+ dtype=torch.int8,
+ )
+
+ gradient = torch.zeros(batch_shape)
+ for _b in range(batch_size):
+ if directions[_b] == 0: # Lower
+ gradient[_b] = torch.linspace(0, 1, height).unsqueeze(1).expand(channels, height, width)
+ elif directions[_b] == 1: # Upper
+ gradient[_b] = torch.linspace(1, 0, height).unsqueeze(1).expand(channels, height, width)
+ elif directions[_b] == 2: # Left
+ gradient[_b] = torch.linspace(0, 1, width).unsqueeze(0).expand(channels, height, width)
+ elif directions[_b] == 3: # Right
+ gradient[_b] = torch.linspace(1, 0, width).unsqueeze(0).expand(channels, height, width)
+
+ gradient = sign * gain_factor * gradient
+
+ return {
+ "gradient": gradient.to(device=_device, dtype=_dtype),
+ }
+
+
+class LinearCornerIlluminationGenerator(RandomGeneratorBase):
+ r"""Generates random 2D Linear (from corner) illumination patterns for image augmentation.
+
+ Args:
+ gain: Range for the gain factor applied to the generated illumination.
+ sign: Range for the sign of the linear distribution.
+
+ Returns:
+ A dictionary of parameters to be passed for transformation.
+ - gradient: : Generated 2D Linear 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],
+ sign: tuple[float, float],
+ ) -> None:
+ super().__init__()
+ self.gain = gain
+ self.sign = sign
+
+ def __repr__(self) -> str:
+ r"""Return a string representation of the object."""
+ repr = f"gain={self.gain}, 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)
+
+ 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)
+
+ self.directions_sampler = UniformDistribution(0, 4, 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.sign])
+
+ gain_factor = _adapted_rsampling((batch_size, 1, 1, 1), self.gain_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)
+
+ directions = _adapted_rsampling((batch_size, 1, 1, 1), self.directions_sampler, same_on_batch).to(
+ device=_device,
+ dtype=torch.int8,
+ )
+
+ y_grad = torch.linspace(0, 1, height).unsqueeze(1).expand(channels, height, width)
+ x_grad = torch.linspace(0, 1, width).unsqueeze(0).expand(channels, height, width)
+ gradient = torch.zeros(batch_shape)
+ for _b in range(batch_size):
+ if directions[_b] == 0: # Bottom right
+ gradient[_b] = x_grad + y_grad
+ elif directions[_b] == 1: # Bottom left
+ gradient[_b] = -x_grad + y_grad
+ elif directions[_b] == 2: # Upper right
+ gradient[_b] = x_grad - y_grad
+ elif directions[_b] == 3: # Upper left
+ gradient[_b] = 1 - (x_grad + y_grad)
+ gradient = sign * gain_factor * normalize_min_max(gradient)
+
+ return {
+ "gradient": gradient.to(device=_device, dtype=_dtype),
+ }
diff --git a/tests/augmentation/test_augmentation.py b/tests/augmentation/test_augmentation.py
index 03cc32892..f9209308c 100644
--- a/tests/augmentation/test_augmentation.py
+++ b/tests/augmentation/test_augmentation.py
@@ -34,6 +34,8 @@ from kornia.augmentation import (
RandomHue,
RandomInvert,
RandomJPEG,
+ RandomLinearCornerIllumination,
+ RandomLinearIllumination,
RandomMedianBlur,
RandomPlanckianJitter,
RandomPlasmaBrightness,
@@ -3368,6 +3370,132 @@ class TestRandomGaussianIllumination(BaseTester):
self.assert_close(output_tensor[0], output_tensor[1])
+class TestRandomLinearIllumination(BaseTester):
+ def _get_expected(self, device, dtype):
+ return torch.tensor(
+ [
+ [
+ [
+ [0.2500000000, 0.2500000000, 0.2500000000],
+ [0.3750000000, 0.3750000000, 0.3750000000],
+ [0.5000000000, 0.5000000000, 0.5000000000],
+ ],
+ [
+ [0.2500000000, 0.2500000000, 0.2500000000],
+ [0.3750000000, 0.3750000000, 0.3750000000],
+ [0.5000000000, 0.5000000000, 0.5000000000],
+ ],
+ [
+ [0.2500000000, 0.2500000000, 0.2500000000],
+ [0.3750000000, 0.3750000000, 0.3750000000],
+ [0.5000000000, 0.5000000000, 0.5000000000],
+ ],
+ ]
+ ],
+ 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 = RandomLinearIllumination(gain=0.25, 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"):
+ RandomLinearIllumination(sign=3)
+
+ with pytest.raises(ValueError, match="gain must be a tuple or a float"):
+ RandomLinearIllumination(gain=[0.01, 0.06])
+
+ with pytest.raises(Exception, match="gain values must be between 0 and 1. Recommended values less than 0.2."):
+ RandomLinearIllumination(gain=(0.01, 2))
+
+ with pytest.raises(Exception, match="sign of linear value must be between -1 and 1."):
+ RandomLinearIllumination(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 TestRandomLinearCornerIllumination(BaseTester):
+ def _get_expected(self, device, dtype):
+ return torch.tensor(
+ [
+ [
+ [
+ [0.3750000596, 0.4375000298, 0.5000000000],
+ [0.3125000894, 0.3750000596, 0.4375000298],
+ [0.2500001192, 0.3125000894, 0.3750000596],
+ ],
+ [
+ [0.3750000596, 0.4375000298, 0.5000000000],
+ [0.3125000894, 0.3750000596, 0.4375000298],
+ [0.2500001192, 0.3125000894, 0.3750000596],
+ ],
+ [
+ [0.3750000596, 0.4375000298, 0.5000000000],
+ [0.3125000894, 0.3750000596, 0.4375000298],
+ [0.2500001192, 0.3125000894, 0.3750000596],
+ ],
+ ]
+ ],
+ 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 = RandomLinearCornerIllumination(gain=0.25, 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"):
+ RandomLinearCornerIllumination(sign=3)
+
+ with pytest.raises(ValueError, match="gain must be a tuple or a float"):
+ RandomLinearCornerIllumination(gain=[0.01, 0.06])
+
+ with pytest.raises(Exception, match="gain values must be between 0 and 1. Recommended values less than 0.2."):
+ RandomLinearCornerIllumination(gain=(0.01, 2))
+
+ with pytest.raises(Exception, match="sign of linear value must be between -1 and 1."):
+ RandomLinearCornerIllumination(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 = RandomLinearCornerIllumination(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 = RandomLinearCornerIllumination(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.