Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

[Feat] Initiate AutoAugment modules (#2181)

Jian Shi3bed5f67455d
diff --git a/docs/source/augmentation.auto.rst b/docs/source/augmentation.auto.rst
new file mode 100644
index 000000000..10badc626
--- /dev/null
+++ b/docs/source/augmentation.auto.rst
@@ -0,0 +1,44 @@
+Automatic Augmentation Methods
+==============================
+
+.. currentmodule:: kornia.augmentation.auto
+
+Augmentation Policy
+-------------------
+
+This module contains common data augmentation policies that can improve the accuracy of image classification models.
+
+.. autoclass:: AutoAugment
+
+ .. automethod:: get_transformation_matrix
+
+ .. automethod:: forward_parameters
+
+ .. automethod:: forward
+
+ .. automethod:: inverse
+
+.. autoclass:: RandomAugment
+
+ .. automethod:: get_transformation_matrix
+
+ .. automethod:: forward_parameters
+
+ .. automethod:: forward
+
+ .. automethod:: inverse
+
+.. autoclass:: TrivialAugment
+
+ .. automethod:: get_transformation_matrix
+
+ .. automethod:: forward_parameters
+
+ .. automethod:: forward
+
+ .. automethod:: inverse
+
+Augmentation Search Methods
+---------------------------
+
+WIP. This module contains common data augmentation search methods.
diff --git a/docs/source/augmentation.rst b/docs/source/augmentation.rst
index 1c262b1b4..8cd40e73b 100644
--- a/docs/source/augmentation.rst
+++ b/docs/source/augmentation.rst
@@ -59,6 +59,7 @@ Benchmark
.. toctree::
+ augmentation.auto
augmentation.base
augmentation.container
augmentation.module
diff --git a/docs/source/references.bib b/docs/source/references.bib
index f0291da4e..a83614700 100644
--- a/docs/source/references.bib
+++ b/docs/source/references.bib
@@ -276,3 +276,33 @@ month = {mar}
biburl = {https://dblp.org/rec/journals/corr/abs-2006-04250.bib},
bibsource = {dblp computer science bibliography, https://dblp.org}
}
+
+@article{rommel2022deep,
+ title={Deep invariant networks with differentiable augmentation layers},
+ author={Rommel, C{\'e}dric and Moreau, Thomas and Gramfort, Alexandre},
+ journal={arXiv preprint arXiv:2202.02142},
+ year={2022}
+}
+
+@article{cubuk2018autoaugment,
+ title={Autoaugment: Learning augmentation policies from data},
+ author={Cubuk, Ekin D and Zoph, Barret and Mane, Dandelion and Vasudevan, Vijay and Le, Quoc V},
+ journal={arXiv preprint arXiv:1805.09501},
+ year={2018}
+}
+
+@inproceedings{cubuk2020randaugment,
+ title={Randaugment: Practical automated data augmentation with a reduced search space},
+ author={Cubuk, Ekin D and Zoph, Barret and Shlens, Jonathon and Le, Quoc V},
+ booktitle={Proceedings of the IEEE/CVF conference on computer vision and pattern recognition workshops},
+ pages={702--703},
+ year={2020}
+}
+
+@inproceedings{muller2021trivialaugment,
+ title={Trivialaugment: Tuning-free yet state-of-the-art data augmentation},
+ author={M{\"u}ller, Samuel G and Hutter, Frank},
+ booktitle={Proceedings of the IEEE/CVF international conference on computer vision},
+ pages={774--782},
+ year={2021}
+}
diff --git a/kornia/augmentation/_2d/base.py b/kornia/augmentation/_2d/base.py
index ba7e2502b..3807d6e56 100644
--- a/kornia/augmentation/_2d/base.py
+++ b/kornia/augmentation/_2d/base.py
@@ -70,7 +70,10 @@ class RigidAffineAugmentationBase2D(AugmentationBase2D):
def generate_transformation_matrix(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
"""Generate transformation matrices with the given input and param settings."""
- to_apply = params['batch_prob']
+
+ batch_prob = params['batch_prob']
+ to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions.
+
in_tensor = self.transform_tensor(input)
if not to_apply.any():
trans_matrix = self.identity_matrix(in_tensor)
diff --git a/kornia/augmentation/_2d/geometric/__init__.py b/kornia/augmentation/_2d/geometric/__init__.py
index 6ca86b72c..bfea3dac0 100644
--- a/kornia/augmentation/_2d/geometric/__init__.py
+++ b/kornia/augmentation/_2d/geometric/__init__.py
@@ -9,5 +9,7 @@ from kornia.augmentation._2d.geometric.perspective import RandomPerspective
from kornia.augmentation._2d.geometric.resize import LongestMaxSize, Resize, SmallestMaxSize
from kornia.augmentation._2d.geometric.resized_crop import RandomResizedCrop
from kornia.augmentation._2d.geometric.rotation import RandomRotation
+from kornia.augmentation._2d.geometric.shear import RandomShear
from kornia.augmentation._2d.geometric.thin_plate_spline import RandomThinPlateSpline
+from kornia.augmentation._2d.geometric.translate import RandomTranslate
from kornia.augmentation._2d.geometric.vertical_flip import RandomVerticalFlip
diff --git a/kornia/augmentation/_2d/geometric/affine.py b/kornia/augmentation/_2d/geometric/affine.py
index 9da954ee6..53efdf4bd 100644
--- a/kornia/augmentation/_2d/geometric/affine.py
+++ b/kornia/augmentation/_2d/geometric/affine.py
@@ -1,11 +1,9 @@
-from typing import Any, Dict, Optional, Tuple, Union, cast
-
-import torch
+from typing import Any, Dict, Optional, Tuple, Union
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
from kornia.constants import Resample, SamplePadding
-from kornia.core import Tensor
+from kornia.core import Tensor, as_tensor
from kornia.geometry.conversions import deg2rad
from kornia.geometry.transform import get_affine_matrix2d, warp_affine
@@ -97,19 +95,20 @@ class RandomAffine(GeometricAugmentationBase2D):
def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
return get_affine_matrix2d(
- torch.as_tensor(params["translations"], device=input.device, dtype=input.dtype),
- torch.as_tensor(params["center"], device=input.device, dtype=input.dtype),
- torch.as_tensor(params["scale"], device=input.device, dtype=input.dtype),
- torch.as_tensor(params["angle"], device=input.device, dtype=input.dtype),
- deg2rad(torch.as_tensor(params["sx"], device=input.device, dtype=input.dtype)),
- deg2rad(torch.as_tensor(params["sy"], device=input.device, dtype=input.dtype)),
+ as_tensor(params["translations"], device=input.device, dtype=input.dtype),
+ as_tensor(params["center"], device=input.device, dtype=input.dtype),
+ as_tensor(params["scale"], device=input.device, dtype=input.dtype),
+ as_tensor(params["angle"], device=input.device, dtype=input.dtype),
+ deg2rad(as_tensor(params["shear_x"], device=input.device, dtype=input.dtype)),
+ deg2rad(as_tensor(params["shear_y"], device=input.device, dtype=input.dtype)),
)
def apply_transform(
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
) -> Tensor:
_, _, height, width = input.shape
- transform = cast(Tensor, transform)
+ if not isinstance(transform, Tensor):
+ raise TypeError(f'Expected the `transform` be a Tensor. Got {type(transform)}.')
return warp_affine(
input,
@@ -127,9 +126,11 @@ class RandomAffine(GeometricAugmentationBase2D):
transform: Optional[Tensor] = None,
size: Optional[Tuple[int, int]] = None,
) -> Tensor:
+ if not isinstance(transform, Tensor):
+ raise TypeError(f'Expected the `transform` be a Tensor. Got {type(transform)}.')
return self.apply_transform(
input,
params=self._params,
- transform=torch.as_tensor(transform, device=input.device, dtype=input.dtype),
+ transform=as_tensor(transform, device=input.device, dtype=input.dtype),
flags=flags,
)
diff --git a/kornia/augmentation/_2d/geometric/base.py b/kornia/augmentation/_2d/geometric/base.py
index 03db1c692..119f7c360 100644
--- a/kornia/augmentation/_2d/geometric/base.py
+++ b/kornia/augmentation/_2d/geometric/base.py
@@ -1,4 +1,3 @@
-import warnings
from typing import Any, Dict, Optional, Tuple
from kornia.augmentation._2d.base import RigidAffineAugmentationBase2D
@@ -132,7 +131,8 @@ class GeometricAugmentationBase2D(RigidAffineAugmentationBase2D):
) -> Tensor:
in_tensor = self.transform_tensor(input)
output = in_tensor.clone()
- to_apply = params['batch_prob']
+ batch_prob = params['batch_prob']
+ to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions.
params, flags = self._process_kwargs_to_params_and_flags(
self._params if params is None else params, flags, **kwargs
@@ -185,10 +185,11 @@ class GeometricAugmentationBase2D(RigidAffineAugmentationBase2D):
**kwargs,
) -> Boxes:
output = input.clone()
- to_apply = params['batch_prob']
+ batch_prob = params['batch_prob']
+ to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions.
if transform is None:
- raise RuntimeError("transform matrix shall not be `None`.")
+ raise RuntimeError("`transform` has to be a tensor. Got None.")
params, flags = self._process_kwargs_to_params_and_flags(
self._params if params is None else params, flags, **kwargs
@@ -222,10 +223,11 @@ class GeometricAugmentationBase2D(RigidAffineAugmentationBase2D):
transform: the inverse tansformation matrix
"""
output = input.clone()
- to_apply = params['batch_prob']
+ batch_prob = params['batch_prob']
+ to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions.
if transform is None:
- raise RuntimeError("transform matrix shall not be `None`.")
+ raise RuntimeError("`transform` has to be a tensor. Got None.")
params, flags = self._process_kwargs_to_params_and_flags(
self._params if params is None else params, flags, **kwargs
@@ -263,7 +265,6 @@ class GeometricAugmentationBase2D(RigidAffineAugmentationBase2D):
"""
input_shape = input.shape
in_tensor = self.transform_tensor(input)
- batch_shape = input.shape
params, flags = self._process_kwargs_to_params_and_flags(
self._params if params is None else params, self.flags, **kwargs
@@ -273,10 +274,6 @@ class GeometricAugmentationBase2D(RigidAffineAugmentationBase2D):
params = self._params
transform = self.get_transformation_matrix(in_tensor, params=params, flags=flags)
- if 'batch_prob' not in params:
- params['batch_prob'] = as_tensor([True] * batch_shape[0])
- warnings.warn("`batch_prob` is not found in params. Will assume applying on all data.")
-
transform = self.compute_inverse_transformation(transform)
output = self.inverse_inputs(in_tensor, params, flags, transform)
diff --git a/kornia/augmentation/_2d/geometric/center_crop.py b/kornia/augmentation/_2d/geometric/center_crop.py
index 6b30186fe..9b6f97359 100644
--- a/kornia/augmentation/_2d/geometric/center_crop.py
+++ b/kornia/augmentation/_2d/geometric/center_crop.py
@@ -1,4 +1,4 @@
-from typing import Any, Dict, Optional, Tuple, Union, cast
+from typing import Any, Dict, Optional, Tuple, Union
import torch
from torch import Tensor
@@ -103,7 +103,8 @@ class CenterCrop(GeometricAugmentationBase2D):
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
) -> Tensor:
if flags["cropping_mode"] == "resample": # uses bilinear interpolation to crop
- transform = cast(Tensor, transform)
+ if not isinstance(transform, Tensor):
+ raise TypeError(f'Expected the `transform` be a Tensor. Got {type(transform)}.')
return crop_by_transform_mat(
input, transform[:, :2, :], self.size, flags["resample"].name.lower(), "zeros", flags["align_corners"]
@@ -125,7 +126,8 @@ class CenterCrop(GeometricAugmentationBase2D):
)
if size is None:
size = self.size
- transform = cast(Tensor, transform)
+ if not isinstance(transform, Tensor):
+ raise TypeError(f'Expected the `transform` be a Tensor. Got {type(transform)}.')
return crop_by_transform_mat(
input,
transform[:, :2, :],
diff --git a/kornia/augmentation/_2d/geometric/crop.py b/kornia/augmentation/_2d/geometric/crop.py
index 650ac185a..f90b60de0 100644
--- a/kornia/augmentation/_2d/geometric/crop.py
+++ b/kornia/augmentation/_2d/geometric/crop.py
@@ -1,4 +1,4 @@
-from typing import Any, Dict, List, Optional, Tuple, Union, cast
+from typing import Any, Dict, List, Optional, Tuple, Union
import torch
@@ -179,7 +179,8 @@ class RandomCrop(GeometricAugmentationBase2D):
flags = self.flags if flags is None else flags
if flags["cropping_mode"] == "resample": # uses bilinear interpolation to crop
- transform = cast(Tensor, transform)
+ if not isinstance(transform, Tensor):
+ raise TypeError(f'Expected the `transform` be a Tensor. Got {type(transform)}.')
# Fit the arg to F.pad
if flags['padding_mode'] == "constant":
padding_mode = "zeros"
@@ -213,8 +214,10 @@ class RandomCrop(GeometricAugmentationBase2D):
raise NotImplementedError(
f"`inverse` is only applicable for resample cropping mode. Got {flags['cropping_mode']}."
)
- size = cast(Tuple[int, int], size)
- transform = cast(Tensor, transform)
+ if size is None:
+ raise RuntimeError("`size` has to be a tuple. Got None.")
+ if not isinstance(transform, Tensor):
+ raise TypeError(f'Expected the `transform` be a Tensor. Got {type(transform)}.')
# Fit the arg to F.pad
if flags['padding_mode'] == "constant":
padding_mode = "zeros"
diff --git a/kornia/augmentation/_2d/geometric/horizontal_flip.py b/kornia/augmentation/_2d/geometric/horizontal_flip.py
index fb7c3a479..4c1637848 100644
--- a/kornia/augmentation/_2d/geometric/horizontal_flip.py
+++ b/kornia/augmentation/_2d/geometric/horizontal_flip.py
@@ -1,9 +1,9 @@
from typing import Any, Dict, Optional, Tuple
-import torch
from torch import Tensor
from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
+from kornia.core import as_tensor, tensor
from kornia.geometry.transform import hflip
@@ -55,7 +55,7 @@ class RandomHorizontalFlip(GeometricAugmentationBase2D):
def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
w: int = int(params["forward_input_shape"][-1])
- flip_mat: Tensor = torch.tensor([[-1, 0, w - 1], [0, 1, 0], [0, 0, 1]], device=input.device, dtype=input.dtype)
+ flip_mat: Tensor = tensor([[-1, 0, w - 1], [0, 1, 0], [0, 0, 1]], device=input.device, dtype=input.dtype)
return flip_mat.expand(input.shape[0], 3, 3)
@@ -71,9 +71,11 @@ class RandomHorizontalFlip(GeometricAugmentationBase2D):
transform: Optional[Tensor] = None,
size: Optional[Tuple[int, int]] = None,
) -> Tensor:
+ if not isinstance(transform, Tensor):
+ raise TypeError(f'Expected the `transform` be a Tensor. Got {type(transform)}.')
return self.apply_transform(
input,
params=self._params,
- transform=torch.as_tensor(transform, device=input.device, dtype=input.dtype),
+ transform=as_tensor(transform, device=input.device, dtype=input.dtype),
flags=flags,
)
diff --git a/kornia/augmentation/_2d/geometric/pad.py b/kornia/augmentation/_2d/geometric/pad.py
index 79d93f767..2c90840ae 100644
--- a/kornia/augmentation/_2d/geometric/pad.py
+++ b/kornia/augmentation/_2d/geometric/pad.py
@@ -1,4 +1,4 @@
-from typing import Any, Dict, Optional, Tuple, Union, cast
+from typing import Any, Dict, Optional, Tuple, Union
import torch
from torch import Tensor
@@ -73,5 +73,6 @@ class PadTo(GeometricAugmentationBase2D):
transform: Optional[Tensor] = None,
size: Optional[Tuple[int, int]] = None,
) -> Tensor:
- size = cast(Tuple[int, int], size)
+ if size is None:
+ raise RuntimeError("`size` has to be a tuple. Got None.")
return input[..., : size[0], : size[1]]
diff --git a/kornia/augmentation/_2d/geometric/perspective.py b/kornia/augmentation/_2d/geometric/perspective.py
index b7399d010..a14984994 100644
--- a/kornia/augmentation/_2d/geometric/perspective.py
+++ b/kornia/augmentation/_2d/geometric/perspective.py
@@ -78,7 +78,7 @@ class RandomPerspective(GeometricAugmentationBase2D):
) -> Tensor:
_, _, height, width = input.shape
if not isinstance(transform, Tensor):
- raise TypeError(f'Expected the transform be a Tensor. Gotcha {type(transform)}')
+ raise TypeError(f'Expected the `transform` be a Tensor. Got {type(transform)}.')
return warp_perspective(
input, transform, (height, width), mode=flags["resample"].name.lower(), align_corners=flags["align_corners"]
@@ -91,6 +91,8 @@ class RandomPerspective(GeometricAugmentationBase2D):
transform: Optional[Tensor] = None,
size: Optional[Tuple[int, int]] = None,
) -> Tensor:
+ if not isinstance(transform, Tensor):
+ raise TypeError(f'Expected the `transform` be a Tensor. Got {type(transform)}.')
return self.apply_transform(
input,
params=self._params,
diff --git a/kornia/augmentation/_2d/geometric/resize.py b/kornia/augmentation/_2d/geometric/resize.py
index ae4050a17..4271f3e2e 100644
--- a/kornia/augmentation/_2d/geometric/resize.py
+++ b/kornia/augmentation/_2d/geometric/resize.py
@@ -83,7 +83,7 @@ class Resize(GeometricAugmentationBase2D):
raise TypeError(f'Expected the size be a tuple. Gotcha {type(size)}')
if not isinstance(transform, Tensor):
- raise TypeError(f'Expected the transform be a Tensor. Gotcha {type(transform)}')
+ raise TypeError(f'Expected the `transform` be a Tensor. Got {type(transform)}.')
return crop_by_transform_mat(
input, transform[:, :2, :], size, flags["resample"].name.lower(), "zeros", flags["align_corners"]
diff --git a/kornia/augmentation/_2d/geometric/resized_crop.py b/kornia/augmentation/_2d/geometric/resized_crop.py
index ebd4b64db..8dc381ded 100644
--- a/kornia/augmentation/_2d/geometric/resized_crop.py
+++ b/kornia/augmentation/_2d/geometric/resized_crop.py
@@ -94,7 +94,7 @@ class RandomResizedCrop(GeometricAugmentationBase2D):
) -> Tensor:
if flags["cropping_mode"] == "resample": # uses bilinear interpolation to crop
if not isinstance(transform, Tensor):
- raise TypeError(f'Expected the transform be a Tensor. Gotcha {type(transform)}')
+ raise TypeError(f'Expected the `transform` be a Tensor. Got {type(transform)}.')
return crop_by_transform_mat(
input,
@@ -129,7 +129,7 @@ class RandomResizedCrop(GeometricAugmentationBase2D):
raise TypeError(f'Expected the size be a tuple. Gotcha {type(size)}')
if not isinstance(transform, Tensor):
- raise TypeError(f'Expected the transform be a Tensor. Gotcha {type(transform)}')
+ raise TypeError(f'Expected the `transform` be a Tensor. Got {type(transform)}.')
return crop_by_transform_mat(
input,
diff --git a/kornia/augmentation/_2d/geometric/rotation.py b/kornia/augmentation/_2d/geometric/rotation.py
index 94196f307..fc01ca0bd 100644
--- a/kornia/augmentation/_2d/geometric/rotation.py
+++ b/kornia/augmentation/_2d/geometric/rotation.py
@@ -91,7 +91,7 @@ class RandomRotation(GeometricAugmentationBase2D):
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
) -> Tensor:
if not isinstance(transform, Tensor):
- raise TypeError(f'Expected the transform be a Tensor. Gotcha {type(transform)}')
+ raise TypeError(f'Expected the `transform` be a Tensor. Got {type(transform)}.')
return affine(input, transform[..., :2, :3], flags["resample"].name.lower(), "zeros", flags["align_corners"])
@@ -102,6 +102,8 @@ class RandomRotation(GeometricAugmentationBase2D):
transform: Optional[Tensor] = None,
size: Optional[Tuple[int, int]] = None,
) -> Tensor:
+ if not isinstance(transform, Tensor):
+ raise TypeError(f'Expected the `transform` be a Tensor. Got {type(transform)}.')
return self.apply_transform(
input,
params=self._params,
diff --git a/kornia/augmentation/_2d/geometric/shear.py b/kornia/augmentation/_2d/geometric/shear.py
new file mode 100644
index 000000000..e9e0585ee
--- /dev/null
+++ b/kornia/augmentation/_2d/geometric/shear.py
@@ -0,0 +1,113 @@
+from typing import Any, Dict, Optional, Tuple, Union
+
+from kornia.augmentation import random_generator as rg
+from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
+from kornia.constants import Resample, SamplePadding
+from kornia.core import Tensor, as_tensor
+from kornia.geometry.conversions import deg2rad
+from kornia.geometry.transform import get_shear_matrix2d, warp_affine
+
+
+class RandomShear(GeometricAugmentationBase2D):
+ r"""Apply a random 2D shear transformation to a tensor image.
+
+ The transformation is computed so that the image center is kept invariant.
+
+ Args:
+ shear: Range of degrees to select from.
+ If float, a shear parallel to the x axis in the range (-shear, +shear) will be applied.
+ If (a, b), a shear parallel to the x axis in the range (-shear, +shear) will be applied.
+ If (a, b, c, d), then x-axis shear in (shear[0], shear[1]) and y-axis shear in (shear[2], shear[3])
+ will be applied. Will not apply shear by default.
+ resample: resample mode from "nearest" (0) or "bilinear" (1).
+ padding_mode: padding mode from "zeros" (0), "border" (1) or "refection" (2).
+ same_on_batch: apply the same transformation across the batch.
+ align_corners: interpolation flag.
+ 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).
+
+ Shape:
+ - Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`
+ - Output: :math:`(B, C, H, W)`
+
+ .. note::
+ This function internally uses :func:`kornia.geometry.transform.warp_affine`.
+
+ Examples:
+ >>> import torch
+ >>> rng = torch.manual_seed(0)
+ >>> input = torch.rand(1, 1, 3, 3)
+ >>> aug = RandomShear((-5., 2., 5., 10.), p=1.)
+ >>> out = aug(input)
+ >>> out, aug.transform_matrix
+ (tensor([[[[0.4420, 0.7598, 0.1536],
+ [0.1740, 0.3095, 0.6121],
+ [0.4450, 0.8892, 0.4045]]]]), tensor([[[ 1.0000, 0.0100, -0.0100],
+ [-0.1183, 0.9988, 0.1171],
+ [ 0.0000, 0.0000, 1.0000]]]))
+ >>> aug.inverse(out)
+ tensor([[[[0.4068, 0.7549, 0.1404],
+ [0.2051, 0.3111, 0.5562],
+ [0.3985, 0.8816, 0.4257]]]])
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.randn(1, 3, 32, 32)
+ >>> aug = RandomShear((-15., 20.), p=1.)
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
+ """
+
+ def __init__(
+ self,
+ shear: Union[Tensor, float, Tuple[float, float], Tuple[float, float, float, float]],
+ resample: Union[str, int, Resample] = Resample.BILINEAR.name,
+ same_on_batch: bool = False,
+ align_corners: bool = False,
+ padding_mode: Union[str, int, SamplePadding] = SamplePadding.ZEROS.name,
+ p: float = 0.5,
+ keepdim: bool = False,
+ ) -> None:
+ super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)
+ self._param_generator: rg.ShearGenerator = rg.ShearGenerator(shear)
+ self.flags = dict(
+ resample=Resample.get(resample), padding_mode=SamplePadding.get(padding_mode), align_corners=align_corners
+ )
+
+ def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
+ return get_shear_matrix2d(
+ as_tensor(params["center"], device=input.device, dtype=input.dtype),
+ deg2rad(as_tensor(params["shear_x"], device=input.device, dtype=input.dtype)),
+ deg2rad(as_tensor(params["shear_y"], device=input.device, dtype=input.dtype)),
+ )
+
+ def apply_transform(
+ self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
+ ) -> Tensor:
+ _, _, height, width = input.shape
+ if not isinstance(transform, Tensor):
+ raise TypeError(f'Expected the `transform` be a Tensor. Got {type(transform)}.')
+
+ return warp_affine(
+ input,
+ transform[:, :2, :],
+ (height, width),
+ flags["resample"].name.lower(),
+ align_corners=flags["align_corners"],
+ padding_mode=flags["padding_mode"].name.lower(),
+ )
+
+ def inverse_transform(
+ self,
+ input: Tensor,
+ flags: Dict[str, Any],
+ transform: Optional[Tensor] = None,
+ size: Optional[Tuple[int, int]] = None,
+ ) -> Tensor:
+ if not isinstance(transform, Tensor):
+ raise TypeError(f'Expected the `transform` be a Tensor. Got {type(transform)}.')
+ return self.apply_transform(
+ input,
+ params=self._params,
+ transform=as_tensor(transform, device=input.device, dtype=input.dtype),
+ flags=flags,
+ )
diff --git a/kornia/augmentation/_2d/geometric/thin_plate_spline.py b/kornia/augmentation/_2d/geometric/thin_plate_spline.py
index bb7073127..b4526b21f 100644
--- a/kornia/augmentation/_2d/geometric/thin_plate_spline.py
+++ b/kornia/augmentation/_2d/geometric/thin_plate_spline.py
@@ -1,12 +1,13 @@
from typing import Any, Dict, Optional
import torch
-from torch import Tensor
from kornia.augmentation._2d.base import AugmentationBase2D
+from kornia.core import Tensor, tensor
from kornia.geometry.transform import get_tps_transform, warp_image_tps
+# NOTE: This NEEDS to be updated. It is out of the random generator controller.
class RandomThinPlateSpline(AugmentationBase2D):
r"""Add random noise to the Thin Plate Spline algorithm.
@@ -50,7 +51,7 @@ class RandomThinPlateSpline(AugmentationBase2D):
def generate_parameters(self, shape: torch.Size) -> Dict[str, Tensor]:
B, _, _, _ = shape
- src = torch.tensor([[[-1.0, -1.0], [-1.0, 1.0], [1.0, -1.0], [1.0, 1.0], [0.0, 0.0]]]).expand(B, 5, 2) # Bx5x2
+ src = tensor([[[-1.0, -1.0], [-1.0, 1.0], [1.0, -1.0], [1.0, 1.0], [0.0, 0.0]]]).expand(B, 5, 2) # Bx5x2
dst = src + self.dist.rsample(src.shape)
return dict(src=src, dst=dst)
diff --git a/kornia/augmentation/_2d/geometric/translate.py b/kornia/augmentation/_2d/geometric/translate.py
new file mode 100644
index 000000000..9e730668d
--- /dev/null
+++ b/kornia/augmentation/_2d/geometric/translate.py
@@ -0,0 +1,109 @@
+from typing import Any, Dict, Optional, Tuple, Union
+
+from kornia.augmentation import random_generator as rg
+from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
+from kornia.constants import Resample, SamplePadding
+from kornia.core import Tensor, as_tensor, stack
+from kornia.geometry.transform import get_translation_matrix2d, warp_affine
+
+
+class RandomTranslate(GeometricAugmentationBase2D):
+ r"""Apply a random 2D affine transformation to a tensor image.
+
+ Args:
+ translate_x: tuple of maximum absolute fraction for horizontal translations.
+ For example translate_x=(a, b), then horizontal shift
+ is randomly sampled in the range img_width * a < dx < img_width * b
+ translate_y: tuple of maximum absolute fraction for vertical translations.
+ For example translate_y=(a, b), then vertical shift
+ is randomly sampled in the range img_height * a < dy < img_height * b.
+ resample: resample mode from "nearest" (0) or "bilinear" (1).
+ padding_mode: padding mode from "zeros" (0), "border" (1) or "refection" (2).
+ same_on_batch: apply the same transformation across the batch.
+ align_corners: interpolation flag.
+ 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).
+
+ Shape:
+ - Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`
+ - Output: :math:`(B, C, H, W)`
+
+ .. note::
+ This function internally uses :func:`kornia.geometry.transform.warp_affine`.
+
+ Examples:
+ >>> import torch
+ >>> rng = torch.manual_seed(0)
+ >>> input = torch.rand(1, 1, 3, 3)
+ >>> aug = RandomTranslate((-0.2, 0.2), (-0.1, 0.1), p=1.)
+ >>> out = aug(input)
+ >>> out, aug.transform_matrix
+ (tensor([[[[0.3403, 0.6439, 0.2920],
+ [0.1377, 0.3383, 0.5569],
+ [0.3226, 0.6909, 0.4844]]]]), tensor([[[ 1.0000, 0.0000, 0.1588],
+ [ 0.0000, 1.0000, -0.0907],
+ [ 0.0000, 0.0000, 1.0000]]]))
+ >>> aug.inverse(out)
+ tensor([[[[0.3565, 0.4839, 0.1922],
+ [0.2164, 0.4134, 0.3968],
+ [0.3797, 0.6075, 0.3765]]]])
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.randn(1, 3, 32, 32)
+ >>> aug = RandomTranslate((-0.2, 0.2), (-0.1, 0.1), p=1.)
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
+ """
+
+ def __init__(
+ self,
+ translate_x: Optional[Union[Tensor, Tuple[float, float]]] = None,
+ translate_y: Optional[Union[Tensor, Tuple[float, float]]] = None,
+ resample: Union[str, int, Resample] = Resample.BILINEAR.name,
+ same_on_batch: bool = False,
+ align_corners: bool = False,
+ padding_mode: Union[str, int, SamplePadding] = SamplePadding.ZEROS.name,
+ p: float = 0.5,
+ keepdim: bool = False,
+ ) -> None:
+ super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)
+ self._param_generator: rg.TranslateGenerator = rg.TranslateGenerator(translate_x, translate_y)
+ self.flags = dict(
+ resample=Resample.get(resample), padding_mode=SamplePadding.get(padding_mode), align_corners=align_corners
+ )
+
+ def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
+ translations = stack([params["translate_x"], params["translate_y"]], dim=-1)
+ return get_translation_matrix2d(as_tensor(translations, device=input.device, dtype=input.dtype))
+
+ def apply_transform(
+ self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
+ ) -> Tensor:
+ _, _, height, width = input.shape
+ if not isinstance(transform, Tensor):
+ raise TypeError(f'Expected the `transform` be a Tensor. Got {type(transform)}.')
+
+ return warp_affine(
+ input,
+ transform[:, :2, :],
+ (height, width),
+ flags["resample"].name.lower(),
+ align_corners=flags["align_corners"],
+ padding_mode=flags["padding_mode"].name.lower(),
+ )
+
+ def inverse_transform(
+ self,
+ input: Tensor,
+ flags: Dict[str, Any],
+ transform: Optional[Tensor] = None,
+ size: Optional[Tuple[int, int]] = None,
+ ) -> Tensor:
+ if not isinstance(transform, Tensor):
+ raise TypeError(f'Expected the `transform` be a Tensor. Got {type(transform)}.')
+ return self.apply_transform(
+ input,
+ params=self._params,
+ transform=as_tensor(transform, device=input.device, dtype=input.dtype),
+ flags=flags,
+ )
diff --git a/kornia/augmentation/_2d/geometric/vertical_flip.py b/kornia/augmentation/_2d/geometric/vertical_flip.py
index 539196878..ef59b5b3b 100644
--- a/kornia/augmentation/_2d/geometric/vertical_flip.py
+++ b/kornia/augmentation/_2d/geometric/vertical_flip.py
@@ -1,9 +1,7 @@
from typing import Any, Dict, Optional, Tuple
-import torch
-from torch import Tensor
-
from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
+from kornia.core import Tensor, as_tensor, tensor
from kornia.geometry.transform import vflip
@@ -26,6 +24,7 @@ class RandomVerticalFlip(GeometricAugmentationBase2D):
This function internally uses :func:`kornia.geometry.transform.vflip`.
Examples:
+ >>> import torch
>>> input = torch.tensor([[[[0., 0., 0.],
... [0., 0., 0.],
... [0., 1., 1.]]]])
@@ -48,7 +47,7 @@ class RandomVerticalFlip(GeometricAugmentationBase2D):
def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
h: int = int(params["forward_input_shape"][-2])
- flip_mat: Tensor = torch.tensor([[1, 0, 0], [0, -1, h - 1], [0, 0, 1]], device=input.device, dtype=input.dtype)
+ flip_mat: Tensor = tensor([[1, 0, 0], [0, -1, h - 1], [0, 0, 1]], device=input.device, dtype=input.dtype)
return flip_mat.expand(input.shape[0], 3, 3)
@@ -64,9 +63,11 @@ class RandomVerticalFlip(GeometricAugmentationBase2D):
transform: Optional[Tensor] = None,
size: Optional[Tuple[int, int]] = None,
) -> Tensor:
+ if not isinstance(transform, Tensor):
+ raise TypeError(f'Expected the `transform` be a Tensor. Got {type(transform)}.')
return self.apply_transform(
input,
params=self._params,
- transform=torch.as_tensor(transform, device=input.device, dtype=input.dtype),
+ transform=as_tensor(transform, device=input.device, dtype=input.dtype),
flags=flags,
)
diff --git a/kornia/augmentation/_2d/intensity/__init__.py b/kornia/augmentation/_2d/intensity/__init__.py
index 5b4923c54..56e35ed35 100644
--- a/kornia/augmentation/_2d/intensity/__init__.py
+++ b/kornia/augmentation/_2d/intensity/__init__.py
@@ -1,3 +1,4 @@
+from kornia.augmentation._2d.intensity.auto_contrast import RandomAutoContrast
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
diff --git a/kornia/augmentation/_2d/intensity/auto_contrast.py b/kornia/augmentation/_2d/intensity/auto_contrast.py
new file mode 100644
index 000000000..a9e542b70
--- /dev/null
+++ b/kornia/augmentation/_2d/intensity/auto_contrast.py
@@ -0,0 +1,40 @@
+from typing import Any, Dict, Optional
+
+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
+from kornia.core import Tensor
+from kornia.enhance import normalize_min_max
+
+
+class RandomAutoContrast(IntensityAugmentationBase2D):
+ r"""Apply a random auto-contrast of a tensor image.
+
+ Args:
+ p: probability of applying the transformation.
+ clip_output: if true clip output
+ 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)`
+ - Output: :math:`(B, C, H, W)`
+
+ .. note::
+ This function internally uses :func:`kornia.enhance.normalize_min_max`
+ """
+
+ def __init__(
+ self, clip_output: bool = True, same_on_batch: bool = False, p: float = 1.0, keepdim: bool = False
+ ) -> None:
+ super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)
+
+ self.clip_output = clip_output
+
+ def apply_transform(
+ self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
+ ) -> Tensor:
+ out = normalize_min_max(input)
+
+ if self.clip_output:
+ return out.clamp(0.0, 1.0)
+
+ return out
diff --git a/kornia/augmentation/_2d/intensity/contrast.py b/kornia/augmentation/_2d/intensity/contrast.py
index 863e525d5..532ed176d 100644
--- a/kornia/augmentation/_2d/intensity/contrast.py
+++ b/kornia/augmentation/_2d/intensity/contrast.py
@@ -16,9 +16,8 @@ class RandomContrast(IntensityAugmentationBase2D):
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.
+ contrast: the contrast factor to apply.
+ clip_output: if true clip output.
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).
diff --git a/kornia/augmentation/_2d/intensity/erasing.py b/kornia/augmentation/_2d/intensity/erasing.py
index 60de26a73..ed5c4333d 100644
--- a/kornia/augmentation/_2d/intensity/erasing.py
+++ b/kornia/augmentation/_2d/intensity/erasing.py
@@ -52,7 +52,6 @@ class RandomErasing(IntensityAugmentationBase2D):
tensor(True)
"""
- # Note: Extra params, inplace=False in Torchvision.
def __init__(
self,
scale: Union[Tensor, Tuple[float, float]] = (0.02, 0.33),
diff --git a/kornia/augmentation/_2d/intensity/gamma.py b/kornia/augmentation/_2d/intensity/gamma.py
index f830f95d8..76ce8d526 100644
--- a/kornia/augmentation/_2d/intensity/gamma.py
+++ b/kornia/augmentation/_2d/intensity/gamma.py
@@ -15,9 +15,8 @@ class RandomGamma(IntensityAugmentationBase2D):
Args:
p: probability of applying the transformation.
- gamma: the gamma factor to apply
- gain: the gain factor to apply
- silence_instantiation_warning: if True, silence the warning at instantiation.
+ gamma: the gamma factor to apply.
+ gain: the gain factor to apply.
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).
diff --git a/kornia/augmentation/_2d/intensity/hue.py b/kornia/augmentation/_2d/intensity/hue.py
index 726c79541..4f57618ce 100644
--- a/kornia/augmentation/_2d/intensity/hue.py
+++ b/kornia/augmentation/_2d/intensity/hue.py
@@ -17,8 +17,7 @@ class RandomHue(IntensityAugmentationBase2D):
Args:
p: probability of applying the transformation.
- hue: the saturation factor to apply
- silence_instantiation_warning: if True, silence the warning at instantiation.
+ hue: the saturation factor to apply.
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).
diff --git a/kornia/augmentation/_2d/intensity/posterize.py b/kornia/augmentation/_2d/intensity/posterize.py
index 9a1c04c12..3ffa40226 100644
--- a/kornia/augmentation/_2d/intensity/posterize.py
+++ b/kornia/augmentation/_2d/intensity/posterize.py
@@ -14,8 +14,8 @@ class RandomPosterize(IntensityAugmentationBase2D):
Args:
p: probability of applying the transformation.
bits: Integer that ranged from (0, 8], in which 0 gives black image and 8 gives the original.
- If int x, bits will be generated from (x, 8).
- If tuple (x, y), bits will be generated from (x, y).
+ If int x, bits will be generated from (x, 8) then convert to int.
+ If tuple (x, y), bits will be generated from (x, y) then convert to int.
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).
@@ -30,24 +30,24 @@ class RandomPosterize(IntensityAugmentationBase2D):
Examples:
>>> rng = torch.manual_seed(0)
>>> input = torch.rand(1, 1, 5, 5)
- >>> posterize = RandomPosterize(3, p=1.)
+ >>> posterize = RandomPosterize(3., p=1.)
>>> posterize(input)
- tensor([[[[0.4706, 0.7529, 0.0627, 0.1255, 0.2824],
- [0.6275, 0.4706, 0.8784, 0.4392, 0.6275],
- [0.3451, 0.3765, 0.0000, 0.1569, 0.2824],
- [0.5020, 0.6902, 0.7843, 0.1569, 0.2510],
- [0.6588, 0.9098, 0.3765, 0.8471, 0.4078]]]])
+ tensor([[[[0.4863, 0.7529, 0.0784, 0.1255, 0.2980],
+ [0.6275, 0.4863, 0.8941, 0.4549, 0.6275],
+ [0.3451, 0.3922, 0.0157, 0.1569, 0.2824],
+ [0.5176, 0.6902, 0.8000, 0.1569, 0.2667],
+ [0.6745, 0.9098, 0.3922, 0.8627, 0.4078]]]])
To apply the exact augmenation again, you may take the advantage of the previous parameter state:
>>> input = torch.randn(1, 3, 32, 32)
- >>> aug = RandomPosterize(3, p=1.)
+ >>> aug = RandomPosterize(3., p=1.)
>>> (aug(input) == aug(input, params=aug._params)).all()
tensor(True)
"""
def __init__(
self,
- bits: Union[int, Tuple[int, int], Tensor] = 3,
+ bits: Union[float, Tuple[float, float], Tensor] = 3,
same_on_batch: bool = False,
p: float = 0.5,
keepdim: bool = False,
diff --git a/kornia/augmentation/_2d/intensity/saturation.py b/kornia/augmentation/_2d/intensity/saturation.py
index 14d65e22b..c1b7e5f9c 100644
--- a/kornia/augmentation/_2d/intensity/saturation.py
+++ b/kornia/augmentation/_2d/intensity/saturation.py
@@ -16,8 +16,7 @@ class RandomSaturation(IntensityAugmentationBase2D):
Args:
p: probability of applying the transformation.
- saturation: the saturation factor to apply
- silence_instantiation_warning: if True, silence the warning at instantiation.
+ saturation: the saturation factor to apply.
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).
diff --git a/kornia/augmentation/_2d/mix/base.py b/kornia/augmentation/_2d/mix/base.py
index 4594cbc1c..467f87a21 100644
--- a/kornia/augmentation/_2d/mix/base.py
+++ b/kornia/augmentation/_2d/mix/base.py
@@ -52,7 +52,8 @@ class MixAugmentationBaseV2(_BasicAugmentationBase):
return input
def transform_input(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
- to_apply = params['batch_prob']
+ batch_prob = params['batch_prob']
+ to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions.
ori_shape = input.shape
in_tensor = self.transform_tensor(input)
output = in_tensor
@@ -66,7 +67,8 @@ class MixAugmentationBaseV2(_BasicAugmentationBase):
return output
def transform_mask(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
- to_apply = params['batch_prob']
+ batch_prob = params['batch_prob']
+ to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions.
output = input
if sum(to_apply) != len(to_apply):
output = self.apply_non_transform_mask(input, params, flags)
@@ -80,7 +82,8 @@ class MixAugmentationBaseV2(_BasicAugmentationBase):
if not (len(input.shape) == 4 and input.shape[2:] == torch.Size([4, 2])):
raise RuntimeError(f"Only BxNx4x2 tensor is supported. Got {input.shape}.")
input = Boxes(input, False, mode="vertices_plus")
- to_apply = params['batch_prob']
+ batch_prob = params['batch_prob']
+ to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions.
output = input
if sum(to_apply) != len(to_apply):
output = self.apply_non_transform_boxes(input, params, flags)
@@ -89,7 +92,8 @@ class MixAugmentationBaseV2(_BasicAugmentationBase):
return output
def transform_keypoint(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
- to_apply = params['batch_prob']
+ batch_prob = params['batch_prob']
+ to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions.
output = input
if sum(to_apply) != len(to_apply):
output = self.apply_non_transform_keypoint(input, params, flags)
@@ -98,7 +102,8 @@ class MixAugmentationBaseV2(_BasicAugmentationBase):
return output
def transform_class(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
- to_apply = params['batch_prob']
+ batch_prob = params['batch_prob']
+ to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions.
output = input
if sum(to_apply) != len(to_apply):
output = self.apply_non_transform_class(input, params, flags)
diff --git a/kornia/augmentation/_2d/mix/jigsaw.py b/kornia/augmentation/_2d/mix/jigsaw.py
index a6fd23fb3..4f9046822 100644
--- a/kornia/augmentation/_2d/mix/jigsaw.py
+++ b/kornia/augmentation/_2d/mix/jigsaw.py
@@ -55,7 +55,8 @@ class RandomJigsaw(MixAugmentationBaseV2):
self, input: Tensor, params: Dict[str, Tensor], maybe_flags: Optional[Dict[str, Any]] = None
) -> Tensor:
# different from the Base class routine. This function will not refer to any non-transformation images.
- to_apply = params['batch_prob']
+ batch_prob = params['batch_prob']
+ to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions.
input = input[to_apply].clone()
b, c, h, w = input.shape
diff --git a/kornia/augmentation/_2d/mix/mosaic.py b/kornia/augmentation/_2d/mix/mosaic.py
index 08ceb10af..c4c060741 100644
--- a/kornia/augmentation/_2d/mix/mosaic.py
+++ b/kornia/augmentation/_2d/mix/mosaic.py
@@ -92,14 +92,15 @@ class RandomMosaic(MixAugmentationBaseV2):
@torch.no_grad()
def apply_transform_boxes(self, input: Boxes, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Boxes:
+ to_apply = params["batch_prob"] > 0.5
src_box = as_tensor(params["src"], device=input.device, dtype=input.dtype)
dst_box = as_tensor(params["dst"], device=input.device, dtype=input.dtype)
# Boxes is BxNx4x2 only.
batch_shapes = as_tensor(params["batch_shapes"], device=input.device, dtype=input.dtype)
- offset = zeros((len(params["batch_prob"]), 2), device=input.device, dtype=input.dtype) # Bx2
+ offset = zeros((len(to_apply), 2), device=input.device, dtype=input.dtype) # Bx2
# NOTE: not a pretty good line I think.
offset_end = dst_box[0, 2].repeat(input.data.shape[0], 1)
- idx = torch.arange(0, input.data.shape[0], device=input.device, dtype=torch.long)[params["batch_prob"]]
+ idx = torch.arange(0, input.data.shape[0], device=input.device, dtype=torch.long)[to_apply]
maybe_out_boxes: Optional[Boxes] = None
for i in range(flags['mosaic_grid'][0]):
@@ -112,9 +113,9 @@ class RandomMosaic(MixAugmentationBaseV2):
_box._data[params["permutation"][:, 0]] = _box._data[params["permutation"][:, _idx]]
_box.translate(_offset, inplace=True)
# zero-out unrelated batch elements.
- _box._data[~params["batch_prob"]] = 0
+ _box._data[~to_apply] = 0
if maybe_out_boxes is None:
- _box._data[~params["batch_prob"]] = input._data[~params["batch_prob"]]
+ _box._data[~to_apply] = input._data[~to_apply]
maybe_out_boxes = _box
else:
KORNIA_UNWRAP(maybe_out_boxes, Boxes).merge(_box, inplace=True)
diff --git a/kornia/augmentation/_3d/base.py b/kornia/augmentation/_3d/base.py
index 1a7a2ee4e..169f6c65e 100644
--- a/kornia/augmentation/_3d/base.py
+++ b/kornia/augmentation/_3d/base.py
@@ -64,7 +64,8 @@ class RigidAffineAugmentationBase3D(AugmentationBase3D):
def generate_transformation_matrix(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
"""Generate transformation matrices with the given input and param settings."""
- to_apply = params['batch_prob']
+ batch_prob = params['batch_prob']
+ to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions.
in_tensor = self.transform_tensor(input)
if not to_apply.any():
trans_matrix = self.identity_matrix(in_tensor)
diff --git a/kornia/augmentation/__init__.py b/kornia/augmentation/__init__.py
index 36a48677e..ec07235d9 100644
--- a/kornia/augmentation/__init__.py
+++ b/kornia/augmentation/__init__.py
@@ -1,3 +1,6 @@
+# Lazy loading auto module
+import kornia.augmentation.auto as auto
+import kornia.augmentation.container as container
from kornia.augmentation._2d import (
CenterCrop,
ColorJiggle,
@@ -7,6 +10,7 @@ from kornia.augmentation._2d import (
Normalize,
PadTo,
RandomAffine,
+ RandomAutoContrast,
RandomBoxBlur,
RandomBrightness,
RandomChannelShuffle,
@@ -39,8 +43,10 @@ from kornia.augmentation._2d import (
RandomRotation,
RandomSaturation,
RandomSharpness,
+ RandomShear,
RandomSolarize,
RandomThinPlateSpline,
+ RandomTranslate,
RandomVerticalFlip,
Resize,
SmallestMaxSize,
@@ -74,6 +80,8 @@ from kornia.augmentation.container import (
)
__all__ = [
+ "auto",
+ "container",
"AugmentationBase2D",
"RigidAffineAugmentationBase2D",
"GeometricAugmentationBase2D",
@@ -87,6 +95,8 @@ __all__ = [
"LongestMaxSize",
"PadTo",
"RandomAffine",
+ "RandomShear",
+ "RandomTranslate",
"RandomBoxBlur",
"RandomBrightness",
"RandomChannelShuffle",
@@ -95,6 +105,7 @@ __all__ = [
"RandomErasing",
"RandomElasticTransform",
"RandomFisheye",
+ "RandomAutoContrast",
"RandomGamma",
"RandomGrayscale",
"RandomGaussianBlur",
diff --git a/kornia/augmentation/auto/__init__.py b/kornia/augmentation/auto/__init__.py
new file mode 100644
index 000000000..621c69da2
--- /dev/null
+++ b/kornia/augmentation/auto/__init__.py
@@ -0,0 +1,7 @@
+from .autoaugment import AutoAugment
+from .base import PolicyAugmentBase
+from .operations import PolicySequential
+from .rand_augment import RandAugment
+from .trivial_augment import TrivialAugment
+
+__all__ = ["AutoAugment", "PolicyAugmentBase", "PolicySequential", "RandAugment", "TrivialAugment"]
diff --git a/kornia/augmentation/auto/autoaugment/__init__.py b/kornia/augmentation/auto/autoaugment/__init__.py
new file mode 100644
index 000000000..4f2c1cab6
--- /dev/null
+++ b/kornia/augmentation/auto/autoaugment/__init__.py
@@ -0,0 +1 @@
+from .autoaugment import AutoAugment
diff --git a/kornia/augmentation/auto/autoaugment/autoaugment.py b/kornia/augmentation/auto/autoaugment/autoaugment.py
new file mode 100644
index 000000000..253d6bada
--- /dev/null
+++ b/kornia/augmentation/auto/autoaugment/autoaugment.py
@@ -0,0 +1,138 @@
+from typing import Iterator, List, Optional, Tuple, Union
+
+from torch.distributions import Categorical
+
+from kornia.augmentation.auto.base import SUBPLOLICY_CONFIG, PolicyAugmentBase
+from kornia.augmentation.auto.operations.policy import PolicySequential
+from kornia.augmentation.container.params import ParamItem
+from kornia.core import Module, tensor
+
+from . import ops
+
+imagenet_policy: List[SUBPLOLICY_CONFIG] = [
+ [("posterize", 0.4, 8), ("rotate", 0.6, 9)],
+ [("solarize", 0.6, 5), ("auto_contrast", 0.6, None)],
+ [("equalize", 0.8, None), ("equalize", 0.6, None)],
+ [("posterize", 0.6, 7), ("posterize", 0.6, 6)],
+ [("equalize", 0.4, None), ("solarize", 0.2, 4)],
+ [("equalize", 0.4, None), ("rotate", 0.8, 8)],
+ [("solarize", 0.6, 3), ("equalize", 0.6, None)],
+ [("posterize", 0.8, 5), ("equalize", 1.0, None)],
+ [("rotate", 0.2, 3), ("solarize", 0.6, 8)],
+ [("equalize", 0.6, None), ("posterize", 0.4, 6)],
+ [("rotate", 0.8, 8), ("color", 0.4, 0)],
+ [("rotate", 0.4, 9), ("equalize", 0.6, None)],
+ [("equalize", 0.0, None), ("equalize", 0.8, None)],
+ [("invert", 0.6, None), ("equalize", 1.0, None)],
+ [("color", 0.6, 4), ("contrast", 1.0, 8)],
+ [("rotate", 0.8, 8), ("color", 1.0, 2)],
+ [("color", 0.8, 8), ("solarize", 0.8, 7)],
+ [("sharpness", 0.4, 7), ("invert", 0.6, None)],
+ [("shear_x", 0.6, 5), ("equalize", 1.0, None)],
+ [("color", 0.4, 0), ("equalize", 0.6, None)],
+ [("equalize", 0.4, None), ("solarize", 0.2, 4)],
+ [("solarize", 0.6, 5), ("auto_contrast", 0.6, None)],
+ [("invert", 0.6, None), ("equalize", 1.0, None)],
+ [("color", 0.6, 4), ("contrast", 1.0, 8)],
+ [("equalize", 0.8, None), ("equalize", 0.6, None)],
+]
+
+
+cifar10_policy: List[SUBPLOLICY_CONFIG] = [
+ [("invert", 0.1, None), ("contrast", 0.2, 6)],
+ [("rotate", 0.7, 2), ("translate_x", 0.3, 9)],
+ [("sharpness", 0.8, 1), ("sharpness", 0.9, 3)],
+ [("shear_y", 0.5, 8), ("translate_y", 0.7, 9)],
+ [("auto_contrast", 0.5, None), ("equalize", 0.9, None)],
+ [("shear_y", 0.2, 7), ("posterize", 0.3, 7)],
+ [("color", 0.4, 3), ("brightness", 0.6, 7)],
+ [("sharpness", 0.3, 9), ("brightness", 0.7, 9)],
+ [("equalize", 0.6, None), ("equalize", 0.5, None)],
+ [("contrast", 0.6, 7), ("sharpness", 0.6, 5)],
+ [("color", 0.7, 7), ("translate_x", 0.5, 8)],
+ [("equalize", 0.3, None), ("auto_contrast", 0.4, None)],
+ [("translate_y", 0.4, 3), ("sharpness", 0.2, 6)],
+ [("brightness", 0.9, 6), ("color", 0.2, 8)],
+ [("solarize", 0.5, 2), ("invert", 0.0, None)],
+ [("equalize", 0.2, None), ("auto_contrast", 0.6, None)],
+ [("equalize", 0.2, None), ("equalize", 0.6, None)],
+ [("color", 0.9, 9), ("equalize", 0.6, None)],
+ [("auto_contrast", 0.8, None), ("solarize", 0.2, 8)],
+ [("brightness", 0.1, 3), ("color", 0.7, 0)],
+ [("solarize", 0.4, 5), ("auto_contrast", 0.9, None)],
+ [("translate_y", 0.9, 9), ("translate_y", 0.7, 9)],
+ [("auto_contrast", 0.9, None), ("solarize", 0.8, 3)],
+ [("equalize", 0.8, None), ("invert", 0.1, None)],
+ [("translate_y", 0.7, 9), ("auto_contrast", 0.9, None)],
+]
+
+
+svhn_policy: List[SUBPLOLICY_CONFIG] = [
+ [("shear_x", 0.9, 4), ("invert", 0.2, None)],
+ [("shear_y", 0.9, 8), ("invert", 0.7, None)],
+ [("equalize", 0.6, None), ("solarize", 0.6, 6)],
+ [("invert", 0.9, None), ("equalize", 0.6, None)],
+ [("equalize", 0.6, None), ("rotate", 0.9, 3)],
+ [("shear_x", 0.9, 4), ("auto_contrast", 0.8, None)],
+ [("shear_y", 0.9, 8), ("invert", 0.4, None)],
+ [("shear_y", 0.9, 5), ("solarize", 0.2, 6)],
+ [("invert", 0.9, None), ("auto_contrast", 0.8, None)],
+ [("equalize", 0.6, None), ("rotate", 0.9, 3)],
+ [("shear_x", 0.9, 4), ("solarize", 0.3, 3)],
+ [("shear_y", 0.8, 8), ("invert", 0.7, None)],
+ [("equalize", 0.9, None), ("translate_y", 0.6, 6)],
+ [("invert", 0.9, None), ("equalize", 0.6, None)],
+ [("contrast", 0.3, 3), ("rotate", 0.8, 4)],
+ [("invert", 0.8, None), ("translate_y", 0.0, 2)],
+ [("shear_y", 0.7, 6), ("solarize", 0.4, 8)],
+ [("invert", 0.6, None), ("rotate", 0.8, 4)],
+ [("shear_y", 0.3, 7), ("translate_x", 0.9, 3)],
+ [("shear_x", 0.1, 6), ("invert", 0.6, None)],
+ [("solarize", 0.7, 2), ("translate_y", 0.6, 7)],
+ [("shear_y", 0.8, 4), ("invert", 0.8, None)],
+ [("shear_x", 0.7, 9), ("translate_y", 0.8, 3)],
+ [("shear_y", 0.8, 5), ("auto_contrast", 0.7, None)],
+ [("shear_x", 0.7, 2), ("invert", 0.1, None)],
+]
+
+
+class AutoAugment(PolicyAugmentBase):
+ """Apply AutoAugment :cite:`cubuk2018autoaugment` searched strategies.
+
+ Args:
+ policy: a customized policy config or presets of "imagenet", "cifar10", and "svhn".
+
+ Examples:
+ >>> import torch
+ >>> import kornia.augmentation as K
+ >>> in_tensor = torch.rand(5, 3, 30, 30)
+ >>> aug = K.AugmentationSequential(AutoAugment())
+ >>> aug(in_tensor).shape
+ torch.Size([5, 3, 30, 30])
+ """
+
+ def __init__(self, policy: Union[str, List[SUBPLOLICY_CONFIG]] = "imagenet") -> None:
+ if policy == "imagenet":
+ _policy = imagenet_policy
+ elif policy == "cifar10":
+ _policy = cifar10_policy
+ elif policy == "svhn":
+ _policy = svhn_policy
+ elif isinstance(policy, (list, tuple)):
+ _policy = policy
+ else:
+ raise NotImplementedError(f"Invalid policy `{policy}`.")
+
+ super().__init__(_policy)
+ selection_weights = tensor([1.0 / len(self)] * len(self))
+ self.rand_selector = Categorical(selection_weights)
+
+ def compose_subpolicy_sequential(self, subpolicy: SUBPLOLICY_CONFIG) -> PolicySequential:
+ return PolicySequential(*[getattr(ops, name)(prob, mag) for name, prob, mag in subpolicy])
+
+ def get_forward_sequence(self, params: Optional[List[ParamItem]] = None) -> Iterator[Tuple[str, Module]]:
+ if params is None:
+ idx = self.rand_selector.sample((1,))
+ return self.get_children_by_indices(idx)
+
+ return self.get_children_by_params(params)
diff --git a/kornia/augmentation/auto/autoaugment/ops.py b/kornia/augmentation/auto/autoaugment/ops.py
new file mode 100644
index 000000000..12320c056
--- /dev/null
+++ b/kornia/augmentation/auto/autoaugment/ops.py
@@ -0,0 +1,117 @@
+"""AutoAugment operation wrapper."""
+from kornia.augmentation.auto.operations import (
+ AutoContrast,
+ Brightness,
+ Contrast,
+ Equalize,
+ Invert,
+ OperationBase,
+ Posterize,
+ Rotate,
+ Saturate,
+ Sharpness,
+ ShearX,
+ ShearY,
+ Solarize,
+ TranslateX,
+ TranslateY,
+)
+from kornia.core import linspace
+
+
+def shear_x(probability: float, magnitude: int) -> OperationBase:
+ magnitudes = linspace(-0.3, 0.3, 11) * 180.0
+ return ShearX(
+ None,
+ probability,
+ magnitude_range=(magnitudes[magnitude].item(), magnitudes[magnitude + 1].item()),
+ symmetric_megnitude=False,
+ )
+
+
+def shear_y(probability: float, magnitude: int) -> OperationBase:
+ magnitudes = linspace(-0.3, 0.3, 11) * 180.0
+ return ShearY(
+ None,
+ probability,
+ magnitude_range=(magnitudes[magnitude].item(), magnitudes[magnitude + 1].item()),
+ symmetric_megnitude=False,
+ )
+
+
+def translate_x(probability: float, magnitude: int) -> OperationBase:
+ magnitudes = linspace(-0.5, 0.5, 11)
+ return TranslateX(
+ None,
+ probability,
+ magnitude_range=(magnitudes[magnitude].item(), magnitudes[magnitude + 1].item()),
+ symmetric_megnitude=False,
+ )
+
+
+def translate_y(probability: float, magnitude: int) -> OperationBase:
+ magnitudes = linspace(-0.5, 0.5, 11)
+ return TranslateY(
+ None,
+ probability,
+ magnitude_range=(magnitudes[magnitude].item(), magnitudes[magnitude + 1].item()),
+ symmetric_megnitude=False,
+ )
+
+
+def rotate(probability: float, magnitude: int) -> OperationBase:
+ magnitudes = linspace(-30, 30, 11)
+ return Rotate(
+ None,
+ probability,
+ magnitude_range=(magnitudes[magnitude].item(), magnitudes[magnitude + 1].item()),
+ symmetric_megnitude=False,
+ )
+
+
+def auto_contrast(probability: float, _: int) -> OperationBase:
+ return AutoContrast(probability)
+
+
+def invert(probability: float, _: int) -> OperationBase:
+ return Invert(probability)
+
+
+def equalize(probability: float, _: int) -> OperationBase:
+ return Equalize(probability)
+
+
+def solarize(probability: float, magnitude: int) -> OperationBase:
+ magnitudes = linspace(0, 255, 11) / 255.0
+ return Solarize(None, probability, magnitude_range=(magnitudes[magnitude].item(), magnitudes[magnitude + 1].item()))
+
+
+def posterize(probability: float, magnitude: int) -> OperationBase:
+ magnitudes = linspace(4, 8, 11)
+ return Posterize(
+ None, probability, magnitude_range=(magnitudes[magnitude].item(), magnitudes[magnitude + 1].item())
+ )
+
+
+def contrast(probability: float, magnitude: int) -> OperationBase:
+ magnitudes = linspace(0.1, 1.9, 11)
+ return Contrast(None, probability, magnitude_range=(magnitudes[magnitude].item(), magnitudes[magnitude + 1].item()))
+
+
+def brightness(probability: float, magnitude: int) -> OperationBase:
+ magnitudes = linspace(0.1, 1.9, 11)
+ return Brightness(
+ None, probability, magnitude_range=(magnitudes[magnitude].item(), magnitudes[magnitude + 1].item())
+ )
+
+
+def sharpness(probability: float, magnitude: int) -> OperationBase:
+ magnitudes = linspace(0.1, 1.9, 11)
+ return Sharpness(
+ None, probability, magnitude_range=(magnitudes[magnitude].item(), magnitudes[magnitude + 1].item())
+ )
+
+
+def color(probability: float, magnitude: int) -> OperationBase:
+ magnitudes = linspace(0.1, 1.9, 11)
+ return Saturate(None, probability, magnitude_range=(magnitudes[magnitude].item(), magnitudes[magnitude + 1].item()))
diff --git a/kornia/augmentation/auto/base.py b/kornia/augmentation/auto/base.py
new file mode 100644
index 000000000..593e637de
--- /dev/null
+++ b/kornia/augmentation/auto/base.py
@@ -0,0 +1,82 @@
+from typing import Any, Dict, Iterator, List, Optional, Tuple, Union, cast
+
+import torch
+
+from kornia.augmentation.auto.operations.base import OperationBase
+from kornia.augmentation.auto.operations.policy import PolicySequential
+from kornia.augmentation.container.base import ImageSequentialBase
+from kornia.augmentation.container.params import ParamItem
+from kornia.core import Module, Tensor
+from kornia.utils import eye_like
+
+NUMBER = Union[float, int]
+OP_CONFIG = Tuple[str, NUMBER, Optional[NUMBER]]
+SUBPLOLICY_CONFIG = List[OP_CONFIG]
+
+
+class PolicyAugmentBase(ImageSequentialBase):
+ """Policy-based image augmentation."""
+
+ def __init__(self, policy: List[SUBPLOLICY_CONFIG]) -> None:
+ policies = self.compose_policy(policy)
+ super().__init__(*policies)
+
+ def compose_policy(self, policy: List[SUBPLOLICY_CONFIG]) -> List[PolicySequential]:
+ """Compose policy by the provided policy config."""
+ return [self.compose_subpolicy_sequential(subpolicy) for subpolicy in policy]
+
+ def compose_subpolicy_sequential(self, subpolicy: SUBPLOLICY_CONFIG) -> PolicySequential:
+ raise NotImplementedError
+
+ def identity_matrix(self, input: Tensor) -> Tensor:
+ """Return identity matrix."""
+ return eye_like(3, input)
+
+ def get_transformation_matrix(
+ self,
+ input: Tensor,
+ params: Optional[List[ParamItem]] = None,
+ recompute: bool = False,
+ extra_args: Dict[str, Any] = {},
+ ) -> Optional[Tensor]:
+ """Compute the transformation matrix according to the provided parameters.
+
+ Args:
+ input: the input tensor.
+ params: params for the sequence.
+ recompute: if to recompute the transformation matrix according to the params.
+ default: False.
+ """
+ if params is None:
+ raise NotImplementedError("requires params to be provided.")
+ named_modules: Iterator[Tuple[str, Module]] = self.get_forward_sequence(params)
+
+ # Define as 1 for broadcasting
+ res_mat: Optional[Tensor] = None
+ for (_, module), param in zip(named_modules, params if params is not None else []):
+ module = cast(PolicySequential, module)
+ mat = module.get_transformation_matrix(
+ input, params=cast(Optional[List[ParamItem]], param.data), recompute=recompute, extra_args=extra_args
+ )
+ res_mat = mat if res_mat is None else mat @ res_mat
+ return res_mat
+
+ def is_intensity_only(self, params: Optional[List[ParamItem]] = None) -> bool:
+ named_modules: Iterator[Tuple[str, Module]] = self.get_forward_sequence(params)
+ for _, module in named_modules:
+ module = cast(PolicySequential, module)
+ if not module.is_intensity_only():
+ return False
+ return True
+
+ def forward_parameters(self, batch_shape: torch.Size) -> List[ParamItem]:
+ named_modules: Iterator[Tuple[str, Module]] = self.get_forward_sequence()
+
+ params: List[ParamItem] = []
+ mod_param: Union[Dict[str, Tensor], List[ParamItem]]
+ for name, module in named_modules:
+ module = cast(OperationBase, module)
+ mod_param = module.forward_parameters(batch_shape)
+ param = ParamItem(name, mod_param)
+ params.append(param)
+ return params
diff --git a/kornia/augmentation/auto/operations/__init__.py b/kornia/augmentation/auto/operations/__init__.py
new file mode 100644
index 000000000..53044e6e7
--- /dev/null
+++ b/kornia/augmentation/auto/operations/__init__.py
@@ -0,0 +1,3 @@
+from .base import OperationBase
+from .ops import *
+from .policy import PolicySequential
diff --git a/kornia/augmentation/auto/operations/base.py b/kornia/augmentation/auto/operations/base.py
new file mode 100644
index 000000000..7c7242cc2
--- /dev/null
+++ b/kornia/augmentation/auto/operations/base.py
@@ -0,0 +1,173 @@
+from typing import Callable, Dict, List, Optional, Tuple, Type, TypeVar
+
+import torch
+from torch import nn
+from torch.autograd import Function
+from torch.distributions import Bernoulli, RelaxedBernoulli
+
+from kornia.augmentation.base import _AugmentationBase
+from kornia.core import Module, Tensor
+
+T = TypeVar('T', bound='OperationBase')
+
+
+class OperationBase(Module):
+ """Base class of differentiable augmentation operations.
+
+ Args:
+ operation: Kornia augmentation module.
+ initial_magnitude: targeted magnitude parameter name and its initial magnitude value.
+ The magnitude parameter name shall align with the attribute inside the random_generator
+ in each augmentation. If None, the augmentation will be randomly applied according to
+ the augmentation sampling range.
+ temperature: temperature for RelaxedBernoulli distribution used during training.
+ is_batch_operation: determine if to obtain the probability from `p` or `p_batch`.
+ Set to True for most non-shape-persistent operations (e.g. cropping).
+ """
+
+ def __init__(
+ self,
+ operation: _AugmentationBase,
+ initial_magnitude: Optional[List[Tuple[str, Optional[float]]]] = None,
+ temperature: float = 0.1,
+ is_batch_operation: bool = False,
+ magnitude_fn: Optional[Callable[[Tensor], Tensor]] = None,
+ gradient_estimator: Optional[Type[Function]] = None,
+ symmetric_megnitude: bool = False,
+ ) -> None:
+ super().__init__()
+ if not isinstance(operation, _AugmentationBase):
+ raise ValueError(f"Only Kornia augmentations supported. Got {operation}.")
+
+ self.op = operation
+
+ self._init_magnitude(initial_magnitude)
+
+ # Avoid skipping the sampling in `__batch_prob_generator__`
+ self.probability_range = (1e-7, 1 - 1e-7)
+ self._is_batch_operation = is_batch_operation
+ if is_batch_operation:
+ self._probability = nn.Parameter(torch.empty(1).fill_(self.op.p_batch))
+ else:
+ self._probability = nn.Parameter(torch.empty(1).fill_(self.op.p))
+
+ if temperature < 0:
+ raise ValueError(f"Expect temperature value greater than 0. Got {temperature}.")
+ self.register_buffer("temperature", torch.empty(1).fill_(temperature))
+
+ self.symmetric_megnitude = symmetric_megnitude
+ self._magnitude_fn = self._init_magnitude_fn(magnitude_fn)
+ self._gradient_estimator = gradient_estimator
+
+ def _init_magnitude_fn(self, magnitude_fn: Optional[Callable[[Tensor], Tensor]]) -> Callable[[Tensor], Tensor]:
+ def _identity(x: Tensor) -> Tensor:
+ return x
+
+ def _random_flip(fn: Callable[[Tensor], Tensor]) -> Callable[[Tensor], Tensor]:
+ def f(x: Tensor) -> Tensor:
+ flip = torch.rand((x.shape[0],), device=x.device) > 0.5
+ return fn(x) * flip
+
+ return f
+
+ if magnitude_fn is None:
+ magnitude_fn = _identity
+
+ if self.symmetric_megnitude:
+ return _random_flip(magnitude_fn)
+
+ return magnitude_fn
+
+ def _init_magnitude(self, initial_magnitude: Optional[List[Tuple[str, Optional[float]]]]) -> None:
+ if isinstance(initial_magnitude, (list, tuple)):
+ if not all([isinstance(ini_mag, (list, tuple)) and len(ini_mag) == 2 for ini_mag in initial_magnitude]):
+ raise ValueError(f"`initial_magnitude` shall be a list of 2-element tuples. Got {initial_magnitude}")
+ if len(initial_magnitude) != 1:
+ raise NotImplementedError("Multi magnitudes operations are not yet supported.")
+
+ if initial_magnitude is None:
+ self._factor_name = None
+ self._magnitude = None
+ self.magnitude_range = None
+ else:
+ self._factor_name = initial_magnitude[0][0]
+ if self.op._param_generator is not None:
+ self.magnitude_range = getattr(self.op._param_generator, self._factor_name)
+ else:
+ raise ValueError(f"No valid magnitude `{self._factor_name}` found in `{self.op._param_generator}`.")
+
+ self._magnitude = None
+ if initial_magnitude[0][1] is not None:
+ self._magnitude = nn.Parameter(torch.empty(1).fill_(initial_magnitude[0][1]))
+
+ def _update_probability_gen(self, relaxation: bool) -> None:
+ if relaxation:
+ if self._is_batch_operation:
+ self.op._p_batch_gen = RelaxedBernoulli(self.temperature, self.probability)
+ else:
+ self.op._p_gen = RelaxedBernoulli(self.temperature, self.probability)
+ else:
+ if self._is_batch_operation:
+ self.op._p_batch_gen = Bernoulli(self.probability)
+ else:
+ self.op._p_gen = Bernoulli(self.probability)
+
+ def train(self: T, mode: bool = True) -> T:
+ self._update_probability_gen(relaxation=mode)
+
+ return super().train(mode=mode)
+
+ def eval(self: T) -> T:
+ return self.train(False)
+
+ def forward_parameters(self, batch_shape: torch.Size, mag: Optional[Tensor] = None) -> Dict[str, Tensor]:
+ if mag is None:
+ mag = self.magnitude
+ # Need to setup the sampler again for each update.
+ # Otherwise, an error for updating the same graph twice will be thrown.
+ self._update_probability_gen(relaxation=True)
+ params = self.op.forward_parameters(batch_shape)
+
+ if mag is not None:
+ if self._factor_name is None:
+ raise RuntimeError("No factor found in the params while `mag` is provided.")
+ # For single factor operations, this is equivalent to `same_on_batch=True`
+ params[self._factor_name] = params[self._factor_name].zero_() + mag
+
+ if self._factor_name is not None:
+ params[self._factor_name] = self._magnitude_fn(params[self._factor_name])
+
+ return params
+
+ def forward(self, input: Tensor, params: Optional[Dict[str, Tensor]] = None) -> Tensor:
+ if params is None:
+ params = self.forward_parameters(input.shape)
+
+ batch_prob = params["batch_prob"][(...,) + ((None,) * (len(input.shape) - 1))]
+
+ if self._gradient_estimator is not None:
+ # skip the gradient computation if gradient estimator is provided.
+ with torch.no_grad():
+ output = self.op(input, params=params)
+ output = batch_prob * output + (1 - batch_prob) * input
+ if self.magnitude is None:
+ # If magnitude is None, make the grad w.r.t the input
+ return self._gradient_estimator.apply(input, output)
+ # If magnitude is not None, make the grad w.r.t the magnitude
+ return self._gradient_estimator.apply(self.magnitude, output)
+
+ return batch_prob * self.op(input, params=params) + (1 - batch_prob) * input
+
+ @property
+ def magnitude(self) -> Optional[Tensor]:
+ if self._magnitude is None:
+ return None
+ mag = self._magnitude
+ if self.magnitude_range is not None:
+ return mag.clamp(*self.magnitude_range)
+ return mag
+
+ @property
+ def probability(self) -> Tensor:
+ p = self._probability.clamp(*self.probability_range)
+ return p
diff --git a/kornia/augmentation/auto/operations/ops.py b/kornia/augmentation/auto/operations/ops.py
new file mode 100644
index 000000000..2b87a7317
--- /dev/null
+++ b/kornia/augmentation/auto/operations/ops.py
@@ -0,0 +1,564 @@
+from typing import Optional, Tuple
+
+import kornia.augmentation as K
+from kornia.augmentation.auto.operations.base import OperationBase
+from kornia.core import Tensor
+from kornia.grad_estimator import STEFunction
+
+__all__ = [
+ "AutoContrast",
+ "Brightness",
+ "Contrast",
+ "Hue",
+ "Saturate",
+ "Equalize",
+ "Gray",
+ "Invert",
+ "Posterize",
+ "Solarize",
+ "SolarizeAdd",
+ "Sharpness",
+ "HorizontalFlip",
+ "VerticalFlip",
+ "Rotate",
+ "ShearX",
+ "ShearY",
+ "TranslateX",
+ "TranslateY",
+]
+
+
+class AutoContrast(OperationBase):
+ """Apply auto_contrast operation.
+
+ Args:
+ initial_probability: the initial probability. If None, the augmentation will be randomly
+ applied according to he augmentation sampling range.
+ temperature: temperature for RelaxedBernoulli distribution used during training.
+ symmetric_megnitude: if to randomly assign the magnitude as negative or not.
+ """
+
+ def __init__(self, initial_probability: float = 0.5, temperature: float = 0.1, symmetric_megnitude: bool = False):
+ super().__init__(
+ K.RandomAutoContrast(same_on_batch=False, p=initial_probability),
+ initial_magnitude=None,
+ temperature=temperature,
+ symmetric_megnitude=symmetric_megnitude,
+ )
+
+
+class Brightness(OperationBase):
+ """Apply brightness operation.
+
+ Args:
+ initial_probability: the initial probability. If None, the augmentation will be randomly
+ applied according to he augmentation sampling range.
+ initial_magnitude: the initial magnitude.
+ magnitude_range: the sampling range for random sampling and clamping the optimized magnitude.
+ temperature: temperature for RelaxedBernoulli distribution used during training.
+ symmetric_megnitude: if to randomly assign the magnitude as negative or not.
+ """
+
+ def __init__(
+ self,
+ initial_magnitude: Optional[float] = 0.5,
+ initial_probability: float = 0.5,
+ magnitude_range: Tuple[float, float] = (0.2, 1.8),
+ temperature: float = 0.1,
+ symmetric_megnitude: bool = False,
+ ):
+ super().__init__(
+ K.RandomBrightness(magnitude_range, same_on_batch=False, p=initial_probability),
+ initial_magnitude=[("brightness_factor", initial_magnitude)],
+ temperature=temperature,
+ symmetric_megnitude=symmetric_megnitude,
+ )
+
+
+class Contrast(OperationBase):
+ """Apply contrast operation.
+
+ Args:
+ initial_probability: the initial probability. If None, the augmentation will be randomly
+ applied according to he augmentation sampling range.
+ initial_magnitude: the initial magnitude.
+ magnitude_range: the sampling range for random sampling and clamping the optimized magnitude.
+ temperature: temperature for RelaxedBernoulli distribution used during training.
+ symmetric_megnitude: if to randomly assign the magnitude as negative or not.
+ """
+
+ def __init__(
+ self,
+ initial_magnitude: Optional[float] = 0.5,
+ initial_probability: float = 0.5,
+ magnitude_range: Tuple[float, float] = (0.2, 1.8),
+ temperature: float = 0.1,
+ symmetric_megnitude: bool = False,
+ ):
+ super().__init__(
+ K.RandomContrast(magnitude_range, same_on_batch=False, p=initial_probability),
+ initial_magnitude=[("contrast_factor", initial_magnitude)],
+ temperature=temperature,
+ symmetric_megnitude=symmetric_megnitude,
+ )
+
+
+class Hue(OperationBase):
+ """Apply hue operation.
+
+ Args:
+ initial_probability: the initial probability. If None, the augmentation will be randomly
+ applied according to he augmentation sampling range.
+ initial_magnitude: the initial magnitude.
+ magnitude_range: the sampling range for random sampling and clamping the optimized magnitude.
+ temperature: temperature for RelaxedBernoulli distribution used during training.
+ symmetric_megnitude: if to randomly assign the magnitude as negative or not.
+ """
+
+ def __init__(
+ self,
+ initial_magnitude: Optional[float] = 0.0,
+ initial_probability: float = 0.5,
+ magnitude_range: Tuple[float, float] = (-0.5, 0.5),
+ temperature: float = 0.1,
+ symmetric_megnitude: bool = False,
+ ):
+ super().__init__(
+ K.RandomHue(magnitude_range, same_on_batch=False, p=initial_probability),
+ initial_magnitude=[("hue_factor", initial_magnitude)],
+ temperature=temperature,
+ symmetric_megnitude=symmetric_megnitude,
+ )
+
+
+class Saturate(OperationBase):
+ """Apply saturation operation.
+
+ Args:
+ initial_probability: the initial probability. If None, the augmentation will be randomly
+ applied according to he augmentation sampling range.
+ initial_magnitude: the initial magnitude.
+ magnitude_range: the sampling range for random sampling and clamping the optimized magnitude.
+ temperature: temperature for RelaxedBernoulli distribution used during training.
+ symmetric_megnitude: if to randomly assign the magnitude as negative or not.
+ """
+
+ def __init__(
+ self,
+ initial_magnitude: Optional[float] = 0.5,
+ initial_probability: float = 0.5,
+ magnitude_range: Tuple[float, float] = (0.2, 1.8),
+ temperature: float = 0.1,
+ symmetric_megnitude: bool = False,
+ ):
+ super().__init__(
+ K.RandomSaturation(magnitude_range, same_on_batch=False, p=initial_probability),
+ initial_magnitude=[("saturation_factor", initial_magnitude)],
+ temperature=temperature,
+ symmetric_megnitude=symmetric_megnitude,
+ )
+
+
+# TODO: Equalize cannot update probabilities yet.
+class Equalize(OperationBase):
+ """Apply equalize operation.
+
+ Args:
+ initial_probability: the initial probability. If None, the augmentation will be randomly
+ applied according to he augmentation sampling range.
+ temperature: temperature for RelaxedBernoulli distribution used during training.
+
+ Note:
+ Equalize cannot update probabilities yet.
+
+ Note:
+ STE gradient estimator applied for back propagation.
+ """
+
+ def __init__(self, initial_probability: float = 0.5, temperature: float = 0.1):
+ super().__init__(
+ K.RandomEqualize(same_on_batch=False, p=initial_probability),
+ initial_magnitude=None,
+ temperature=temperature,
+ symmetric_megnitude=False,
+ gradient_estimator=STEFunction,
+ )
+
+
+class Gray(OperationBase):
+ """Apply grayscale operation.
+
+ Args:
+ initial_probability: the initial probability. If None, the augmentation will be randomly
+ applied according to he augmentation sampling range.
+ temperature: temperature for RelaxedBernoulli distribution used during training.
+ """
+
+ def __init__(self, initial_probability: float = 0.5, temperature: float = 0.1):
+ super().__init__(
+ K.RandomGrayscale(same_on_batch=False, p=initial_probability),
+ initial_magnitude=None,
+ temperature=temperature,
+ symmetric_megnitude=False,
+ )
+
+
+class Invert(OperationBase):
+ """Apply invert operation.
+
+ Args:
+ initial_probability: the initial probability. If None, the augmentation will be randomly
+ applied according to he augmentation sampling range.
+ temperature: temperature for RelaxedBernoulli distribution used during training.
+ """
+
+ def __init__(self, initial_probability: float = 0.5, temperature: float = 0.1):
+ super().__init__(
+ K.RandomInvert(same_on_batch=False, p=initial_probability),
+ initial_magnitude=None,
+ temperature=temperature,
+ symmetric_megnitude=False,
+ )
+
+
+class Posterize(OperationBase):
+ """Apply posterize operation.
+
+ Args:
+ initial_magnitude: the initial magnitude.
+ initial_probability: the initial probability. If None, the augmentation will be randomly
+ applied according to he augmentation sampling range.
+ magnitude_range: the sampling range for random sampling and clamping the optimized magnitude.
+ temperature: temperature for RelaxedBernoulli distribution used during training.
+ symmetric_megnitude: if to randomly assign the magnitude as negative or not.
+
+ Note:
+ STE gradient estimator applied for back propagation.
+ """
+
+ @staticmethod
+ def _process_magnitude(magnitude: Tensor) -> Tensor:
+ return magnitude.long()
+
+ def __init__(
+ self,
+ initial_magnitude: Optional[float] = 4.0,
+ initial_probability: float = 0.5,
+ magnitude_range: Tuple[float, float] = (1.0, 8.0),
+ temperature: float = 0.1,
+ symmetric_megnitude: bool = False,
+ ):
+ super().__init__(
+ K.RandomPosterize(magnitude_range, same_on_batch=False, p=initial_probability),
+ initial_magnitude=[("bits_factor", initial_magnitude)],
+ temperature=temperature,
+ symmetric_megnitude=symmetric_megnitude,
+ magnitude_fn=Posterize._process_magnitude,
+ gradient_estimator=STEFunction,
+ )
+
+
+class Solarize(OperationBase):
+ """Apply solarize operation.
+
+ Args:
+ initial_magnitude: the initial magnitude.
+ initial_probability: the initial probability. If None, the augmentation will be randomly
+ applied according to he augmentation sampling range.
+ magnitude_range: the sampling range for random sampling and clamping the optimized
+ symmetric_megnitude: if to randomly assign the magnitude as negative or not.magnitude.
+ temperature: temperature for RelaxedBernoulli distribution used during training.
+
+ Note:
+ STE gradient estimator applied for back propagation.
+ """
+
+ def __init__(
+ self,
+ initial_magnitude: Optional[float] = 0.5,
+ initial_probability: float = 0.5,
+ magnitude_range: Tuple[float, float] = (0.0, 1.0),
+ temperature: float = 0.1,
+ symmetric_megnitude: bool = False,
+ ):
+ super().__init__(
+ K.RandomSolarize(magnitude_range, additions=0.0, same_on_batch=False, p=initial_probability),
+ initial_magnitude=[("thresholds", initial_magnitude)],
+ temperature=temperature,
+ symmetric_megnitude=symmetric_megnitude,
+ gradient_estimator=STEFunction,
+ )
+
+
+class SolarizeAdd(OperationBase):
+ """Apply solarize-addition operation with a fixed thresholds of 0.5.
+
+ Args:
+ initial_magnitude: the initial magnitude.
+ initial_probability: the initial probability. If None, the augmentation will be randomly
+ applied according to he augmentation sampling range.
+ magnitude_range: the sampling range for random sampling and clamping the optimized magnitude.
+ temperature: temperature for RelaxedBernoulli distribution used during training.
+ symmetric_megnitude: if to randomly assign the magnitude as negative or not.
+
+ Note:
+ STE gradient estimator applied for back propagation.
+ """
+
+ def __init__(
+ self,
+ initial_magnitude: Optional[float] = 0.0,
+ initial_probability: float = 0.5,
+ magnitude_range: Tuple[float, float] = (-0.3, 0.3),
+ temperature: float = 0.1,
+ symmetric_megnitude: bool = False,
+ ):
+ super().__init__(
+ K.RandomSolarize(thresholds=0.5, additions=magnitude_range, same_on_batch=False, p=initial_probability),
+ initial_magnitude=[("additions", initial_magnitude)],
+ temperature=temperature,
+ symmetric_megnitude=symmetric_megnitude,
+ gradient_estimator=STEFunction,
+ )
+
+
+class Sharpness(OperationBase):
+ """Apply sharpness operation.
+
+ Args:
+ initial_magnitude: the initial magnitude.
+ initial_probability: the initial probability. If None, the augmentation will be randomly
+ applied according to he augmentation sampling range.
+ magnitude_range: the sampling range for random sampling and clamping the optimized magnitude.
+ temperature: temperature for RelaxedBernoulli distribution used during training.
+ symmetric_megnitude: if to randomly assign the magnitude as negative or not.
+ """
+
+ def __init__(
+ self,
+ initial_magnitude: Optional[float] = 0.5,
+ initial_probability: float = 0.5,
+ magnitude_range: Tuple[float, float] = (0.1, 1.9),
+ temperature: float = 0.1,
+ symmetric_megnitude: bool = False,
+ ):
+ super().__init__(
+ K.RandomSharpness(magnitude_range, same_on_batch=False, p=initial_probability),
+ initial_magnitude=[("sharpness", initial_magnitude)],
+ temperature=temperature,
+ symmetric_megnitude=symmetric_megnitude,
+ )
+
+
+class HorizontalFlip(OperationBase):
+ """Apply horizontal flip operation.
+
+ Args:
+ initial_probability: the initial probability. If None, the augmentation will be randomly
+ applied according to he augmentation sampling range.
+ temperature: temperature for RelaxedBernoulli distribution used during training.
+ """
+
+ def __init__(self, initial_probability: float = 0.5, temperature: float = 0.1):
+ super().__init__(
+ K.RandomHorizontalFlip(same_on_batch=False, p=initial_probability),
+ initial_magnitude=None,
+ temperature=temperature,
+ symmetric_megnitude=False,
+ )
+
+
+class VerticalFlip(OperationBase):
+ """Apply vertical flip operation.
+
+ Args:
+ initial_magnitude: the initial magnitude.
+ temperature: temperature for RelaxedBernoulli distribution used during training.
+ """
+
+ def __init__(self, initial_probability: float = 0.5, temperature: float = 0.1):
+ super().__init__(
+ K.RandomVerticalFlip(same_on_batch=False, p=initial_probability),
+ initial_magnitude=None,
+ temperature=temperature,
+ symmetric_megnitude=False,
+ )
+
+
+class Rotate(OperationBase):
+ """Apply rotate operation.
+
+ Args:
+ initial_magnitude: the initial magnitude.
+ initial_probability: the initial probability. If None, the augmentation will be randomly
+ applied according to he augmentation sampling range.
+ magnitude_range: the sampling range for random sampling and clamping the optimized magnitude.
+ temperature: temperature for RelaxedBernoulli distribution used during training.
+ symmetric_megnitude: if to randomly assign the magnitude as negative or not.
+ """
+
+ def __init__(
+ self,
+ initial_magnitude: Optional[float] = 15.0,
+ initial_probability: float = 0.5,
+ magnitude_range: Tuple[float, float] = (0.0, 30.0),
+ temperature: float = 0.1,
+ symmetric_megnitude: bool = True,
+ ):
+ if symmetric_megnitude and magnitude_range[0] < 0:
+ raise ValueError(
+ f"Lower bound of {self.__class__.__name__} is a symmetric operation. "
+ f"The lower bound must above 0. Got {magnitude_range[0]}."
+ )
+ super().__init__(
+ K.RandomRotation(magnitude_range, same_on_batch=False, p=initial_probability),
+ initial_magnitude=[("degrees", initial_magnitude)],
+ temperature=temperature,
+ symmetric_megnitude=symmetric_megnitude,
+ )
+
+
+class ShearX(OperationBase):
+ """Apply shear operation along x-axis.
+
+ Args:
+ initial_magnitude: the initial magnitude.
+ initial_probability: the initial probability. If None, the augmentation will be randomly
+ applied according to he augmentation sampling range.
+ magnitude_range: the sampling range for random sampling and clamping the optimized magnitude.
+ temperature: temperature for RelaxedBernoulli distribution used during training.
+ symmetric_megnitude: if to randomly assign the magnitude as negative or not.
+ """
+
+ @staticmethod
+ def _process_magnitude(magnitude: Tensor) -> Tensor:
+ # make it sign-agnostic
+ return magnitude * 180
+
+ def __init__(
+ self,
+ initial_magnitude: Optional[float] = 0.1,
+ initial_probability: float = 0.5,
+ magnitude_range: Tuple[float, float] = (0.0, 0.3),
+ temperature: float = 0.1,
+ symmetric_megnitude: bool = True,
+ ):
+ if symmetric_megnitude and magnitude_range[0] < 0:
+ raise ValueError(
+ f"Lower bound of {self.__class__.__name__} is a symmetric operation. "
+ f"The lower bound must above 0. Got {magnitude_range[0]}."
+ )
+ super().__init__(
+ K.RandomShear(magnitude_range, same_on_batch=False, p=initial_probability),
+ initial_magnitude=[("shear_x", initial_magnitude)],
+ temperature=temperature,
+ symmetric_megnitude=symmetric_megnitude,
+ magnitude_fn=ShearX._process_magnitude,
+ )
+
+
+class ShearY(OperationBase):
+ """Apply shear operation along y-axis.
+
+ Args:
+ initial_magnitude: the initial magnitude.
+ initial_probability: the initial probability. If None, the augmentation will be randomly
+ applied according to he augmentation sampling range.
+ magnitude_range: the sampling range for random sampling and clamping the optimized magnitude.
+ temperature: temperature for RelaxedBernoulli distribution used during training.
+ symmetric_megnitude: if to randomly assign the magnitude as negative or not.
+ """
+
+ @staticmethod
+ def _process_magnitude(magnitude: Tensor) -> Tensor:
+ # make it sign-agnostic
+ return magnitude * 180
+
+ def __init__(
+ self,
+ initial_magnitude: Optional[float] = 0.1,
+ initial_probability: float = 0.5,
+ magnitude_range: Tuple[float, float] = (0.0, 0.3),
+ temperature: float = 0.1,
+ symmetric_megnitude: bool = True,
+ ):
+ if symmetric_megnitude and magnitude_range[0] < 0:
+ raise ValueError(
+ f"Lower bound of {self.__class__.__name__} is a symmetric operation. "
+ f"The lower bound must above 0. Got {magnitude_range[0]}."
+ )
+ super().__init__(
+ K.RandomShear(
+ (0.0, 0.0, magnitude_range[0], magnitude_range[1]), same_on_batch=False, p=initial_probability
+ ),
+ initial_magnitude=[("shear_y", initial_magnitude)],
+ temperature=temperature,
+ symmetric_megnitude=symmetric_megnitude,
+ magnitude_fn=ShearY._process_magnitude,
+ )
+
+
+class TranslateX(OperationBase):
+ """Apply translate operation along x-axis.
+
+ Args:
+ initial_magnitude: the initial magnitude.
+ initial_probability: the initial probability. If None, the augmentation will be randomly
+ applied according to he augmentation sampling range.
+ magnitude_range: the sampling range for random sampling and clamping the optimized magnitude.
+ temperature: temperature for RelaxedBernoulli distribution used during training.
+ symmetric_megnitude: if to randomly assign the magnitude as negative or not.
+ """
+
+ def __init__(
+ self,
+ initial_magnitude: Optional[float] = 0.2,
+ initial_probability: float = 0.5,
+ magnitude_range: Tuple[float, float] = (0.0, 0.5),
+ temperature: float = 0.1,
+ symmetric_megnitude: bool = True,
+ ):
+ if symmetric_megnitude and magnitude_range[0] < 0:
+ raise ValueError(
+ f"Lower bound of {self.__class__.__name__} is a symmetric operation. "
+ f"The lower bound must above 0. Got {magnitude_range[0]}."
+ )
+ super().__init__(
+ K.RandomTranslate(magnitude_range, same_on_batch=False, p=initial_probability),
+ initial_magnitude=[("translate_x", initial_magnitude)],
+ temperature=temperature,
+ symmetric_megnitude=symmetric_megnitude,
+ )
+
+
+class TranslateY(OperationBase):
+ """Apply translate operation along y-axis.
+
+ Args:
+ initial_magnitude: the initial magnitude.
+ initial_probability: the initial probability. If None, the augmentation will be randomly
+ applied according to he augmentation sampling range.
+ magnitude_range: the sampling range for random sampling and clamping the optimized magnitude.
+ temperature: temperature for RelaxedBernoulli distribution used during training.
+ symmetric_megnitude: if to randomly assign the magnitude as negative or not.
+ """
+
+ def __init__(
+ self,
+ initial_magnitude: Optional[float] = 0.2,
+ initial_probability: float = 0.5,
+ magnitude_range: Tuple[float, float] = (0.0, 0.5),
+ temperature: float = 0.1,
+ symmetric_megnitude: bool = True,
+ ):
+ if symmetric_megnitude and magnitude_range[0] < 0:
+ raise ValueError(
+ f"Lower bound of {self.__class__.__name__} is a symmetric operation. "
+ f"The lower bound must above 0. Got {magnitude_range[0]}."
+ )
+ super().__init__(
+ K.RandomTranslate(None, magnitude_range, same_on_batch=False, p=initial_probability),
+ initial_magnitude=[("translate_y", initial_magnitude)],
+ temperature=temperature,
+ symmetric_megnitude=symmetric_megnitude,
+ )
diff --git a/kornia/augmentation/auto/operations/policy.py b/kornia/augmentation/auto/operations/policy.py
new file mode 100644
index 000000000..01a1eda66
--- /dev/null
+++ b/kornia/augmentation/auto/operations/policy.py
@@ -0,0 +1,99 @@
+from typing import Any, Dict, Iterator, List, Optional, Tuple, Union, cast
+
+from torch import Size
+
+import kornia.augmentation as K
+from kornia.augmentation.auto.operations import OperationBase
+from kornia.augmentation.container.base import ImageSequentialBase
+from kornia.augmentation.container.params import ParamItem
+from kornia.augmentation.utils import _transform_input, override_parameters
+from kornia.core import Module, Tensor, as_tensor
+from kornia.utils import eye_like
+
+
+class PolicySequential(ImageSequentialBase):
+ """Policy tuple for applying multiple operations.
+
+ Args:
+ operations: a list of operations to perform.
+ """
+
+ def __init__(self, *operations: OperationBase) -> None:
+ self.validate_operations(*operations)
+ super().__init__(*operations)
+
+ def validate_operations(self, *operations: OperationBase) -> None:
+ invalid_ops: List[OperationBase] = []
+ for op in operations:
+ if not isinstance(op, OperationBase):
+ invalid_ops.append(op)
+ if len(invalid_ops) != 0:
+ raise ValueError(f"All operations must be Kornia Operations. Got {invalid_ops}.")
+
+ def identity_matrix(self, input: Tensor) -> Tensor:
+ """Return identity matrix."""
+ return eye_like(3, input)
+
+ def get_transformation_matrix(
+ self,
+ input: Tensor,
+ params: Optional[List[ParamItem]] = None,
+ recompute: bool = False,
+ extra_args: Dict[str, Any] = {},
+ ) -> Tensor:
+ """Compute the transformation matrix according to the provided parameters.
+
+ Args:
+ input: the input tensor.
+ params: params for the sequence.
+ recompute: if to recompute the transformation matrix according to the params.
+ default: False.
+ """
+ if params is None:
+ raise NotImplementedError("requires params to be provided.")
+ named_modules: Iterator[Tuple[str, Module]] = self.get_forward_sequence(params)
+
+ # Define as 1 for broadcasting
+ res_mat: Tensor = self.identity_matrix(_transform_input(input))
+ for (_, module), param in zip(named_modules, params if params is not None else []):
+ module = cast(OperationBase, module)
+ if isinstance(module.op, (K.GeometricAugmentationBase2D,)) and isinstance(param.data, dict):
+ ori_shape = input.shape
+ input = module.op.transform_tensor(input)
+ # Standardize shape
+ if recompute:
+ flags = override_parameters(module.op.flags, extra_args, in_place=False)
+ mat = module.op.generate_transformation_matrix(input, param.data, flags)
+ elif module.op._transform_matrix is not None:
+ mat = as_tensor(module.op._transform_matrix, device=input.device, dtype=input.dtype)
+ else:
+ raise RuntimeError(f"{module}.op._transform_matrix is None while `recompute=False`.")
+ res_mat = mat @ res_mat
+ input = module.op.transform_output_tensor(input, ori_shape)
+ if module.op.keepdim and ori_shape != input.shape:
+ res_mat = res_mat.squeeze()
+ return res_mat
+
+ def is_intensity_only(self) -> bool:
+ for module in self.children():
+ module = cast(OperationBase, module)
+ if isinstance(module.op, (K.GeometricAugmentationBase2D,)):
+ return False
+ return True
+
+ def get_forward_sequence(self, params: Optional[List[ParamItem]] = None) -> Iterator[Tuple[str, Module]]:
+ if params is not None:
+ return super().get_children_by_params(params)
+ return self.named_children()
+
+ def forward_parameters(self, batch_shape: Size) -> List[ParamItem]:
+ named_modules: Iterator[Tuple[str, Module]] = self.get_forward_sequence()
+
+ params: List[ParamItem] = []
+ mod_param: Union[Dict[str, Tensor], List[ParamItem]]
+ for name, module in named_modules:
+ module = cast(OperationBase, module)
+ mod_param = module.op.forward_parameters(batch_shape)
+ param = ParamItem(name, mod_param)
+ params.append(param)
+ return params
diff --git a/kornia/augmentation/auto/rand_augment/__init__.py b/kornia/augmentation/auto/rand_augment/__init__.py
new file mode 100644
index 000000000..7ef1cbaca
--- /dev/null
+++ b/kornia/augmentation/auto/rand_augment/__init__.py
@@ -0,0 +1 @@
+from .rand_augment import RandAugment
diff --git a/kornia/augmentation/auto/rand_augment/ops.py b/kornia/augmentation/auto/rand_augment/ops.py
new file mode 100644
index 000000000..2a7518397
--- /dev/null
+++ b/kornia/augmentation/auto/rand_augment/ops.py
@@ -0,0 +1,99 @@
+"""RandAugment operation wrapper."""
+from kornia.augmentation.auto.operations import (
+ AutoContrast,
+ Brightness,
+ Contrast,
+ Equalize,
+ Invert,
+ OperationBase,
+ Posterize,
+ Rotate,
+ Saturate,
+ Sharpness,
+ ShearX,
+ ShearY,
+ Solarize,
+ SolarizeAdd,
+ TranslateX,
+ TranslateY,
+)
+
+
+def shear_x(min_mag: float, max_mag: float) -> OperationBase:
+ if min_mag != -max_mag:
+ raise ValueError(
+ f"{ShearX.__name__} is a symmetric operation that `- min_mag == max_mag`. Got [{min_mag}, {max_mag}]"
+ )
+ return ShearX(None, 1.0, magnitude_range=(0.0, max_mag), symmetric_megnitude=True)
+
+
+def shear_y(min_mag: float, max_mag: float) -> OperationBase:
+ if min_mag != -max_mag:
+ raise ValueError(
+ f"{ShearY.__name__} is a symmetric operation that `- min_mag == max_mag`. Got [{min_mag}, {max_mag}]"
+ )
+ return ShearY(None, 1.0, magnitude_range=(0.0, max_mag), symmetric_megnitude=True)
+
+
+def translate_x(min_mag: float, max_mag: float) -> OperationBase:
+ if min_mag != -max_mag:
+ raise ValueError(
+ f"{TranslateX.__name__} is a symmetric operation that `- min_mag == max_mag`. Got [{min_mag}, {max_mag}]"
+ )
+ return TranslateX(None, 1.0, magnitude_range=(0.0, max_mag), symmetric_megnitude=True)
+
+
+def translate_y(min_mag: float, max_mag: float) -> OperationBase:
+ if min_mag != -max_mag:
+ raise ValueError(
+ f"{TranslateY.__name__} is a symmetric operation that `- min_mag == max_mag`. Got [{min_mag}, {max_mag}]"
+ )
+ return TranslateY(None, 1.0, magnitude_range=(0.0, max_mag), symmetric_megnitude=True)
+
+
+def rotate(min_mag: float, max_mag: float) -> OperationBase:
+ if min_mag != -max_mag:
+ raise ValueError(
+ f"{Rotate.__name__} is a symmetric operation that `- min_mag == max_mag`. Got [{min_mag}, {max_mag}]"
+ )
+ return Rotate(None, 1.0, magnitude_range=(0.0, max_mag), symmetric_megnitude=True)
+
+
+def auto_contrast(min_mag: float, max_mag: float) -> OperationBase:
+ return AutoContrast(1.0)
+
+
+def invert(min_mag: float, max_mag: float) -> OperationBase:
+ return Invert(1.0)
+
+
+def equalize(min_mag: float, max_mag: float) -> OperationBase:
+ return Equalize(1.0)
+
+
+def solarize(min_mag: float, max_mag: float) -> OperationBase:
+ return Solarize(None, 1.0, magnitude_range=(min_mag, max_mag))
+
+
+def solarize_add(min_mag: float, max_mag: float) -> OperationBase:
+ return SolarizeAdd(None, 1.0, magnitude_range=(min_mag, max_mag))
+
+
+def posterize(min_mag: float, max_mag: float) -> OperationBase:
+ return Posterize(None, 1.0, magnitude_range=(min_mag, max_mag))
+
+
+def contrast(min_mag: float, max_mag: float) -> OperationBase:
+ return Contrast(None, 1.0, magnitude_range=(min_mag, max_mag))
+
+
+def brightness(min_mag: float, max_mag: float) -> OperationBase:
+ return Brightness(None, 1.0, magnitude_range=(min_mag, max_mag))
+
+
+def sharpness(min_mag: float, max_mag: float) -> OperationBase:
+ return Sharpness(None, 1.0, magnitude_range=(min_mag, max_mag))
+
+
+def color(min_mag: float, max_mag: float) -> OperationBase:
+ return Saturate(None, 1.0, magnitude_range=(min_mag, max_mag))
diff --git a/kornia/augmentation/auto/rand_augment/rand_augment.py b/kornia/augmentation/auto/rand_augment/rand_augment.py
new file mode 100644
index 000000000..0e27734e1
--- /dev/null
+++ b/kornia/augmentation/auto/rand_augment/rand_augment.py
@@ -0,0 +1,98 @@
+from typing import Dict, Iterator, List, Optional, Tuple, Union, cast
+
+import torch
+from torch.distributions import Categorical
+
+from kornia.augmentation.auto.base import SUBPLOLICY_CONFIG, PolicyAugmentBase
+from kornia.augmentation.auto.operations import OperationBase
+from kornia.augmentation.auto.operations.policy import PolicySequential
+from kornia.augmentation.container.params import ParamItem
+from kornia.core import Module, Tensor
+
+from . import ops
+
+default_policy: List[SUBPLOLICY_CONFIG] = [
+ [("auto_contrast", 0, 1)],
+ [("equalize", 0, 1)],
+ [("invert", 0, 1)],
+ [("rotate", -30.0, 30.0)],
+ [("posterize", 0.0, 4)],
+ [("solarize", 0.0, 1.0)],
+ [("solarize_add", 0.0, 0.43)],
+ [("color", 0.1, 1.9)],
+ [("contrast", 0.1, 1.9)],
+ [("brightness", 0.1, 1.9)],
+ [("sharpness", 0.1, 1.9)],
+ [("shear_x", -0.3, 0.3)],
+ [("shear_y", -0.3, 0.3)],
+ # (CutoutAbs, 0, 40),
+ [("translate_x", -0.1, 0.1)],
+ [("translate_x", -0.1, 0.1)],
+]
+
+
+class RandAugment(PolicyAugmentBase):
+ """Apply RandAugment :cite:`cubuk2020randaugment` augmentation strategies.
+
+ Args:
+ n: the number of augmentations to apply sequentially.
+ m: magnitude for all the augmentations, ranged from [0, 30].
+ policy: candidate transformations. If None, a default candidate list will be used.
+
+ Examples:
+ >>> import kornia.augmentation as K
+ >>> in_tensor = torch.rand(5, 3, 30, 30)
+ >>> aug = K.AugmentationSequential(RandAugment(n=2, m=10))
+ >>> aug(in_tensor).shape
+ torch.Size([5, 3, 30, 30])
+ """
+
+ def __init__(self, n: int, m: int, policy: Optional[List[SUBPLOLICY_CONFIG]] = None) -> None:
+ if m <= 0 or m >= 30:
+ raise ValueError(f"Expect `m` in [0, 30]. Got {m}.")
+
+ if policy is None:
+ _policy = default_policy
+ else:
+ _policy = policy
+
+ super().__init__(_policy)
+ selection_weights = torch.tensor([1.0 / len(self)] * len(self))
+ self.rand_selector = Categorical(selection_weights)
+ self.n = n
+ self.m = m
+
+ def compose_subpolicy_sequential(self, subpolicy: SUBPLOLICY_CONFIG) -> PolicySequential:
+ if len(subpolicy) != 1:
+ raise RuntimeError(f"Each policy must have only one operation for TrivialAugment. Got {len(subpolicy)}.")
+ name, low, high = subpolicy[0]
+ return PolicySequential(*[getattr(ops, name)(low, high)])
+
+ def get_forward_sequence(self, params: Optional[List[ParamItem]] = None) -> Iterator[Tuple[str, Module]]:
+ if params is None:
+ idx = self.rand_selector.sample((self.n,))
+ return self.get_children_by_indices(idx)
+
+ return self.get_children_by_params(params)
+
+ def forward_parameters(self, batch_shape: torch.Size) -> List[ParamItem]:
+ named_modules: Iterator[Tuple[str, Module]] = self.get_forward_sequence()
+
+ params: List[ParamItem] = []
+ mod_param: Union[Dict[str, Tensor], List[ParamItem]]
+ m = torch.tensor([self.m / 30] * batch_shape[0])
+
+ for name, module in named_modules:
+ # The Input PolicySequential only got one child.
+ op = cast(PolicySequential, module)[0]
+ op = cast(OperationBase, op)
+ mag = None
+ if op.magnitude_range is not None:
+ minval, maxval = op.magnitude_range
+ mag = m * float(maxval - minval) + minval
+ mod_param = op.forward_parameters(batch_shape, mag=mag)
+ # Compose it
+ param = ParamItem(name, [ParamItem(list(module.named_children())[0][0], mod_param)])
+ params.append(param)
+
+ return params
diff --git a/kornia/augmentation/auto/trivial_augment/__init__.py b/kornia/augmentation/auto/trivial_augment/__init__.py
new file mode 100644
index 000000000..041c11cff
--- /dev/null
+++ b/kornia/augmentation/auto/trivial_augment/__init__.py
@@ -0,0 +1 @@
+from .trivial_augment import TrivialAugment
diff --git a/kornia/augmentation/auto/trivial_augment/trivial_augment.py b/kornia/augmentation/auto/trivial_augment/trivial_augment.py
new file mode 100644
index 000000000..99b54868e
--- /dev/null
+++ b/kornia/augmentation/auto/trivial_augment/trivial_augment.py
@@ -0,0 +1,65 @@
+from typing import Iterator, List, Optional, Tuple
+
+import torch
+from torch.distributions import Categorical
+
+import kornia.augmentation.auto.rand_augment.ops as ops
+from kornia.augmentation.auto.base import SUBPLOLICY_CONFIG, PolicyAugmentBase
+from kornia.augmentation.auto.operations.policy import PolicySequential
+from kornia.augmentation.container.params import ParamItem
+from kornia.core import Module
+
+default_policy: List[SUBPLOLICY_CONFIG] = [
+ # [("identity", 0, 1)],
+ [("auto_contrast", 0, 1)],
+ [("equalize", 0, 1)],
+ [("rotate", -30.0, 30.0)],
+ [("posterize", 0.0, 4)],
+ [("solarize", 0.0, 1.0)],
+ # (Color, 0.1, 1.9),
+ [("contrast", 0.1, 1.9)],
+ [("brightness", 0.1, 1.9)],
+ [("sharpness", 0.1, 1.9)],
+ [("shear_x", -0.3, 0.3)],
+ [("shear_y", -0.3, 0.3)],
+ [("translate_x", -0.5, 0.5)],
+ [("translate_y", -0.5, 0.5)],
+]
+
+
+class TrivialAugment(PolicyAugmentBase):
+ """Apply TrivialAugment :cite:`muller2021trivialaugment` augmentation strategies.
+
+ Args:
+ policy: candidate transformations. If None, a default candidate list will be used.
+
+ Examples:
+ >>> import kornia.augmentation as K
+ >>> in_tensor = torch.rand(5, 3, 30, 30)
+ >>> aug = K.AugmentationSequential(TrivialAugment())
+ >>> aug(in_tensor).shape
+ torch.Size([5, 3, 30, 30])
+ """
+
+ def __init__(self, policy: Optional[List[SUBPLOLICY_CONFIG]] = None) -> None:
+ if policy is None:
+ _policy = default_policy
+ else:
+ _policy = policy
+
+ super().__init__(_policy)
+ selection_weights = torch.tensor([1.0 / len(self)] * len(self))
+ self.rand_selector = Categorical(selection_weights)
+
+ def compose_subpolicy_sequential(self, subpolicy: SUBPLOLICY_CONFIG) -> PolicySequential:
+ if len(subpolicy) != 1:
+ raise RuntimeError(f"Each policy must have only one operation for TrivialAugment. Got {len(subpolicy)}.")
+ name, low, high = subpolicy[0]
+ return PolicySequential(*[getattr(ops, name)(low, high)])
+
+ def get_forward_sequence(self, params: Optional[List[ParamItem]] = None) -> Iterator[Tuple[str, Module]]:
+ if params is None:
+ idx = self.rand_selector.sample((1,))
+ return self.get_children_by_indices(idx)
+
+ return self.get_children_by_params(params)
diff --git a/kornia/augmentation/base.py b/kornia/augmentation/base.py
index 8c473d719..32a98115b 100644
--- a/kornia/augmentation/base.py
+++ b/kornia/augmentation/base.py
@@ -2,11 +2,16 @@ from enum import Enum
from typing import Any, Callable, Dict, Optional, Tuple, Union
import torch
-from torch.distributions import Bernoulli
+from torch.distributions import Bernoulli, Distribution, RelaxedBernoulli
from kornia.augmentation.random_generator import RandomGeneratorBase
-from kornia.augmentation.utils import _adapted_sampling, _transform_output_shape, override_parameters
-from kornia.core import Module, Tensor, tensor
+from kornia.augmentation.utils import (
+ _adapted_rsampling,
+ _adapted_sampling,
+ _transform_output_shape,
+ override_parameters,
+)
+from kornia.core import Module, Tensor, tensor, zeros
from kornia.geometry.boxes import Boxes
from kornia.geometry.keypoints import Keypoints
from kornia.utils import is_autocast_enabled
@@ -56,6 +61,8 @@ class _BasicAugmentationBase(Module):
self.same_on_batch = same_on_batch
self.keepdim = keepdim
self._params: Dict[str, Tensor] = {}
+ self._p_gen: Distribution
+ self._p_batch_gen: Distribution
if p != 0.0 or p != 1.0:
self._p_gen = Bernoulli(self.p)
if p_batch != 0.0 or p_batch != 1.0:
@@ -113,23 +120,32 @@ class _BasicAugmentationBase(Module):
) -> Tensor:
batch_prob: Tensor
if p_batch == 1:
- batch_prob = tensor([True])
+ batch_prob = zeros(1) + 1
elif p_batch == 0:
- batch_prob = tensor([False])
+ batch_prob = zeros(1)
else:
- batch_prob = _adapted_sampling((1,), self._p_batch_gen, same_on_batch).bool()
+ # NOTE: there is no simple way to know if the sampler has `rsample` or not
+ if isinstance(self._p_batch_gen, (RelaxedBernoulli,)):
+ batch_prob = _adapted_rsampling((1,), self._p_batch_gen, same_on_batch)
+ else:
+ batch_prob = _adapted_sampling((1,), self._p_batch_gen, same_on_batch)
- if batch_prob.sum().item() == 1:
+ if batch_prob.sum() == 1:
elem_prob: Tensor
if p == 1:
- elem_prob = tensor([True] * batch_shape[0])
+ elem_prob = zeros(batch_shape[0]) + 1
elif p == 0:
- elem_prob = tensor([False] * batch_shape[0])
+ elem_prob = zeros(batch_shape[0])
else:
- elem_prob = _adapted_sampling((batch_shape[0],), self._p_gen, same_on_batch).bool()
+ if isinstance(self._p_gen, (RelaxedBernoulli,)):
+ elem_prob = _adapted_rsampling((batch_shape[0],), self._p_gen, same_on_batch)
+ else:
+ elem_prob = _adapted_sampling((batch_shape[0],), self._p_gen, same_on_batch)
batch_prob = batch_prob * elem_prob
else:
batch_prob = batch_prob.repeat(batch_shape[0])
+ if len(batch_prob.shape) == 2:
+ return batch_prob[..., 0]
return batch_prob
def _process_kwargs_to_params_and_flags(
@@ -152,11 +168,12 @@ class _BasicAugmentationBase(Module):
return params, flags
def forward_parameters(self, batch_shape) -> Dict[str, Tensor]:
- to_apply = self.__batch_prob_generator__(batch_shape, self.p, self.p_batch, self.same_on_batch)
+ batch_prob = self.__batch_prob_generator__(batch_shape, self.p, self.p_batch, self.same_on_batch)
+ to_apply = batch_prob > 0.5
_params = self.generate_parameters(torch.Size((int(to_apply.sum().item()), *batch_shape[1:])))
if _params is None:
_params = {}
- _params['batch_prob'] = to_apply
+ _params['batch_prob'] = batch_prob
# Added another input_size parameter for geometric transformations
# This might be needed for correctly inversing.
input_size = tensor(batch_shape, dtype=torch.long)
@@ -238,7 +255,8 @@ class _AugmentationBase(_BasicAugmentationBase):
self._params if params is None else params, flags, **kwargs
)
- to_apply = params['batch_prob']
+ batch_prob = params['batch_prob']
+ to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions.
ori_shape = input.shape
in_tensor = self.transform_tensor(input)
if to_apply.all():
@@ -275,7 +293,8 @@ class _AugmentationBase(_BasicAugmentationBase):
self._params if params is None else params, flags, **kwargs
)
- to_apply = params['batch_prob']
+ batch_prob = params['batch_prob']
+ to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions.
ori_shape = input.shape
in_tensor = self.transform_tensor(input)
if to_apply.all():
@@ -306,9 +325,10 @@ class _AugmentationBase(_BasicAugmentationBase):
self._params if params is None else params, flags, **kwargs
)
- to_apply = params['batch_prob']
+ batch_prob = params['batch_prob']
+ to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions.
output: Boxes
- if to_apply.all():
+ if to_apply.bool().all():
output = self.apply_transform_box(input, params, flags, transform=transform)
elif not to_apply.any():
output = self.apply_non_transform_box(input, params, flags, transform=transform)
@@ -339,7 +359,8 @@ class _AugmentationBase(_BasicAugmentationBase):
self._params if params is None else params, flags, **kwargs
)
- to_apply = params['batch_prob']
+ batch_prob = params['batch_prob']
+ to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions.
if to_apply.all():
output = self.apply_transform_keypoint(input, params, flags, transform=transform)
elif not to_apply.any():
@@ -367,7 +388,8 @@ class _AugmentationBase(_BasicAugmentationBase):
self._params if params is None else params, flags, **kwargs
)
- to_apply = params['batch_prob']
+ batch_prob = params['batch_prob']
+ to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions.
if to_apply.all():
output = self.apply_transform_class(input, params, flags, transform=transform)
elif not to_apply.any():
diff --git a/kornia/augmentation/container/__init__.py b/kornia/augmentation/container/__init__.py
index a05780e08..df2d1521a 100644
--- a/kornia/augmentation/container/__init__.py
+++ b/kornia/augmentation/container/__init__.py
@@ -1,4 +1,5 @@
from kornia.augmentation.container.augment import AugmentationSequential
+from kornia.augmentation.container.base import ImageSequentialBase
from kornia.augmentation.container.dispatcher import ManyToManyAugmentationDispather, ManyToOneAugmentationDispather
from kornia.augmentation.container.image import ImageSequential
from kornia.augmentation.container.patch import PatchSequential
diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.py
index 383b36f7d..406ef8601 100644
--- a/kornia/augmentation/container/augment.py
+++ b/kornia/augmentation/container/augment.py
@@ -1,18 +1,20 @@
import warnings
from typing import Any, Dict, List, Optional, Tuple, Union, cast
-from kornia.augmentation import AugmentationBase3D, RigidAffineAugmentationBase2D, RigidAffineAugmentationBase3D
+import kornia.augmentation as K
from kornia.augmentation.base import _AugmentationBase
-from kornia.augmentation.container.image import ImageSequential, ParamItem
-from kornia.augmentation.container.ops import AugmentationSequentialOps, DataType
-from kornia.augmentation.container.patch import PatchSequential
-from kornia.augmentation.container.video import VideoSequential
from kornia.constants import DataKey, Resample
from kornia.core import Module, Tensor
from kornia.geometry.boxes import Boxes, VideoBoxes
from kornia.geometry.keypoints import Keypoints, VideoKeypoints
from kornia.utils import eye_like, is_autocast_enabled
+from .image import ImageSequential
+from .ops import AugmentationSequentialOps, DataType
+from .params import ParamItem
+from .patch import PatchSequential
+from .video import VideoSequential
+
__all__ = ["AugmentationSequential"]
@@ -193,7 +195,7 @@ class AugmentationSequential(ImageSequential):
if isinstance(arg, VideoSequential):
self.contains_video_sequential = True
# NOTE: only for images are supported for 3D.
- if isinstance(arg, AugmentationBase3D):
+ if isinstance(arg, K.AugmentationBase3D):
self.contains_3d_augmentation = True
self._transform_matrix: Optional[Tensor] = None
self.extra_args = extra_args
@@ -216,7 +218,9 @@ class AugmentationSequential(ImageSequential):
def _update_transform_matrix_by_module(self, module: Module) -> None:
if self._transformation_matrix_arg == "skip":
return
- if isinstance(module, (RigidAffineAugmentationBase2D, RigidAffineAugmentationBase3D, AugmentationSequential)):
+ if isinstance(
+ module, (K.RigidAffineAugmentationBase2D, K.RigidAffineAugmentationBase3D, AugmentationSequential)
+ ):
# Passed in pointer, allows lazy transformation matrix computation
self._transform_matrices.append(module.transform_matrix) # type: ignore
elif self._transformation_matrix_arg == "rigid":
diff --git a/kornia/augmentation/container/base.py b/kornia/augmentation/container/base.py
index 3514eb60e..11fe60dd0 100644
--- a/kornia/augmentation/container/base.py
+++ b/kornia/augmentation/container/base.py
@@ -1,36 +1,30 @@
from collections import OrderedDict
-from typing import Dict, Iterator, List, NamedTuple, Optional, Tuple, Union
+from itertools import zip_longest
+from typing import Any, Dict, Iterator, List, Optional, Tuple
import torch
import torch.nn as nn
-from kornia.augmentation import MixAugmentationBaseV2
+import kornia.augmentation as K
from kornia.augmentation.base import _AugmentationBase
from kornia.core import Module, Tensor
+from kornia.geometry.boxes import Boxes
+from kornia.geometry.keypoints import Keypoints
-__all__ = ["SequentialBase", "ParamItem"]
+from .ops import BoxSequentialOps, InputSequentialOps, KeypointSequentialOps, MaskSequentialOps
+from .params import ParamItem
+__all__ = ["BasicSequentialBase", "ImageSequentialBase", "SequentialBase"]
-class ParamItem(NamedTuple):
- name: str
- # TODO: add type List['ParamItem'] when mypy > 0.991 be available (see python/mypy#14200)
- data: Optional[Union[Dict[str, Tensor], List]] # type: ignore [type-arg]
-
-class SequentialBase(nn.Sequential):
- r"""SequentialBase for creating kornia modulized processing pipeline.
+class BasicSequentialBase(nn.Sequential):
+ r"""BasicSequential for creating kornia modulized processing pipeline.
Args:
*args : a list of kornia augmentation and image operation modules.
- same_on_batch: apply the same transformation across the batch.
- If None, it will not overwrite the function-wise settings.
- return_transform: if ``True`` return the matrix describing the transformation
- applied to each. If None, it will not overwrite the function-wise settings.
- keepdim: whether to keep the output shape the same as input (True) or broadcast it
- to the batch form (False). If None, it will not overwrite the function-wise settings.
"""
- def __init__(self, *args: Module, same_on_batch: Optional[bool] = None, keepdim: Optional[bool] = None) -> None:
+ def __init__(self, *args: Module) -> None:
# To name the modules properly
_args = OrderedDict()
for idx, mod in enumerate(args):
@@ -38,26 +32,7 @@ class SequentialBase(nn.Sequential):
raise NotImplementedError(f"Only Module are supported at this moment. Got {mod}.")
_args.update({f"{mod.__class__.__name__}_{idx}": mod})
super().__init__(_args)
- self._same_on_batch = same_on_batch
- self._keepdim = keepdim
self._params: Optional[List[ParamItem]] = None
- self.update_attribute(same_on_batch, keepdim)
-
- def update_attribute(
- self,
- same_on_batch: Optional[bool] = None,
- return_transform: Optional[bool] = None,
- keepdim: Optional[bool] = None,
- ) -> None:
- for mod in self.children():
- # MixAugmentation does not have return transform
- if isinstance(mod, (_AugmentationBase, MixAugmentationBaseV2)):
- if same_on_batch is not None:
- mod.same_on_batch = same_on_batch
- if keepdim is not None:
- mod.keepdim = keepdim
- if isinstance(mod, SequentialBase):
- mod.update_attribute(same_on_batch, return_transform, keepdim)
def get_submodule(self, target: str) -> Module:
"""Get submodule.
@@ -83,7 +58,7 @@ class SequentialBase(nn.Sequential):
return self
atoms: List[str] = target.split(".")
- mod: Module = self
+ mod = self
for item in atoms:
if not hasattr(mod, item):
@@ -96,24 +71,6 @@ class SequentialBase(nn.Sequential):
return mod
- @property
- def same_on_batch(self) -> Optional[bool]:
- return self._same_on_batch
-
- @same_on_batch.setter
- def same_on_batch(self, same_on_batch: Optional[bool]) -> None:
- self._same_on_batch = same_on_batch
- self.update_attribute(same_on_batch=same_on_batch)
-
- @property
- def keepdim(self) -> Optional[bool]:
- return self._keepdim
-
- @keepdim.setter
- def keepdim(self, keepdim: Optional[bool]) -> None:
- self._keepdim = keepdim
- self.update_attribute(keepdim=keepdim)
-
def clear_state(self) -> None:
"""Reset self._params state to None."""
self._params = None
@@ -138,6 +95,61 @@ class SequentialBase(nn.Sequential):
for name, _ in named_modules:
yield ParamItem(name, None)
+
+class SequentialBase(BasicSequentialBase):
+ r"""SequentialBase for creating kornia modulized processing pipeline.
+
+ Args:
+ *args : a list of kornia augmentation and image operation modules.
+ same_on_batch: apply the same transformation across the batch.
+ If None, it will not overwrite the function-wise settings.
+ return_transform: if ``True`` return the matrix describing the transformation
+ applied to each. If None, it will not overwrite the function-wise settings.
+ keepdim: whether to keep the output shape the same as input (True) or broadcast it
+ to the batch form (False). If None, it will not overwrite the function-wise settings.
+ """
+
+ def __init__(self, *args: Module, same_on_batch: Optional[bool] = None, keepdim: Optional[bool] = None) -> None:
+ # To name the modules properly
+ super().__init__(*args)
+ self._same_on_batch = same_on_batch
+ self._keepdim = keepdim
+ self.update_attribute(same_on_batch, keepdim)
+
+ def update_attribute(
+ self,
+ same_on_batch: Optional[bool] = None,
+ return_transform: Optional[bool] = None,
+ keepdim: Optional[bool] = None,
+ ) -> None:
+ for mod in self.children():
+ # MixAugmentation does not have return transform
+ if isinstance(mod, (_AugmentationBase, K.MixAugmentationBaseV2)):
+ if same_on_batch is not None:
+ mod.same_on_batch = same_on_batch
+ if keepdim is not None:
+ mod.keepdim = keepdim
+ if isinstance(mod, SequentialBase):
+ mod.update_attribute(same_on_batch, return_transform, keepdim)
+
+ @property
+ def same_on_batch(self) -> Optional[bool]:
+ return self._same_on_batch
+
+ @same_on_batch.setter
+ def same_on_batch(self, same_on_batch: Optional[bool]) -> None:
+ self._same_on_batch = same_on_batch
+ self.update_attribute(same_on_batch=same_on_batch)
+
+ @property
+ def keepdim(self) -> Optional[bool]:
+ return self._keepdim
+
+ @keepdim.setter
+ def keepdim(self, keepdim: Optional[bool]) -> None:
+ self._keepdim = keepdim
+ self.update_attribute(keepdim=keepdim)
+
def autofill_dim(self, input: Tensor, dim_range: Tuple[int, int] = (2, 4)) -> Tuple[torch.Size, torch.Size]:
"""Fill tensor dim to the upper bound of dim_range.
@@ -149,3 +161,116 @@ class SequentialBase(nn.Sequential):
while len(input.shape) < dim_range[1]:
input = input[None]
return ori_shape, input.shape
+
+
+class ImageSequentialBase(SequentialBase):
+ def identity_matrix(self, input) -> Tensor:
+ """Return identity matrix."""
+ raise NotImplementedError
+
+ def get_transformation_matrix(
+ self,
+ input: Tensor,
+ params: Optional[List[ParamItem]] = None,
+ recompute: bool = False,
+ extra_args: Dict[str, Any] = {},
+ ) -> Optional[Tensor]:
+ """Compute the transformation matrix according to the provided parameters.
+
+ Args:
+ input: the input tensor.
+ params: params for the sequence.
+ recompute: if to recompute the transformation matrix according to the params.
+ default: False.
+ """
+ raise NotImplementedError
+
+ def forward_parameters(self, batch_shape: torch.Size) -> List[ParamItem]:
+ raise NotImplementedError
+
+ def get_forward_sequence(self, params: Optional[List[ParamItem]] = None) -> Iterator[Tuple[str, Module]]:
+ """Get module sequence by input params."""
+ raise NotImplementedError
+
+ def transform_inputs(self, input: Tensor, params: List[ParamItem], extra_args: Dict[str, Any] = {}) -> Tensor:
+ for param in params:
+ module = self.get_submodule(param.name)
+ input = InputSequentialOps.transform(input, module=module, param=param, extra_args=extra_args)
+ return input
+
+ def inverse_inputs(self, input: Tensor, params: List[ParamItem], extra_args: Dict[str, Any] = {}) -> Tensor:
+ for (name, module), param in zip_longest(list(self.get_forward_sequence(params))[::-1], params[::-1]):
+ input = InputSequentialOps.inverse(input, module=module, param=param, extra_args=extra_args)
+ return input
+
+ def transform_masks(self, input: Tensor, params: List[ParamItem], extra_args: Dict[str, Any] = {}) -> Tensor:
+ for param in params:
+ module = self.get_submodule(param.name)
+ input = MaskSequentialOps.transform(input, module=module, param=param, extra_args=extra_args)
+ return input
+
+ def inverse_masks(self, input: Tensor, params: List[ParamItem], extra_args: Dict[str, Any] = {}) -> Tensor:
+ for (name, module), param in zip_longest(list(self.get_forward_sequence(params))[::-1], params[::-1]):
+ input = MaskSequentialOps.inverse(input, module=module, param=param, extra_args=extra_args)
+ return input
+
+ def transform_boxes(self, input: Boxes, params: List[ParamItem], extra_args: Dict[str, Any] = {}) -> Boxes:
+ for param in params:
+ module = self.get_submodule(param.name)
+ input = BoxSequentialOps.transform(input, module=module, param=param, extra_args=extra_args)
+ return input
+
+ def inverse_boxes(self, input: Boxes, params: List[ParamItem], extra_args: Dict[str, Any] = {}) -> Boxes:
+ for (name, module), param in zip_longest(list(self.get_forward_sequence(params))[::-1], params[::-1]):
+ input = BoxSequentialOps.inverse(input, module=module, param=param, extra_args=extra_args)
+ return input
+
+ def transform_keypoints(
+ self, input: Keypoints, params: List[ParamItem], extra_args: Dict[str, Any] = {}
+ ) -> Keypoints:
+ for param in params:
+ module = self.get_submodule(param.name)
+ input = KeypointSequentialOps.transform(input, module=module, param=param, extra_args=extra_args)
+ return input
+
+ def inverse_keypoints(
+ self, input: Keypoints, params: List[ParamItem], extra_args: Dict[str, Any] = {}
+ ) -> Keypoints:
+ for (name, module), param in zip_longest(list(self.get_forward_sequence(params))[::-1], params[::-1]):
+ input = KeypointSequentialOps.inverse(input, module=module, param=param, extra_args=extra_args)
+ return input
+
+ def inverse(
+ self, input: Tensor, params: Optional[List[ParamItem]] = None, extra_args: Dict[str, Any] = {}
+ ) -> Tensor:
+ """Inverse transformation.
+
+ Used to inverse a tensor according to the performed transformation by a forward pass, or with respect to
+ provided parameters.
+ """
+ if params is None:
+ if self._params is None:
+ raise ValueError(
+ "No parameters available for inversing, please run a forward pass first "
+ "or passing valid params into this function."
+ )
+ params = self._params
+
+ input = self.inverse_inputs(input, params, extra_args=extra_args)
+
+ return input
+
+ def forward(
+ self, input: Tensor, params: Optional[List[ParamItem]] = None, extra_args: Dict[str, Any] = {}
+ ) -> Tensor:
+ self.clear_state()
+
+ if params is None:
+ inp = input
+ _, out_shape = self.autofill_dim(inp, dim_range=(2, 4))
+ params = self.forward_parameters(out_shape)
+
+ input = self.transform_inputs(input, params=params, extra_args=extra_args)
+
+ self._params = params
+ return input
diff --git a/kornia/augmentation/container/dispatcher.py b/kornia/augmentation/container/dispatcher.py
index ca7a1e8a4..6b436b444 100644
--- a/kornia/augmentation/container/dispatcher.py
+++ b/kornia/augmentation/container/dispatcher.py
@@ -3,7 +3,7 @@ from typing import List, Tuple, Union
import torch.nn as nn
from torch import Tensor
-from kornia.augmentation.container.augment import AugmentationSequential
+from .augment import AugmentationSequential
class ManyToManyAugmentationDispather(nn.Module):
diff --git a/kornia/augmentation/container/image.py b/kornia/augmentation/container/image.py
index ed0fd1ada..e520b55e2 100644
--- a/kornia/augmentation/container/image.py
+++ b/kornia/augmentation/container/image.py
@@ -1,27 +1,20 @@
-from itertools import zip_longest
from typing import Any, Dict, Iterator, List, Optional, Tuple, Union, cast
import torch
-import kornia
-from kornia.augmentation import GeometricAugmentationBase2D, IntensityAugmentationBase2D, MixAugmentationBaseV2
+import kornia.augmentation as K
from kornia.augmentation.base import _AugmentationBase
-from kornia.augmentation.container.base import ParamItem, SequentialBase
-from kornia.augmentation.container.ops import (
- BoxSequentialOps,
- InputSequentialOps,
- KeypointSequentialOps,
- MaskSequentialOps,
-)
from kornia.augmentation.utils import override_parameters
from kornia.core import Module, Tensor, as_tensor
-from kornia.geometry.boxes import Boxes
-from kornia.geometry.keypoints import Keypoints
+from kornia.utils import eye_like
+
+from .base import ImageSequentialBase
+from .params import ParamItem
__all__ = ["ImageSequential"]
-class ImageSequential(SequentialBase):
+class ImageSequential(ImageSequentialBase):
r"""Sequential for creating kornia image processing pipeline.
Args:
@@ -176,7 +169,7 @@ class ImageSequential(SequentialBase):
Special operations needed for label-involved augmentations.
"""
# NOTE: MixV2 will not be a special op in the future.
- return [idx for idx, (_, child) in enumerate(named_modules) if isinstance(child, MixAugmentationBaseV2)]
+ return [idx for idx, (_, child) in enumerate(named_modules) if isinstance(child, K.MixAugmentationBaseV2)]
def get_forward_sequence(self, params: Optional[List[ParamItem]] = None) -> Iterator[Tuple[str, Module]]:
if params is None:
@@ -202,7 +195,7 @@ class ImageSequential(SequentialBase):
params: List[ParamItem] = []
mod_param: Union[Dict[str, Tensor], List[ParamItem]]
for name, module in named_modules:
- if isinstance(module, (_AugmentationBase, MixAugmentationBaseV2, ImageSequential)):
+ if isinstance(module, (_AugmentationBase, K.MixAugmentationBaseV2, ImageSequentialBase)):
mod_param = module.forward_parameters(batch_shape)
param = ParamItem(name, mod_param)
else:
@@ -213,7 +206,7 @@ class ImageSequential(SequentialBase):
def identity_matrix(self, input) -> Tensor:
"""Return identity matrix."""
- return kornia.eye_like(3, input)
+ return eye_like(3, input)
def get_transformation_matrix(
self,
@@ -237,8 +230,7 @@ class ImageSequential(SequentialBase):
# Define as 1 for broadcasting
res_mat: Optional[Tensor] = None
for (_, module), param in zip(named_modules, params if params is not None else []):
- if isinstance(module, (GeometricAugmentationBase2D,)) and isinstance(param.data, dict):
- to_apply = param.data['batch_prob']
+ if isinstance(module, (K.GeometricAugmentationBase2D,)) and isinstance(param.data, dict):
ori_shape = input.shape
try:
input = module.transform_tensor(input)
@@ -247,18 +239,19 @@ class ImageSequential(SequentialBase):
pass
# Standardize shape
if recompute:
- mat: Tensor = self.identity_matrix(input)
flags = override_parameters(module.flags, extra_args, in_place=False)
- mat[to_apply] = module.compute_transformation(input[to_apply], param.data, flags)
- else:
+ mat = module.generate_transformation_matrix(input, param.data, flags)
+ elif module._transform_matrix is not None:
mat = as_tensor(module._transform_matrix, device=input.device, dtype=input.dtype)
+ else:
+ raise RuntimeError(f"{module}._transform_matrix is None while `recompute=False`.")
res_mat = mat if res_mat is None else mat @ res_mat
input = module.transform_output_tensor(input, ori_shape)
if module.keepdim and ori_shape != input.shape:
res_mat = res_mat.squeeze()
- elif isinstance(module, (ImageSequential,)):
+ elif isinstance(module, (ImageSequentialBase,)):
# If not augmentationSequential
- if isinstance(module, (kornia.augmentation.AugmentationSequential,)) and not recompute:
+ if isinstance(module, (K.AugmentationSequential,)) and not recompute:
mat = as_tensor(module._transform_matrix, device=input.device, dtype=input.dtype)
else:
maybe_param_data = cast(Optional[List[ParamItem]], param.data)
@@ -285,7 +278,7 @@ class ImageSequential(SequentialBase):
return False
elif isinstance(arg, (ImageSequential,)):
pass
- elif isinstance(arg, IntensityAugmentationBase2D):
+ elif isinstance(arg, K.IntensityAugmentationBase2D):
pass
elif strict:
# disallow non-registered ops if in strict mode
@@ -293,90 +286,6 @@ class ImageSequential(SequentialBase):
return False
return True
- def transform_inputs(self, input: Tensor, params: List[ParamItem], extra_args: Dict[str, Any] = {}) -> Tensor:
- for param in params:
- module = self.get_submodule(param.name)
- input = InputSequentialOps.transform(input, module=module, param=param, extra_args=extra_args)
- return input
-
- def inverse_inputs(self, input: Tensor, params: List[ParamItem], extra_args: Dict[str, Any] = {}) -> Tensor:
- for (name, module), param in zip_longest(list(self.get_forward_sequence(params))[::-1], params[::-1]):
- input = InputSequentialOps.inverse(input, module=module, param=param, extra_args=extra_args)
- return input
-
- def transform_masks(self, input: Tensor, params: List[ParamItem], extra_args: Dict[str, Any] = {}) -> Tensor:
- for param in params:
- module = self.get_submodule(param.name)
- input = MaskSequentialOps.transform(input, module=module, param=param, extra_args=extra_args)
- return input
-
- def inverse_masks(self, input: Tensor, params: List[ParamItem], extra_args: Dict[str, Any] = {}) -> Tensor:
- for (name, module), param in zip_longest(list(self.get_forward_sequence(params))[::-1], params[::-1]):
- input = MaskSequentialOps.inverse(input, module=module, param=param, extra_args=extra_args)
- return input
-
- def transform_boxes(self, input: Boxes, params: List[ParamItem], extra_args: Dict[str, Any] = {}) -> Boxes:
- for param in params:
- module = self.get_submodule(param.name)
- input = BoxSequentialOps.transform(input, module=module, param=param, extra_args=extra_args)
- return input
-
- def inverse_boxes(self, input: Boxes, params: List[ParamItem], extra_args: Dict[str, Any] = {}) -> Boxes:
- for (name, module), param in zip_longest(list(self.get_forward_sequence(params))[::-1], params[::-1]):
- input = BoxSequentialOps.inverse(input, module=module, param=param, extra_args=extra_args)
- return input
-
- def transform_keypoints(
- self, input: Keypoints, params: List[ParamItem], extra_args: Dict[str, Any] = {}
- ) -> Keypoints:
- for param in params:
- module = self.get_submodule(param.name)
- input = KeypointSequentialOps.transform(input, module=module, param=param, extra_args=extra_args)
- return input
-
- def inverse_keypoints(
- self, input: Keypoints, params: List[ParamItem], extra_args: Dict[str, Any] = {}
- ) -> Keypoints:
- for (name, module), param in zip_longest(list(self.get_forward_sequence(params))[::-1], params[::-1]):
- input = KeypointSequentialOps.inverse(input, module=module, param=param, extra_args=extra_args)
- return input
-
- def inverse(
- self, input: Tensor, params: Optional[List[ParamItem]] = None, extra_args: Dict[str, Any] = {}
- ) -> Tensor:
- """Inverse transformation.
-
- Used to inverse a tensor according to the performed transformation by a forward pass, or with respect to
- provided parameters.
- """
- if params is None:
- if self._params is None:
- raise ValueError(
- "No parameters available for inversing, please run a forward pass first "
- "or passing valid params into this function."
- )
- params = self._params
-
- input = self.inverse_inputs(input, params, extra_args=extra_args)
-
- return input
-
- def forward(
- self, input: Tensor, params: Optional[List[ParamItem]] = None, extra_args: Dict[str, Any] = {}
- ) -> Tensor:
- self.clear_state()
-
- if params is None:
- inp = input
- _, out_shape = self.autofill_dim(inp, dim_range=(2, 4))
- params = self.forward_parameters(out_shape)
- for param in params:
- module = self.get_submodule(param.name)
- input = InputSequentialOps.transform(input, module=module, param=param, extra_args=extra_args)
-
- self._params = params
- return input
-
def _get_new_batch_shape(param: ParamItem, batch_shape: torch.Size) -> torch.Size:
"""Get the new batch shape if the augmentation changes the image size.
@@ -390,7 +299,7 @@ def _get_new_batch_shape(param: ParamItem, batch_shape: torch.Size) -> torch.Siz
for p in param.data:
batch_shape = _get_new_batch_shape(p, batch_shape)
elif 'output_size' in param.data:
- if not param.data['batch_prob'][0]:
+ if not (param.data['batch_prob'] > 0.5)[0]:
# Augmentations that change the image size must be applied equally to all elements in batch.
# If the augmentation is not applied, return the same batch shape.
return batch_shape
diff --git a/kornia/augmentation/container/ops.py b/kornia/augmentation/container/ops.py
index 9ea346915..d11062692 100644
--- a/kornia/augmentation/container/ops.py
+++ b/kornia/augmentation/container/ops.py
@@ -1,15 +1,15 @@
from abc import ABCMeta, abstractmethod
from typing import Any, Callable, Dict, Generic, List, Optional, Type, TypeVar, Union
-import kornia
-from kornia.augmentation import GeometricAugmentationBase2D, GeometricAugmentationBase3D, MixAugmentationBaseV2
+import kornia.augmentation as K
from kornia.augmentation.base import _AugmentationBase
-from kornia.augmentation.container.base import ParamItem
from kornia.constants import DataKey
from kornia.core import Module, Tensor
from kornia.geometry.boxes import Boxes
from kornia.geometry.keypoints import Keypoints
+from .params import ParamItem
+
DataType = Union[Tensor, List[Tensor], Boxes, Keypoints]
T = TypeVar('T')
@@ -128,7 +128,7 @@ class AugmentationSequentialOps:
return outputs
-def make_input_only_sequential(module: 'kornia.augmentation.ImageSequential') -> Callable[..., Tensor]:
+def make_input_only_sequential(module: 'K.container.ImageSequentialBase') -> Callable[..., Tensor]:
"""Disable all other additional inputs (e.g. ) for ImageSequential."""
def f(*args, **kwargs):
@@ -138,12 +138,12 @@ def make_input_only_sequential(module: 'kornia.augmentation.ImageSequential') ->
return f
-def get_geometric_only_param(module: 'kornia.augmentation.ImageSequential', param: List[ParamItem]) -> List[ParamItem]:
+def get_geometric_only_param(module: 'K.container.ImageSequentialBase', param: List[ParamItem]) -> List[ParamItem]:
named_modules = module.get_forward_sequence(param)
res: List[ParamItem] = []
for (_, mod), p in zip(named_modules, param):
- if isinstance(mod, (GeometricAugmentationBase2D, GeometricAugmentationBase3D)):
+ if isinstance(mod, (K.GeometricAugmentationBase2D, K.GeometricAugmentationBase3D)):
res.append(p)
return res
@@ -151,10 +151,12 @@ def get_geometric_only_param(module: 'kornia.augmentation.ImageSequential', para
class InputSequentialOps(SequentialOpsInterface[Tensor]):
@classmethod
def transform(cls, input: Tensor, module: Module, param: ParamItem, extra_args: Dict[str, Any] = {}) -> Tensor:
- if isinstance(module, (_AugmentationBase, MixAugmentationBaseV2)):
+ if isinstance(module, (_AugmentationBase, K.MixAugmentationBaseV2)):
input = module(input, params=cls.get_instance_module_param(param), **extra_args)
- elif isinstance(module, kornia.augmentation.ImageSequential):
+ elif isinstance(module, (K.container.ImageSequentialBase,)):
input = module.transform_inputs(input, params=cls.get_sequential_module_param(param), extra_args=extra_args)
+ elif isinstance(module, (K.auto.operations.OperationBase,)):
+ input = module(input, params=cls.get_instance_module_param(param))
else:
if param.data is not None:
raise AssertionError(f"Non-augmentaion operation {param.name} require empty parameters. Got {param}.")
@@ -163,14 +165,18 @@ class InputSequentialOps(SequentialOpsInterface[Tensor]):
@classmethod
def inverse(cls, input: Tensor, module: Module, param: ParamItem, extra_args: Dict[str, Any] = {}) -> Tensor:
- if isinstance(module, GeometricAugmentationBase2D):
+ if isinstance(module, K.GeometricAugmentationBase2D):
input = module.inverse(input, params=cls.get_instance_module_param(param), **extra_args)
- elif isinstance(module, (GeometricAugmentationBase3D,)):
+ elif isinstance(module, (K.GeometricAugmentationBase3D,)):
raise NotImplementedError(
"The support for 3d inverse operations are not yet supported. "
"You are welcome to file a PR in our repo."
)
- elif isinstance(module, kornia.augmentation.ImageSequential) and not module.is_intensity_only():
+ elif isinstance(module, (K.auto.operations.OperationBase,)):
+ return InputSequentialOps.inverse(input, module=module.op, param=param, extra_args=extra_args)
+ elif isinstance(module, K.ImageSequential) and not module.is_intensity_only():
+ input = module.inverse_inputs(input, params=cls.get_sequential_module_param(param), extra_args=extra_args)
+ elif isinstance(module, K.container.ImageSequentialBase):
input = module.inverse_inputs(input, params=cls.get_sequential_module_param(param), extra_args=extra_args)
return input
@@ -188,7 +194,7 @@ class MaskSequentialOps(SequentialOpsInterface[Tensor]):
to apply transformations.
param: the corresponding parameters to the module.
"""
- if isinstance(module, (GeometricAugmentationBase2D,)):
+ if isinstance(module, (K.GeometricAugmentationBase2D,)):
input = module.transform_masks(
input,
params=cls.get_instance_module_param(param),
@@ -197,7 +203,7 @@ class MaskSequentialOps(SequentialOpsInterface[Tensor]):
**extra_args,
)
- elif isinstance(module, (GeometricAugmentationBase3D,)):
+ elif isinstance(module, (K.GeometricAugmentationBase3D,)):
raise NotImplementedError(
"The support for 3d mask operations are not yet supported. You are welcome to file a PR in our repo."
)
@@ -207,8 +213,14 @@ class MaskSequentialOps(SequentialOpsInterface[Tensor]):
input, params=cls.get_instance_module_param(param), flags=module.flags, **extra_args
)
- elif isinstance(module, kornia.augmentation.ImageSequential) and not module.is_intensity_only():
+ elif isinstance(module, K.ImageSequential) and not module.is_intensity_only():
+ input = module.transform_masks(input, params=cls.get_sequential_module_param(param), extra_args=extra_args)
+
+ elif isinstance(module, K.container.ImageSequentialBase):
input = module.transform_masks(input, params=cls.get_sequential_module_param(param), extra_args=extra_args)
+
+ elif isinstance(module, (K.auto.operations.OperationBase,)):
+ return MaskSequentialOps.transform(input, module=module.op, param=param, extra_args=extra_args)
return input
@classmethod
@@ -221,7 +233,7 @@ class MaskSequentialOps(SequentialOpsInterface[Tensor]):
to apply transformations.
param: the corresponding parameters to the module.
"""
- if isinstance(module, (GeometricAugmentationBase2D,)):
+ if isinstance(module, (K.GeometricAugmentationBase2D,)):
if module.transform_matrix is None:
raise ValueError(f"No valid transformation matrix found in {module.__class__}.")
transform = module.compute_inverse_transformation(module.transform_matrix)
@@ -233,14 +245,17 @@ class MaskSequentialOps(SequentialOpsInterface[Tensor]):
**extra_args,
)
- elif isinstance(module, (GeometricAugmentationBase3D,)):
+ elif isinstance(module, (K.GeometricAugmentationBase3D,)):
raise NotImplementedError(
"The support for 3d mask operations are not yet supported. You are welcome to file a PR in our repo."
)
- elif isinstance(module, kornia.augmentation.ImageSequential):
+ elif isinstance(module, K.container.ImageSequentialBase):
input = module.inverse_masks(input, params=cls.get_sequential_module_param(param), extra_args=extra_args)
+ elif isinstance(module, (K.auto.operations.OperationBase,)):
+ return MaskSequentialOps.inverse(input, module=module.op, param=param, extra_args=extra_args)
+
return input
@@ -262,7 +277,7 @@ class BoxSequentialOps(SequentialOpsInterface[Boxes]):
"""
_input = input.clone()
- if isinstance(module, (GeometricAugmentationBase2D,)):
+ if isinstance(module, (K.GeometricAugmentationBase2D,)):
_input = module.transform_boxes(
_input,
cls.get_instance_module_param(param),
@@ -271,16 +286,24 @@ class BoxSequentialOps(SequentialOpsInterface[Boxes]):
**extra_args,
)
- elif isinstance(module, (GeometricAugmentationBase3D,)):
+ elif isinstance(module, (K.GeometricAugmentationBase3D,)):
raise NotImplementedError(
"The support for 3d box operations are not yet supported. You are welcome to file a PR in our repo."
)
- elif isinstance(module, kornia.augmentation.ImageSequential) and not module.is_intensity_only():
+ elif isinstance(module, K.ImageSequential) and not module.is_intensity_only():
_input = module.transform_boxes(
_input, params=cls.get_sequential_module_param(param), extra_args=extra_args
)
+ elif isinstance(module, K.container.ImageSequentialBase):
+ _input = module.transform_boxes(
+ _input, params=cls.get_sequential_module_param(param), extra_args=extra_args
+ )
+
+ elif isinstance(module, (K.auto.operations.OperationBase,)):
+ return BoxSequentialOps.transform(input, module=module.op, param=param, extra_args=extra_args)
+
return _input
@classmethod
@@ -295,7 +318,7 @@ class BoxSequentialOps(SequentialOpsInterface[Boxes]):
"""
_input = input.clone()
- if isinstance(module, (GeometricAugmentationBase2D,)):
+ if isinstance(module, (K.GeometricAugmentationBase2D,)):
if module.transform_matrix is None:
raise ValueError(f"No valid transformation matrix found in {module.__class__}.")
transform = module.compute_inverse_transformation(module.transform_matrix)
@@ -303,13 +326,19 @@ class BoxSequentialOps(SequentialOpsInterface[Boxes]):
_input, param.data, module.flags, transform=transform, **extra_args # type: ignore
)
- elif isinstance(module, (GeometricAugmentationBase3D,)):
+ elif isinstance(module, (K.GeometricAugmentationBase3D,)):
raise NotImplementedError(
"The support for 3d box operations are not yet supported. You are welcome to file a PR in our repo."
)
- elif isinstance(module, kornia.augmentation.ImageSequential) and not module.is_intensity_only():
+ elif isinstance(module, K.ImageSequential) and not module.is_intensity_only():
+ _input = module.inverse_boxes(_input, params=cls.get_sequential_module_param(param), extra_args=extra_args)
+
+ elif isinstance(module, K.container.ImageSequentialBase):
_input = module.inverse_boxes(_input, params=cls.get_sequential_module_param(param), extra_args=extra_args)
+
+ elif isinstance(module, (K.auto.operations.OperationBase,)):
+ return BoxSequentialOps.inverse(input, module=module.op, param=param, extra_args=extra_args)
return _input
@@ -333,7 +362,7 @@ class KeypointSequentialOps(SequentialOpsInterface[Keypoints]):
"""
_input = input.clone()
- if isinstance(module, (GeometricAugmentationBase2D,)):
+ if isinstance(module, (K.GeometricAugmentationBase2D,)):
_input = module.transform_keypoints(
_input,
cls.get_instance_module_param(param),
@@ -342,17 +371,25 @@ class KeypointSequentialOps(SequentialOpsInterface[Keypoints]):
**extra_args,
)
- elif isinstance(module, (GeometricAugmentationBase3D,)):
+ elif isinstance(module, (K.GeometricAugmentationBase3D,)):
raise NotImplementedError(
"The support for 3d keypoint operations are not yet supported. "
"You are welcome to file a PR in our repo."
)
- elif isinstance(module, kornia.augmentation.ImageSequential) and not module.is_intensity_only():
+ elif isinstance(module, K.ImageSequential) and not module.is_intensity_only():
+ _input = module.transform_keypoints(
+ _input, params=cls.get_sequential_module_param(param), extra_args=extra_args
+ )
+
+ elif isinstance(module, K.container.ImageSequentialBase):
_input = module.transform_keypoints(
_input, params=cls.get_sequential_module_param(param), extra_args=extra_args
)
+ elif isinstance(module, (K.auto.operations.OperationBase,)):
+ return KeypointSequentialOps.transform(input, module=module.op, param=param, extra_args=extra_args)
+
return _input
@classmethod
@@ -367,7 +404,7 @@ class KeypointSequentialOps(SequentialOpsInterface[Keypoints]):
"""
_input = input.clone()
- if isinstance(module, (GeometricAugmentationBase2D,)):
+ if isinstance(module, (K.GeometricAugmentationBase2D,)):
if module.transform_matrix is None:
raise ValueError(f"No valid transformation matrix found in {module.__class__}.")
transform = module.compute_inverse_transformation(module.transform_matrix)
@@ -375,15 +412,23 @@ class KeypointSequentialOps(SequentialOpsInterface[Keypoints]):
_input, cls.get_instance_module_param(param), module.flags, transform=transform, **extra_args
)
- elif isinstance(module, (GeometricAugmentationBase3D,)):
+ elif isinstance(module, (K.GeometricAugmentationBase3D,)):
raise NotImplementedError(
"The support for 3d keypoint operations are not yet supported. "
"You are welcome to file a PR in our repo."
)
- elif isinstance(module, kornia.augmentation.ImageSequential) and not module.is_intensity_only():
+ elif isinstance(module, K.ImageSequential) and not module.is_intensity_only():
+ _input = module.inverse_keypoints(
+ _input, params=cls.get_sequential_module_param(param), extra_args=extra_args
+ )
+
+ elif isinstance(module, K.container.ImageSequentialBase):
_input = module.inverse_keypoints(
_input, params=cls.get_sequential_module_param(param), extra_args=extra_args
)
+ elif isinstance(module, (K.auto.operations.OperationBase,)):
+ return KeypointSequentialOps.inverse(input, module=module.op, param=param, extra_args=extra_args)
+
return _input
diff --git a/kornia/augmentation/container/params.py b/kornia/augmentation/container/params.py
new file mode 100644
index 000000000..c4e6b8079
--- /dev/null
+++ b/kornia/augmentation/container/params.py
@@ -0,0 +1,16 @@
+from typing import Dict, List, NamedTuple, Optional, Union
+
+from kornia.core import Tensor
+
+__all__ = ["ParamItem", "PatchParamItem"]
+
+
+class ParamItem(NamedTuple):
+ name: str
+ # TODO: add type List['ParamItem'] when mypy > 0.991 be available (see python/mypy#14200)
+ data: Optional[Union[Dict[str, Tensor], List]] # type: ignore [type-arg]
+
+
+class PatchParamItem(NamedTuple):
+ indices: List[int]
+ param: ParamItem
diff --git a/kornia/augmentation/container/patch.py b/kornia/augmentation/container/patch.py
index 87463c981..1166df61c 100644
--- a/kornia/augmentation/container/patch.py
+++ b/kornia/augmentation/container/patch.py
@@ -1,25 +1,22 @@
from itertools import cycle, islice
-from typing import Any, Dict, Iterator, List, NamedTuple, Optional, Tuple, Union
+from typing import Any, Dict, Iterator, List, Optional, Tuple, Union
import torch
-from kornia.augmentation import MixAugmentationBaseV2
+import kornia.augmentation as K
from kornia.augmentation.base import _AugmentationBase
-from kornia.augmentation.container.base import SequentialBase
-from kornia.augmentation.container.image import ImageSequential, ParamItem
-from kornia.augmentation.container.ops import InputSequentialOps
from kornia.contrib.extract_patches import extract_tensor_patches
from kornia.core import Module, Tensor, concatenate
from kornia.core import pad as fpad
from kornia.geometry.boxes import Boxes
from kornia.geometry.keypoints import Keypoints
-__all__ = ["PatchSequential"]
-
+from .base import SequentialBase
+from .image import ImageSequential
+from .ops import InputSequentialOps
+from .params import ParamItem, PatchParamItem
-class PatchParamItem(NamedTuple):
- indices: List[int]
- param: ParamItem
+__all__ = ["PatchSequential"]
class PatchSequential(ImageSequential):
@@ -272,20 +269,20 @@ class PatchSequential(ImageSequential):
seq, mix_added = self.get_random_forward_sequence(with_mix=with_mix)
with_mix = mix_added
for s in seq:
- if isinstance(s[1], (_AugmentationBase, SequentialBase, MixAugmentationBaseV2)):
+ if isinstance(s[1], (_AugmentationBase, SequentialBase, K.MixAugmentationBaseV2)):
yield ParamItem(s[0], s[1].forward_parameters(torch.Size(batch_shape[1:]))), i
else:
yield ParamItem(s[0], None), i
elif not self.same_on_batch and not self.random_apply:
for i, nchild in enumerate(self.named_children()):
- if isinstance(nchild[1], (_AugmentationBase, SequentialBase, MixAugmentationBaseV2)):
+ if isinstance(nchild[1], (_AugmentationBase, SequentialBase, K.MixAugmentationBaseV2)):
yield ParamItem(nchild[0], nchild[1].forward_parameters(torch.Size(batch_shape[1:]))), i
else:
yield ParamItem(nchild[0], None), i
elif not self.random_apply:
# same_on_batch + not random_apply => location-wise augmentation
for i, nchild in enumerate(islice(cycle(self.named_children()), batch_shape[0])):
- if isinstance(nchild[1], (_AugmentationBase, SequentialBase, MixAugmentationBaseV2)):
+ if isinstance(nchild[1], (_AugmentationBase, SequentialBase, K.MixAugmentationBaseV2)):
yield ParamItem(nchild[0], nchild[1].forward_parameters(torch.Size(batch_shape[1:]))), i
else:
yield ParamItem(nchild[0], None), i
@@ -296,7 +293,7 @@ class PatchSequential(ImageSequential):
seq, mix_added = self.get_random_forward_sequence(with_mix=with_mix)
with_mix = mix_added
for s in seq:
- if isinstance(s[1], (_AugmentationBase, SequentialBase, MixAugmentationBaseV2)):
+ if isinstance(s[1], (_AugmentationBase, SequentialBase, K.MixAugmentationBaseV2)):
yield ParamItem(s[0], s[1].forward_parameters(torch.Size(batch_shape[1:]))), i
else:
yield ParamItem(s[0], None), i
diff --git a/kornia/augmentation/container/video.py b/kornia/augmentation/container/video.py
index 44ae8b843..d5704fa7a 100644
--- a/kornia/augmentation/container/video.py
+++ b/kornia/augmentation/container/video.py
@@ -2,15 +2,16 @@ from typing import Any, Dict, List, Optional, Tuple, Union, cast
import torch
-import kornia
-from kornia.augmentation import MixAugmentationBaseV2, RandomCrop
+import kornia.augmentation as K
from kornia.augmentation.base import _AugmentationBase
from kornia.augmentation.container.base import SequentialBase
-from kornia.augmentation.container.image import ImageSequential, ParamItem, _get_new_batch_shape
+from kornia.augmentation.container.image import ImageSequential, _get_new_batch_shape
from kornia.core import Module, Tensor
from kornia.geometry.boxes import Boxes
from kornia.geometry.keypoints import Keypoints
+from .params import ParamItem
+
__all__ = ["VideoSequential"]
@@ -41,6 +42,7 @@ class VideoSequential(ImageSequential):
If set `same_on_frame` to True, we would expect the same augmentation has been applied to each
timeframe.
+ >>> import kornia
>>> input = torch.randn(2, 3, 1, 5, 6).repeat(1, 1, 4, 1, 1)
>>> aug_list = VideoSequential(
... kornia.augmentation.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0),
@@ -168,7 +170,7 @@ class VideoSequential(ImageSequential):
params = []
for name, module in named_modules:
- if isinstance(module, RandomCrop):
+ if isinstance(module, K.RandomCrop):
mod_param = module.forward_parameters(batch_shape)
if self.same_on_frame:
mod_param["src"] = mod_param["src"].repeat(frame_num, 1, 1)
@@ -179,15 +181,12 @@ class VideoSequential(ImageSequential):
if self.same_on_frame:
raise ValueError("Sequential is currently unsupported for ``same_on_frame``.")
param = ParamItem(name, seq_param)
- elif isinstance(module, (_AugmentationBase, MixAugmentationBaseV2)):
+ elif isinstance(module, (_AugmentationBase, K.MixAugmentationBaseV2)):
mod_param = module.forward_parameters(batch_shape)
if self.same_on_frame:
for k, v in mod_param.items():
# TODO: revise ColorJiggle and ColorJitter order param in the future to align the standard.
- if k == "order" and (
- isinstance(module, kornia.augmentation.ColorJiggle)
- or isinstance(module, kornia.augmentation.ColorJitter)
- ):
+ if k == "order" and (isinstance(module, (K.ColorJiggle, K.ColorJitter))):
continue
if k == "forward_input_shape":
mod_param.update({k: v})
@@ -317,8 +316,8 @@ class VideoSequential(ImageSequential):
provided parameters.
"""
if params is None:
- if self._params is not None: # type: ignore
- params = self._params # type: ignore
+ if self._params is not None:
+ params = self._params
else:
raise RuntimeError("No valid params to inverse the transformation.")
@@ -332,7 +331,7 @@ class VideoSequential(ImageSequential):
raise AssertionError(f"Input must be a 5-dim tensor. Got {input.shape}.")
if params is None:
- if self._params is None: # type: ignore
+ if self._params is None:
self._params = self.forward_parameters(input.shape)
params = self._params
diff --git a/kornia/augmentation/random_generator/_2d/__init__.py b/kornia/augmentation/random_generator/_2d/__init__.py
index 87f0f47f4..3cb9a073e 100644
--- a/kornia/augmentation/random_generator/_2d/__init__.py
+++ b/kornia/augmentation/random_generator/_2d/__init__.py
@@ -15,3 +15,5 @@ from kornia.augmentation.random_generator._2d.posterize import *
from kornia.augmentation.random_generator._2d.probability import *
from kornia.augmentation.random_generator._2d.rectangle_earase import *
from kornia.augmentation.random_generator._2d.resize import *
+from kornia.augmentation.random_generator._2d.shear import *
+from kornia.augmentation.random_generator._2d.translate import *
diff --git a/kornia/augmentation/random_generator/_2d/affine.py b/kornia/augmentation/random_generator/_2d/affine.py
index 0ae8fe685..191a50e43 100644
--- a/kornia/augmentation/random_generator/_2d/affine.py
+++ b/kornia/augmentation/random_generator/_2d/affine.py
@@ -8,6 +8,8 @@ from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _
from kornia.core import Tensor, as_tensor, concatenate, stack, tensor, zeros
from kornia.utils.helpers import _extract_device_dtype
+__all__ = ["AffineGenerator"]
+
class AffineGenerator(RandomGeneratorBase):
r"""Get parameters for ``affine`` for a random affine transform.
@@ -34,8 +36,8 @@ class AffineGenerator(RandomGeneratorBase):
- center (Tensor): element-wise center with a shape of (B, 2).
- scale (Tensor): element-wise scales with a shape of (B, 2).
- angle (Tensor): element-wise rotation angles with a shape of (B,).
- - sx (Tensor): element-wise x-axis shears with a shape of (B,).
- - sy (Tensor): element-wise y-axis shears with a shape of (B,).
+ - shear_x (Tensor): element-wise x-axis shears with a shape of (B,).
+ - shear_y (Tensor): element-wise y-axis shears with a shape of (B,).
Note:
The generated random numbers are not reproducible across different devices and dtypes. By default,
@@ -173,6 +175,7 @@ class AffineGenerator(RandomGeneratorBase):
sx = sx.to(device=_device, dtype=_dtype)
sy = sy.to(device=_device, dtype=_dtype)
else:
- sx = sy = tensor([0] * batch_size, device=_device, dtype=_dtype)
+ sx = tensor([0] * batch_size, device=_device, dtype=_dtype)
+ sy = tensor([0] * batch_size, device=_device, dtype=_dtype)
- return dict(translations=translations, center=center, scale=_scale, angle=angle, sx=sx, sy=sy)
+ return dict(translations=translations, center=center, scale=_scale, angle=angle, shear_x=sx, shear_y=sy)
diff --git a/kornia/augmentation/random_generator/_2d/color_jiggle.py b/kornia/augmentation/random_generator/_2d/color_jiggle.py
index 1a5d47c42..dbb44f610 100644
--- a/kornia/augmentation/random_generator/_2d/color_jiggle.py
+++ b/kornia/augmentation/random_generator/_2d/color_jiggle.py
@@ -9,6 +9,8 @@ from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _
from kornia.core import Tensor
from kornia.utils.helpers import _extract_device_dtype
+__all__ = ["ColorJiggleGenerator"]
+
class ColorJiggleGenerator(RandomGeneratorBase):
r"""Generate random color jiter parameters for a batch of images following OpenCV.
diff --git a/kornia/augmentation/random_generator/_2d/color_jitter.py b/kornia/augmentation/random_generator/_2d/color_jitter.py
index 80926652a..f0d1bdaae 100644
--- a/kornia/augmentation/random_generator/_2d/color_jitter.py
+++ b/kornia/augmentation/random_generator/_2d/color_jitter.py
@@ -9,6 +9,8 @@ from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _
from kornia.core import Tensor
from kornia.utils.helpers import _extract_device_dtype
+__all__ = ["ColorJitterGenerator"]
+
class ColorJitterGenerator(RandomGeneratorBase):
r"""Generate random color jiter parameters for a batch of images following Pil.
diff --git a/kornia/augmentation/random_generator/_2d/crop.py b/kornia/augmentation/random_generator/_2d/crop.py
index 408e6cf99..7e4a97b88 100644
--- a/kornia/augmentation/random_generator/_2d/crop.py
+++ b/kornia/augmentation/random_generator/_2d/crop.py
@@ -9,6 +9,8 @@ from kornia.core import Device, Tensor, tensor, where, zeros
from kornia.geometry.bbox import bbox_generator
from kornia.utils.helpers import _extract_device_dtype
+__all__ = ["CropGenerator", "ResizedCropGenerator", "center_crop_generator"]
+
class CropGenerator(RandomGeneratorBase):
r"""Get parameters for ```crop``` transformation for crop transform.
diff --git a/kornia/augmentation/random_generator/_2d/cutmix.py b/kornia/augmentation/random_generator/_2d/cutmix.py
index 4c2db1895..baa33cc23 100644
--- a/kornia/augmentation/random_generator/_2d/cutmix.py
+++ b/kornia/augmentation/random_generator/_2d/cutmix.py
@@ -3,19 +3,14 @@ from typing import Dict, Optional, Tuple, Union
import torch
from torch.distributions import Bernoulli, Beta, Uniform
-from kornia.augmentation.random_generator._2d.probability import random_prob_generator
from kornia.augmentation.random_generator.base import RandomGeneratorBase
-from kornia.augmentation.utils import (
- _adapted_beta,
- _adapted_rsampling,
- _adapted_sampling,
- _adapted_uniform,
- _common_param_check,
- _joint_range_check,
-)
+from kornia.augmentation.utils import _adapted_rsampling, _adapted_sampling, _common_param_check, _joint_range_check
+from kornia.core import as_tensor, tensor, zeros
from kornia.geometry.bbox import bbox_generator
from kornia.utils.helpers import _extract_device_dtype
+__all__ = ["CutmixGenerator"]
+
class CutmixGenerator(RandomGeneratorBase):
r"""Generate cutmix indexes and lambdas for a batch of inputs.
@@ -61,22 +56,23 @@ class CutmixGenerator(RandomGeneratorBase):
def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
if self.beta is None:
- self._beta = torch.tensor(1.0, device=device, dtype=dtype)
+ self._beta = tensor(1.0, device=device, dtype=dtype)
else:
- self._beta = torch.as_tensor(self.beta, device=device, dtype=dtype)
+ self._beta = as_tensor(self.beta, device=device, dtype=dtype)
if self.cut_size is None:
- self._cut_size = torch.tensor([0.0, 1.0], device=device, dtype=dtype)
+ self._cut_size = tensor([0.0, 1.0], device=device, dtype=dtype)
else:
- self._cut_size = torch.as_tensor(self.cut_size, device=device, dtype=dtype)
+ self._cut_size = as_tensor(self.cut_size, device=device, dtype=dtype)
_joint_range_check(self._cut_size, 'cut_size', bounds=(0, 1))
self.beta_sampler = Beta(self._beta, self._beta)
- self.prob_sampler = Bernoulli(torch.tensor(float(self.p), device=device, dtype=dtype))
+ self.prob_sampler = Bernoulli(tensor(float(self.p), device=device, dtype=dtype))
self.rand_sampler = Uniform(
- torch.tensor(0.0, device=device, dtype=dtype),
- torch.tensor(1.0, device=device, dtype=dtype),
- validate_args=False,
+ tensor(0.0, device=device, dtype=dtype), tensor(1.0, device=device, dtype=dtype), validate_args=False
+ )
+ self.pair_sampler = Uniform(
+ tensor(0.0, device=device, dtype=dtype), tensor(1.0, device=device, dtype=dtype), validate_args=False
)
def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, torch.Tensor]:
@@ -91,15 +87,20 @@ class CutmixGenerator(RandomGeneratorBase):
if batch_size == 0:
return dict(
- mix_pairs=torch.zeros([0, 3], device=_device, dtype=torch.long),
- crop_src=torch.zeros([0, 4, 2], device=_device, dtype=_dtype),
+ mix_pairs=zeros([0, 3], device=_device, dtype=torch.long),
+ crop_src=zeros([0, 4, 2], device=_device, dtype=_dtype),
)
with torch.no_grad():
batch_probs: torch.Tensor = _adapted_sampling(
(batch_size * self.num_mix,), self.prob_sampler, same_on_batch
)
- mix_pairs: torch.Tensor = torch.rand(self.num_mix, batch_size, device=_device, dtype=_dtype).argsort(dim=1)
+ mix_pairs: torch.Tensor = (
+ _adapted_sampling((self.num_mix, batch_size), self.pair_sampler, same_on_batch)
+ .to(device=_device, dtype=_dtype)
+ .argsort(dim=1)
+ )
+
cutmix_betas: torch.Tensor = _adapted_rsampling((batch_size * self.num_mix,), self.beta_sampler, same_on_batch)
# Note: torch.clamp does not accept tensor, cutmix_betas.clamp(cut_size[0], cut_size[1]) throws:
@@ -134,144 +135,5 @@ class CutmixGenerator(RandomGeneratorBase):
return dict(
mix_pairs=mix_pairs.to(device=_device, dtype=torch.long),
crop_src=crop_src.floor().to(device=_device, dtype=_dtype),
- image_shape=torch.as_tensor(batch_shape[-2:], device=_device, dtype=_dtype),
- )
-
-
-def random_cutmix_generator(
- batch_size: int,
- width: int,
- height: int,
- p: float = 0.5,
- num_mix: int = 1,
- beta: Optional[torch.Tensor] = None,
- cut_size: Optional[torch.Tensor] = None,
- same_on_batch: bool = False,
- device: torch.device = torch.device('cpu'),
- dtype: torch.dtype = torch.float32,
-) -> Dict[str, torch.Tensor]:
- r"""Generate cutmix indexes and lambdas for a batch of inputs.
-
- Args:
- batch_size (int): the number of images. If batchsize == 1, the output will be as same as the input.
- width (int): image width.
- height (int): image height.
- p (float): probability of applying cutmix.
- num_mix (int): number of images to mix with. Default is 1.
- beta (torch.Tensor, optional): hyperparameter for generating cut size from beta distribution.
- If None, it will be set to 1.
- cut_size (torch.Tensor, optional): controlling the minimum and maximum cut ratio from [0, 1].
- If None, it will be set to [0, 1], which means no restriction.
- same_on_batch (bool): apply the same transformation across the batch. Default: False.
- device (torch.device): the device on which the random numbers will be generated. Default: cpu.
- dtype (torch.dtype): the data type of the generated random numbers. Default: float32.
-
- Returns:
- params Dict[str, torch.Tensor]: parameters to be passed for transformation.
- - mix_pairs (torch.Tensor): element-wise probabilities with a shape of (num_mix, B).
- - crop_src (torch.Tensor): element-wise probabilities with a shape of (num_mix, B, 4, 2).
-
- Note:
- The generated random numbers are not reproducible across different devices and dtypes.
-
- Examples:
- >>> rng = torch.manual_seed(0)
- >>> random_cutmix_generator(3, 224, 224, p=0.5, num_mix=2)
- {'mix_pairs': tensor([[2, 0, 1],
- [1, 2, 0]]), 'crop_src': tensor([[[[ 35., 25.],
- [208., 25.],
- [208., 198.],
- [ 35., 198.]],
- <BLANKLINE>
- [[156., 137.],
- [155., 137.],
- [155., 136.],
- [156., 136.]],
- <BLANKLINE>
- [[ 3., 12.],
- [210., 12.],
- [210., 219.],
- [ 3., 219.]]],
- <BLANKLINE>
- <BLANKLINE>
- [[[ 83., 125.],
- [177., 125.],
- [177., 219.],
- [ 83., 219.]],
- <BLANKLINE>
- [[ 54., 8.],
- [205., 8.],
- [205., 159.],
- [ 54., 159.]],
- <BLANKLINE>
- [[ 97., 70.],
- [ 96., 70.],
- [ 96., 69.],
- [ 97., 69.]]]])}
- """
- _device, _dtype = _extract_device_dtype([beta, cut_size])
- beta = torch.as_tensor(1.0 if beta is None else beta, device=device, dtype=dtype)
- cut_size = torch.as_tensor([0.0, 1.0] if cut_size is None else cut_size, device=device, dtype=dtype)
- if not (num_mix >= 1 and isinstance(num_mix, (int,))):
- raise AssertionError(f"`num_mix` must be an integer greater than 1. Got {num_mix}.")
- if not (type(height) is int and height > 0 and type(width) is int and width > 0):
- raise AssertionError(f"'height' and 'width' must be integers. Got {height}, {width}.")
- _joint_range_check(cut_size, 'cut_size', bounds=(0, 1))
- _common_param_check(batch_size, same_on_batch)
-
- if batch_size == 0:
- return dict(
- mix_pairs=torch.zeros([0, 3], device=_device, dtype=torch.long),
- crop_src=torch.zeros([0, 4, 2], device=_device, dtype=torch.long),
+ image_shape=as_tensor(batch_shape[-2:], device=_device, dtype=_dtype),
)
-
- batch_probs: torch.Tensor = random_prob_generator(
- batch_size * num_mix, p, same_on_batch, device=device, dtype=dtype
- )
- mix_pairs: torch.Tensor = torch.rand(num_mix, batch_size, device=device, dtype=dtype).argsort(dim=1)
- cutmix_betas: torch.Tensor = _adapted_beta((batch_size * num_mix,), beta, beta, same_on_batch=same_on_batch)
- # Note: torch.clamp does not accept tensor, cutmix_betas.clamp(cut_size[0], cut_size[1]) throws:
- # Argument 1 to "clamp" of "_TensorBase" has incompatible type "Tensor"; expected "float"
- cutmix_betas = torch.min(torch.max(cutmix_betas, cut_size[0]), cut_size[1])
- cutmix_rate = torch.sqrt(1.0 - cutmix_betas) * batch_probs
-
- cut_height = (cutmix_rate * height).floor().to(device=device, dtype=_dtype)
- cut_width = (cutmix_rate * width).floor().to(device=device, dtype=_dtype)
- _gen_shape = (1,)
-
- if same_on_batch:
- _gen_shape = (cut_height.size(0),)
- cut_height = cut_height[0]
- cut_width = cut_width[0]
-
- # Reserve at least 1 pixel for cropping.
- x_start = (
- _adapted_uniform(
- _gen_shape,
- torch.zeros_like(cut_width, device=device, dtype=dtype),
- (width - cut_width - 1).to(device=device, dtype=dtype),
- same_on_batch,
- )
- .floor()
- .to(device=device, dtype=_dtype)
- )
- y_start = (
- _adapted_uniform(
- _gen_shape,
- torch.zeros_like(cut_height, device=device, dtype=dtype),
- (height - cut_height - 1).to(device=device, dtype=dtype),
- same_on_batch,
- )
- .floor()
- .to(device=device, dtype=_dtype)
- )
-
- crop_src = bbox_generator(x_start.squeeze(), y_start.squeeze(), cut_width, cut_height)
-
- # (B * num_mix, 4, 2) => (num_mix, batch_size, 4, 2)
- crop_src = crop_src.view(num_mix, batch_size, 4, 2)
-
- return dict(
- mix_pairs=mix_pairs.to(device=_device, dtype=torch.long),
- crop_src=crop_src.floor().to(device=_device, dtype=_dtype),
- )
diff --git a/kornia/augmentation/random_generator/_2d/gaussian_blur.py b/kornia/augmentation/random_generator/_2d/gaussian_blur.py
index 1a20e5111..b5fcfa80a 100644
--- a/kornia/augmentation/random_generator/_2d/gaussian_blur.py
+++ b/kornia/augmentation/random_generator/_2d/gaussian_blur.py
@@ -8,6 +8,8 @@ from kornia.augmentation.random_generator.base import RandomGeneratorBase
from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _joint_range_check
from kornia.utils.helpers import _extract_device_dtype
+__all__ = ["RandomGaussianBlurGenerator"]
+
class RandomGaussianBlurGenerator(RandomGeneratorBase):
r"""Generate random gaussian blur parameters for a batch of images.
diff --git a/kornia/augmentation/random_generator/_2d/jigsaw.py b/kornia/augmentation/random_generator/_2d/jigsaw.py
index 5e8ecaa50..781b724b8 100644
--- a/kornia/augmentation/random_generator/_2d/jigsaw.py
+++ b/kornia/augmentation/random_generator/_2d/jigsaw.py
@@ -6,6 +6,8 @@ from kornia.augmentation.random_generator.base import RandomGeneratorBase
from kornia.augmentation.random_generator.utils import randperm
from kornia.augmentation.utils import _common_param_check
+__all__ = ["JigsawGenerator"]
+
class JigsawGenerator(RandomGeneratorBase):
r"""Generate Jigsaw permutation indices for a batch of inputs.
diff --git a/kornia/augmentation/random_generator/_2d/mixup.py b/kornia/augmentation/random_generator/_2d/mixup.py
index dc3b8fac7..2e240cb7d 100644
--- a/kornia/augmentation/random_generator/_2d/mixup.py
+++ b/kornia/augmentation/random_generator/_2d/mixup.py
@@ -3,17 +3,12 @@ from typing import Dict, Optional, Tuple, Union
import torch
from torch.distributions import Bernoulli, Uniform
-from kornia.augmentation.random_generator._2d.probability import random_prob_generator
from kornia.augmentation.random_generator.base import RandomGeneratorBase
-from kornia.augmentation.utils import (
- _adapted_rsampling,
- _adapted_sampling,
- _adapted_uniform,
- _common_param_check,
- _joint_range_check,
-)
+from kornia.augmentation.utils import _adapted_rsampling, _adapted_sampling, _common_param_check, _joint_range_check
from kornia.utils.helpers import _extract_device_dtype
+__all__ = ["MixupGenerator"]
+
class MixupGenerator(RandomGeneratorBase):
r"""Generate mixup indexes and lambdas for a batch of inputs.
@@ -68,55 +63,3 @@ class MixupGenerator(RandomGeneratorBase):
mixup_pairs=mixup_pairs.to(device=_device, dtype=torch.long),
mixup_lambdas=mixup_lambdas.to(device=_device, dtype=_dtype),
)
-
-
-def random_mixup_generator(
- batch_size: int,
- p: float = 0.5,
- lambda_val: Optional[torch.Tensor] = None,
- same_on_batch: bool = False,
- device: torch.device = torch.device('cpu'),
- dtype: torch.dtype = torch.float32,
-) -> Dict[str, torch.Tensor]:
- r"""Generate mixup indexes and lambdas for a batch of inputs.
-
- Args:
- batch_size (int): the number of images. If batchsize == 1, the output will be as same as the input.
- p (flot): probability of applying mixup.
- lambda_val (torch.Tensor, optional): min-max strength for mixup images, ranged from [0., 1.].
- If None, it will be set to tensor([0., 1.]), which means no restrictions.
- same_on_batch (bool): apply the same transformation across the batch. Default: False.
- device (torch.device): the device on which the random numbers will be generated. Default: cpu.
- dtype (torch.dtype): the data type of the generated random numbers. Default: float32.
-
- Returns:
- params Dict[str, torch.Tensor]: parameters to be passed for transformation.
- - mix_pairs (torch.Tensor): element-wise probabilities with a shape of (B,).
- - mixup_lambdas (torch.Tensor): element-wise probabilities with a shape of (B,).
-
- Note:
- The generated random numbers are not reproducible across different devices and dtypes.
-
- Examples:
- >>> rng = torch.manual_seed(0)
- >>> random_mixup_generator(5, 0.7)
- {'mixup_pairs': tensor([4, 0, 3, 1, 2]), 'mixup_lambdas': tensor([0.6323, 0.0000, 0.4017, 0.0223, 0.1689])}
- """
- _common_param_check(batch_size, same_on_batch)
- _device, _dtype = _extract_device_dtype([lambda_val])
- lambda_val = torch.as_tensor([0.0, 1.0] if lambda_val is None else lambda_val, device=device, dtype=dtype)
- _joint_range_check(lambda_val, 'lambda_val', bounds=(0, 1))
-
- batch_probs: torch.Tensor = random_prob_generator(
- batch_size, p, same_on_batch=same_on_batch, device=device, dtype=dtype
- )
- mixup_pairs: torch.Tensor = torch.randperm(batch_size, device=device, dtype=dtype).long()
- mixup_lambdas: torch.Tensor = _adapted_uniform(
- (batch_size,), lambda_val[0], lambda_val[1], same_on_batch=same_on_batch
- )
- mixup_lambdas = mixup_lambdas * batch_probs
-
- return dict(
- mixup_pairs=mixup_pairs.to(device=_device, dtype=torch.long),
- mixup_lambdas=mixup_lambdas.to(device=_device, dtype=_dtype),
- )
diff --git a/kornia/augmentation/random_generator/_2d/mosaic.py b/kornia/augmentation/random_generator/_2d/mosaic.py
index 46a116c5a..a3899416e 100644
--- a/kornia/augmentation/random_generator/_2d/mosaic.py
+++ b/kornia/augmentation/random_generator/_2d/mosaic.py
@@ -9,6 +9,8 @@ from kornia.core import Tensor
from kornia.geometry.bbox import bbox_generator
from kornia.utils.helpers import _extract_device_dtype
+__all__ = ["MosaicGenerator"]
+
class MosaicGenerator(RandomGeneratorBase):
r"""Generate mixup indexes and lambdas for a batch of inputs.
diff --git a/kornia/augmentation/random_generator/_2d/motion_blur.py b/kornia/augmentation/random_generator/_2d/motion_blur.py
index c7d1744b7..d9fc48969 100644
--- a/kornia/augmentation/random_generator/_2d/motion_blur.py
+++ b/kornia/augmentation/random_generator/_2d/motion_blur.py
@@ -8,6 +8,8 @@ from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _
from kornia.core import Tensor
from kornia.utils.helpers import _extract_device_dtype
+__all__ = ["MotionBlurGenerator"]
+
class MotionBlurGenerator(RandomGeneratorBase):
r"""Get parameters for motion blur.
diff --git a/kornia/augmentation/random_generator/_2d/perspective.py b/kornia/augmentation/random_generator/_2d/perspective.py
index dbb67edbd..2ec49f690 100644
--- a/kornia/augmentation/random_generator/_2d/perspective.py
+++ b/kornia/augmentation/random_generator/_2d/perspective.py
@@ -8,6 +8,8 @@ from kornia.augmentation.utils import _adapted_rsampling, _common_param_check
from kornia.core import Tensor, tensor
from kornia.utils.helpers import _extract_device_dtype
+__all__ = ["PerspectiveGenerator"]
+
class PerspectiveGenerator(RandomGeneratorBase):
r"""Get parameters for ``perspective`` for a random perspective transform.
diff --git a/kornia/augmentation/random_generator/_2d/plain_uniform.py b/kornia/augmentation/random_generator/_2d/plain_uniform.py
index e773e5454..14cf7c03f 100644
--- a/kornia/augmentation/random_generator/_2d/plain_uniform.py
+++ b/kornia/augmentation/random_generator/_2d/plain_uniform.py
@@ -8,6 +8,8 @@ from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _
from kornia.core import Tensor, as_tensor
from kornia.utils.helpers import _extract_device_dtype
+__all__ = ["ParameterBound", "PlainUniformGenerator"]
+
# factor, name, center, range
ParameterBound = Tuple[Any, str, Optional[float], Optional[Tuple[float, float]]]
@@ -44,7 +46,7 @@ class PlainUniformGenerator(RandomGeneratorBase):
super().__init__()
self.samplers = samplers
names = []
- for factor, name, _, _ in samplers:
+ for factor, name, center, bound in samplers:
if name in names:
raise RuntimeError(f"factor name `{name}` has already been registered. Please check the duplication.")
names.append(name)
@@ -52,6 +54,9 @@ class PlainUniformGenerator(RandomGeneratorBase):
self.register_parameter(name, factor)
elif isinstance(factor, Tensor):
self.register_buffer(name, factor)
+ else:
+ factor = _range_bound(factor, name, center=center, bounds=bound)
+ self.register_buffer(name, factor)
def __repr__(self) -> str:
repr = ", ".join([f"{name}={factor}" for factor, name, _, _ in self.samplers])
diff --git a/kornia/augmentation/random_generator/_2d/planckian_jitter.py b/kornia/augmentation/random_generator/_2d/planckian_jitter.py
index e9388f1ce..0b9e159a3 100644
--- a/kornia/augmentation/random_generator/_2d/planckian_jitter.py
+++ b/kornia/augmentation/random_generator/_2d/planckian_jitter.py
@@ -6,6 +6,8 @@ from torch.distributions import Uniform
from kornia.augmentation.random_generator.base import RandomGeneratorBase
from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _joint_range_check, _range_bound
+__all__ = ["PlanckianJitterGenerator"]
+
class PlanckianJitterGenerator(RandomGeneratorBase):
r"""Generate random planckian jitter parameters for a batch of images."""
diff --git a/kornia/augmentation/random_generator/_2d/posterize.py b/kornia/augmentation/random_generator/_2d/posterize.py
index 0f076831b..f82c007f4 100644
--- a/kornia/augmentation/random_generator/_2d/posterize.py
+++ b/kornia/augmentation/random_generator/_2d/posterize.py
@@ -8,13 +8,15 @@ from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _
from kornia.core import Tensor, as_tensor
from kornia.utils.helpers import _extract_device_dtype
+__all__ = ["PosterizeGenerator"]
+
class PosterizeGenerator(RandomGeneratorBase):
r"""Generate random posterize parameters for a batch of images.
Args:
- bits: Integer that ranged from (0, 8], in which 0 gives black image and 8 gives the original.
- If int x, bits will be generated from (x, 8).
+ bits: floats that ranged from (0, 8], in which 0 gives black image and 8 gives the original.
+ If float x, bits will be generated from (x, 8).
If tuple (x, y), bits will be generated from (x, y).
Returns:
@@ -27,16 +29,16 @@ class PosterizeGenerator(RandomGeneratorBase):
``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``.
"""
- def __init__(self, bits: Union[int, Tuple[int, int], Tensor]) -> None:
+ def __init__(self, bits: Union[float, Tuple[float, float], Tensor]) -> None:
super().__init__()
- self.bits = bits
+ self.bits_factor = bits
def __repr__(self) -> str:
- repr = f"bits={self.bits}"
+ repr = f"bits={self.bits_factor}"
return repr
def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
- bits = as_tensor(self.bits, device=device, dtype=dtype)
+ bits = as_tensor(self.bits_factor, device=device, dtype=dtype)
if len(bits.size()) == 0:
bits = bits.repeat(2)
bits[1] = 8
@@ -48,6 +50,6 @@ class PosterizeGenerator(RandomGeneratorBase):
def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, Tensor]:
batch_size = batch_shape[0]
_common_param_check(batch_size, same_on_batch)
- _device, _ = _extract_device_dtype([self.bits if isinstance(self.bits, Tensor) else None])
+ _device, _ = _extract_device_dtype([self.bits_factor if isinstance(self.bits_factor, Tensor) else None])
bits_factor = _adapted_rsampling((batch_size,), self.bit_sampler, same_on_batch)
- return dict(bits_factor=bits_factor.to(device=_device, dtype=torch.int32))
+ return dict(bits_factor=bits_factor.round().to(device=_device, dtype=torch.int32))
diff --git a/kornia/augmentation/random_generator/_2d/probability.py b/kornia/augmentation/random_generator/_2d/probability.py
index 2e272bb28..5a94d9cda 100644
--- a/kornia/augmentation/random_generator/_2d/probability.py
+++ b/kornia/augmentation/random_generator/_2d/probability.py
@@ -7,6 +7,8 @@ from kornia.augmentation.random_generator.base import RandomGeneratorBase
from kornia.augmentation.utils import _adapted_sampling, _common_param_check
from kornia.core import Tensor, tensor
+__all__ = ["ProbabilityGenerator"]
+
class ProbabilityGenerator(RandomGeneratorBase):
r"""Generate random probabilities for a batch of inputs.
diff --git a/kornia/augmentation/random_generator/_2d/rectangle_earase.py b/kornia/augmentation/random_generator/_2d/rectangle_earase.py
index 85bd5d4d6..007845f70 100644
--- a/kornia/augmentation/random_generator/_2d/rectangle_earase.py
+++ b/kornia/augmentation/random_generator/_2d/rectangle_earase.py
@@ -8,6 +8,8 @@ from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _
from kornia.core import Tensor, as_tensor, tensor, where
from kornia.utils.helpers import _extract_device_dtype
+__all__ = ["RectangleEraseGenerator"]
+
class RectangleEraseGenerator(RandomGeneratorBase):
r"""Get parameters for ```erasing``` transformation for erasing transform.
diff --git a/kornia/augmentation/random_generator/_2d/resize.py b/kornia/augmentation/random_generator/_2d/resize.py
index cabe5d40b..95deb206a 100644
--- a/kornia/augmentation/random_generator/_2d/resize.py
+++ b/kornia/augmentation/random_generator/_2d/resize.py
@@ -8,6 +8,8 @@ from kornia.core import Device, Tensor, tensor
from kornia.geometry.bbox import bbox_generator
from kornia.geometry.transform.affwarp import _side_to_image_size
+__all__ = ["ResizeGenerator"]
+
class ResizeGenerator(RandomGeneratorBase):
r"""Get parameters for ```resize``` transformation for resize transform.
diff --git a/kornia/augmentation/random_generator/_2d/shear.py b/kornia/augmentation/random_generator/_2d/shear.py
new file mode 100644
index 000000000..7128a69e8
--- /dev/null
+++ b/kornia/augmentation/random_generator/_2d/shear.py
@@ -0,0 +1,88 @@
+from typing import Dict, Tuple, Union
+
+import torch
+from torch.distributions import Uniform
+
+from kornia.augmentation.random_generator.base import RandomGeneratorBase
+from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _joint_range_check, _range_bound
+from kornia.core import Tensor, as_tensor, stack, tensor
+from kornia.utils.helpers import _extract_device_dtype
+
+__all__ = ["ShearGenerator"]
+
+
+class ShearGenerator(RandomGeneratorBase):
+ r"""Get parameters for ``shear`` for a random shear transform.
+
+ Args:
+ shear: Range of degrees to select from.
+ If float, a shear parallel to the x axis in the range (-shear, +shear) will be applied.
+ If (a, b), a shear parallel to the x axis in the range (-shear, +shear) will be applied.
+ If (a, b, c, d), then x-axis shear in (shear[0], shear[1]) and y-axis shear in (shear[2], shear[3])
+ will be applied. Will not apply shear by default.
+ If tensor, shear is a 2x2 tensor, a x-axis shear in (shear[0][0], shear[0][1]) and y-axis shear in
+ (shear[1][0], shear[1][1]) will be applied. Will not apply shear by default.
+
+ Returns:
+ A dict of parameters to be passed for transformation.
+ - shear_x (Tensor): element-wise x-axis shears with a shape of (B,).
+ - shear_y (Tensor): element-wise y-axis shears with a shape of (B,).
+
+ Note:
+ The generated random numbers are not reproducible across different devices and dtypes. By default,
+ the parameters will be generated on CPU in float32. This can be changed by calling
+ ``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``.
+ """
+
+ def __init__(self, shear: Union[Tensor, float, Tuple[float, float], Tuple[float, float, float, float]]) -> None:
+ super().__init__()
+ self.shear = shear
+
+ def __repr__(self) -> str:
+ repr = f"shear={self.shear}"
+ return repr
+
+ def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
+ shear = as_tensor(self.shear, device=device, dtype=dtype)
+ if shear.shape == torch.Size([2, 2]):
+ _shear = shear
+ else:
+ _shear = stack(
+ [
+ _range_bound(shear if shear.dim() == 0 else shear[:2], 'shear-x', 0, (-360, 360)),
+ tensor([0, 0], device=device, dtype=dtype)
+ if shear.dim() == 0 or len(shear) == 2
+ else _range_bound(shear[2:], 'shear-y', 0, (-360, 360)),
+ ]
+ )
+
+ _joint_range_check(_shear[0], "shear")
+ _joint_range_check(_shear[1], "shear")
+ self.shear_x = _shear[0]
+ self.shear_y = _shear[1]
+
+ shear_x_sampler = Uniform(_shear[0][0], _shear[0][1], validate_args=False)
+ shear_y_sampler = Uniform(_shear[1][0], _shear[1][1], validate_args=False)
+
+ self.shear_x_sampler = shear_x_sampler
+ self.shear_y_sampler = shear_y_sampler
+
+ def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, Tensor]:
+ batch_size = batch_shape[0]
+ height = batch_shape[-2]
+ width = batch_shape[-1]
+
+ _device, _dtype = _extract_device_dtype([self.shear])
+ _common_param_check(batch_size, same_on_batch)
+ if not (isinstance(width, (int,)) and isinstance(height, (int,)) and width > 0 and height > 0):
+ raise AssertionError(f"`width` and `height` must be positive integers. Got {width}, {height}.")
+
+ center: Tensor = tensor([width, height], device=_device, dtype=_dtype).view(1, 2) / 2.0 - 0.5
+ center = center.expand(batch_size, -1)
+
+ sx = _adapted_rsampling((batch_size,), self.shear_x_sampler, same_on_batch)
+ sy = _adapted_rsampling((batch_size,), self.shear_y_sampler, same_on_batch)
+ sx = sx.to(device=_device, dtype=_dtype)
+ sy = sy.to(device=_device, dtype=_dtype)
+
+ return dict(center=center, shear_x=sx, shear_y=sy)
diff --git a/kornia/augmentation/random_generator/_2d/translate.py b/kornia/augmentation/random_generator/_2d/translate.py
new file mode 100644
index 000000000..3a4b143ba
--- /dev/null
+++ b/kornia/augmentation/random_generator/_2d/translate.py
@@ -0,0 +1,94 @@
+from typing import Dict, Optional, Tuple, Union
+
+import torch
+from torch.distributions import Uniform
+
+from kornia.augmentation.random_generator.base import RandomGeneratorBase
+from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _range_bound
+from kornia.core import Tensor
+from kornia.utils.helpers import _extract_device_dtype
+
+__all__ = ["TranslateGenerator"]
+
+
+class TranslateGenerator(RandomGeneratorBase):
+ r"""Get parameters for ``translate`` for a random translate transform.
+
+ Args:
+ translate: tuple of maximum absolute fraction for horizontal
+ and vertical translations. For example translate=(a, b), then horizontal shift
+ is randomly sampled in the range -img_width * a < dx < img_width * a and vertical shift is
+ randomly sampled in the range -img_height * b < dy < img_height * b. Will not translate by default.
+
+ Returns:
+ A dict of parameters to be passed for transformation.
+ - translations (Tensor): element-wise translations with a shape of (B, 2).
+
+ Note:
+ The generated random numbers are not reproducible across different devices and dtypes. By default,
+ the parameters will be generated on CPU in float32. This can be changed by calling
+ ``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``.
+ """
+
+ def __init__(
+ self,
+ translate_x: Optional[Union[Tensor, Tuple[float, float]]] = None,
+ translate_y: Optional[Union[Tensor, Tuple[float, float]]] = None,
+ ) -> None:
+ super().__init__()
+ self.translate_x = translate_x
+ self.translate_y = translate_y
+
+ def __repr__(self) -> str:
+ repr = f"translate_x={self.translate_x}, translate_y={self.translate_y}"
+ return repr
+
+ def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
+ self.translate_x_sampler = None
+ self.translate_y_sampler = None
+
+ if self.translate_x is not None:
+ _translate_x = _range_bound(self.translate_x, 'translate_x', bounds=(-1, 1), check='joint').to(
+ device=device, dtype=dtype
+ )
+
+ self.translate_x_sampler = Uniform(_translate_x[..., 0], _translate_x[..., 1], validate_args=False)
+
+ if self.translate_y is not None:
+ _translate_y = _range_bound(self.translate_y, 'translate_y', bounds=(-1, 1), check='joint').to(
+ device=device, dtype=dtype
+ )
+
+ self.translate_y_sampler = Uniform(_translate_y[..., 0], _translate_y[..., 1], validate_args=False)
+
+ def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, Tensor]:
+ batch_size = batch_shape[0]
+ height = batch_shape[-2]
+ width = batch_shape[-1]
+
+ _device, _dtype = _extract_device_dtype([self.translate_x, self.translate_y])
+ _common_param_check(batch_size, same_on_batch)
+ if not (isinstance(width, (int,)) and isinstance(height, (int,)) and width > 0 and height > 0):
+ raise AssertionError(f"`width` and `height` must be positive integers. Got {width}, {height}.")
+
+ if self.translate_x_sampler is not None:
+ translate_x = (
+ _adapted_rsampling((batch_size,), self.translate_x_sampler, same_on_batch).to(
+ device=_device, dtype=_dtype
+ )
+ * width
+ )
+ else:
+ translate_x = torch.zeros((batch_size,), device=_device, dtype=_dtype)
+
+ if self.translate_y_sampler is not None:
+ translate_y = (
+ _adapted_rsampling((batch_size,), self.translate_y_sampler, same_on_batch).to(
+ device=_device, dtype=_dtype
+ )
+ * height
+ )
+ else:
+ translate_y = torch.zeros((batch_size,), device=_device, dtype=_dtype)
+
+ return dict(translate_x=translate_x, translate_y=translate_y)
diff --git a/kornia/augmentation/utils/param_validation.py b/kornia/augmentation/utils/param_validation.py
index 824d87dd7..8800c9220 100644
--- a/kornia/augmentation/utils/param_validation.py
+++ b/kornia/augmentation/utils/param_validation.py
@@ -16,8 +16,8 @@ def _common_param_check(batch_size: int, same_on_batch: Optional[bool] = None):
def _range_bound(
factor: Union[Tensor, float, Tuple[float, float], List[float]],
name: str,
- center: float = 0.0,
- bounds: Tuple[float, float] = (0, float('inf')),
+ center: Optional[float] = 0.0,
+ bounds: Optional[Tuple[float, float]] = (0, float('inf')),
check: Optional[str] = 'joint',
device: torch.device = torch.device('cpu'),
dtype: torch.dtype = torch.get_default_dtype(),
@@ -29,7 +29,9 @@ def _range_bound(
if factor.dim() == 0:
if factor < 0:
- raise ValueError(f"If {name} is a single number number, it must be non negative. Got {factor}")
+ raise ValueError(f"If {name} is a single number, it must be non negative. Got {factor}.")
+ if center is None or bounds is None:
+ raise ValueError(f"`center` and `bounds` cannot be None for single number. Got {center}, {bounds}.")
# Should be something other than clamp
# Currently, single value factor will not out of scope as long as the user provided it.
# Note: I personally think throw an error will be better than a coarse clamp.
diff --git a/kornia/core/__init__.py b/kornia/core/__init__.py
index c39f0afde..5e5093490 100644
--- a/kornia/core/__init__.py
+++ b/kornia/core/__init__.py
@@ -7,6 +7,7 @@ from ._backend import (
complex,
concatenate,
eye,
+ linspace,
normalize,
pad,
rand,
@@ -34,4 +35,5 @@ __all__ = [
"zeros",
"complex",
"zeros_like",
+ "linspace",
]
diff --git a/kornia/core/_backend.py b/kornia/core/_backend.py
index 71a29ceca..b0f53388c 100644
--- a/kornia/core/_backend.py
+++ b/kornia/core/_backend.py
@@ -14,6 +14,7 @@ Parameter = torch.nn.Parameter
# NOTE: ideally we expose what we find in numpy
concatenate = torch.cat
stack = torch.stack
+linspace = torch.linspace
normalize = F.normalize
pad = F.pad
eye = torch.eye
diff --git a/kornia/enhance/adjust.py b/kornia/enhance/adjust.py
index 1434f0623..56898733e 100644
--- a/kornia/enhance/adjust.py
+++ b/kornia/enhance/adjust.py
@@ -309,7 +309,7 @@ def adjust_contrast(image: Tensor, factor: Union[float, Tensor], clip_output: bo
in the batch. 0 generates a completely black image, 1 does not modify
the input image while any other non-negative number modify the
brightness by this factor.
- clip_output: whether to clip the output image with range of [0, 1].
+ clip_output: whether to clip the output image with range of [0, 1].
Return:
Adjusted image in the shape of :math:`(*, H, W)`.
diff --git a/kornia/geometry/transform/imgwarp.py b/kornia/geometry/transform/imgwarp.py
index fe209b1d2..b16f307e5 100644
--- a/kornia/geometry/transform/imgwarp.py
+++ b/kornia/geometry/transform/imgwarp.py
@@ -29,6 +29,7 @@ __all__ = [
"invert_affine_transform",
"get_affine_matrix2d",
"get_affine_matrix3d",
+ "get_translation_matrix2d",
"get_shear_matrix2d",
"get_shear_matrix3d",
"warp_affine3d",
@@ -603,6 +604,27 @@ def get_affine_matrix2d(
return transform_h
+def get_translation_matrix2d(translations: Tensor) -> Tensor:
+ r"""Compose translation matrix from the components.
+
+ Args:
+ translations: tensor containing the translation vector with shape :math:`(B, 2)`.
+
+ Returns:
+ the affine transformation matrix :math:`(B, 3, 3)`.
+
+ .. note::
+ This function is often used in conjunction with :func:`warp_affine`, :func:`warp_perspective`.
+ """
+ transform: Tensor = eye_like(3, translations)[:, :2, :]
+ transform[..., 2] += translations # tx/ty
+
+ # pad transform to get Bx3x3
+ transform_h = convert_affinematrix_to_homography(transform)
+
+ return transform_h
+
+
def get_shear_matrix2d(center: Tensor, sx: Optional[Tensor] = None, sy: Optional[Tensor] = None):
r"""Compose shear matrix Bx4x4 from the components.
diff --git a/test/augmentation/test_augmentation.py b/test/augmentation/test_augmentation.py
index 77c18588a..9c2a0c4a0 100644
--- a/test/augmentation/test_augmentation.py
+++ b/test/augmentation/test_augmentation.py
@@ -149,19 +149,18 @@ class CommonTests(BaseTester):
assert isinstance(generated_params, dict)
# compute_transformation can be called and returns the correct shaped transformation matrix
- expected_transformation_shape = torch.Size((generated_params['batch_prob'].sum(), 3, 3))
+ to_apply = generated_params['batch_prob'] > 0.5
+ expected_transformation_shape = torch.Size((to_apply.sum(), 3, 3))
test_input = torch.ones(batch_shape, device=self.device, dtype=self.dtype)
- transformation = augmentation.compute_transformation(
- test_input[generated_params['batch_prob']], generated_params, augmentation.flags
- )
+ transformation = augmentation.compute_transformation(test_input[to_apply], generated_params, augmentation.flags)
assert transformation.shape == expected_transformation_shape
# apply_transform can be called and returns the correct batch sized output
- if generated_params['batch_prob'].sum() != 0:
+ if to_apply.sum() != 0:
output = augmentation.apply_transform(
- test_input[generated_params['batch_prob']], generated_params, augmentation.flags, transformation
+ test_input[to_apply], generated_params, augmentation.flags, transformation
)
- assert output.shape[0] == generated_params['batch_prob'].sum()
+ assert output.shape[0] == to_apply.sum()
else:
# Re-generate parameters if 0 batch size
self._test_smoke_implementation(params)
@@ -4059,3 +4058,39 @@ class TestRandomRGBShift:
dtype=dtype,
)
utils.assert_close(f(input), expected, rtol=1e-4, atol=1e-4)
+
+
+class TestRandomTranslate:
+ torch.manual_seed(0) # for random reproductibility
+
+ def test_smoke_no_transform(self, device):
+ x_data = torch.rand(1, 2, 8, 9).to(device)
+ aug = kornia.augmentation.RandomTranslate((0.5, 0.5))
+ out = aug(x_data)
+ assert out.shape == x_data.shape
+ assert aug.inverse(out).shape == x_data.shape
+ assert aug.inverse(out, aug._params).shape == x_data.shape
+
+ def test_gradcheck(self, device):
+ input = torch.rand(1, 2, 5, 7).to(device)
+ input = utils.tensor_to_gradcheck_var(input) # to var
+ # TODO: turned off with p=0
+ assert gradcheck(
+ kornia.augmentation.RandomTranslate((0.5, 0.5), p=1.0), (input,), raise_exception=True, fast_mode=True
+ )
+
+
+class TestRandomAutoContrast:
+ torch.manual_seed(0) # for random reproductibility
+
+ def test_smoke_no_transform(self, device):
+ x_data = torch.rand(1, 2, 8, 9).to(device)
+ aug = kornia.augmentation.RandomAutoContrast()
+ out = aug(x_data)
+ assert out.shape == x_data.shape
+
+ def test_gradcheck(self, device):
+ input = torch.rand(1, 2, 5, 7).to(device)
+ input = utils.tensor_to_gradcheck_var(input) # to var
+ # TODO: turned off with p=0
+ assert gradcheck(kornia.augmentation.RandomAutoContrast(p=1.0), (input,), raise_exception=True, fast_mode=True)
diff --git a/test/augmentation/test_auto_operation.py b/test/augmentation/test_auto_operation.py
new file mode 100644
index 000000000..dac5ab87b
--- /dev/null
+++ b/test/augmentation/test_auto_operation.py
@@ -0,0 +1,138 @@
+import inspect
+from test.augmentation.test_container import reproducibility_test
+from typing import List
+
+import pytest
+import torch
+
+import kornia.augmentation.auto.operations.ops as ops
+from kornia.augmentation.auto.autoaugment import AutoAugment
+from kornia.augmentation.auto.operations import OperationBase
+from kornia.augmentation.auto.rand_augment.rand_augment import RandAugment
+from kornia.augmentation.auto.rand_augment.rand_augment import default_policy as randaug_config
+from kornia.augmentation.auto.trivial_augment import TrivialAugment
+from kornia.augmentation.container import AugmentationSequential
+from kornia.geometry.bbox import bbox_to_mask
+from kornia.testing import assert_close
+
+
+def _find_all_ops() -> List[OperationBase]:
+ _ops = [op for _, op in inspect.getmembers(ops, inspect.isclass)]
+ return list([op() for op in _ops if issubclass(op, OperationBase) and op != OperationBase])
+
+
+def _test_sequential(augment_method, device, dtype):
+ inp = torch.rand(1, 3, 1000, 500, device=device, dtype=dtype)
+ bbox = torch.tensor([[[355, 10], [660, 10], [660, 250], [355, 250]]], device=device, dtype=dtype)
+ keypoints = torch.tensor([[[465, 115], [545, 116]]], device=device, dtype=dtype)
+ mask = bbox_to_mask(
+ torch.tensor([[[155, 0], [900, 0], [900, 400], [155, 400]]], device=device, dtype=dtype), 1000, 500
+ )[:, None]
+ aug = AugmentationSequential(augment_method, data_keys=["input", "mask", "bbox", "keypoints"])
+ out = aug(inp, mask, bbox, keypoints)
+ assert out[0].shape == inp.shape
+ assert out[1].shape == mask.shape
+ assert out[2].shape == bbox.shape
+ assert out[3].shape == keypoints.shape
+ assert set(out[1].unique().tolist()).issubset(set(mask.unique().tolist()))
+
+ out_inv = aug.inverse(*out)
+ assert out_inv[0].shape == inp.shape
+ assert out_inv[1].shape == mask.shape
+ assert out_inv[2].shape == bbox.shape
+ assert out_inv[3].shape == keypoints.shape
+ assert set(out_inv[1].unique().tolist()).issubset(set(mask.unique().tolist()))
+
+ reproducibility_test((inp, mask, bbox, keypoints), aug)
+
+
+class TestOperations:
+ @pytest.mark.parametrize("op", _find_all_ops())
+ def test_step_routine(self, op: OperationBase):
+ op = op.eval()
+ op = op.train()
+ if op.magnitude is not None:
+ init_mag = op.magnitude.item()
+ init_prob = op.probability.item()
+
+ optimizer = torch.optim.SGD(op.parameters(), lr=10, momentum=0.9)
+
+ for _ in range(5):
+ in_tensor = torch.rand(10, 3, 50, 50, requires_grad=True)
+ optimizer.zero_grad()
+ x = op(in_tensor)
+ loss = (x - 0).mean()
+ loss.backward()
+ optimizer.step()
+
+ if op.magnitude is not None:
+ assert init_mag != op.magnitude.item()
+ if isinstance(op, ops.Equalize):
+ # NOTE: Equalize is somehow not working yet to update the probabilities.
+ return
+ assert init_prob != op.probability.item()
+
+
+class TestAutoAugment:
+ @pytest.mark.parametrize("policy", ["imagenet", "cifar10", "svhn", [[("shear_x", 0.9, 4), ("invert", 0.2, None)]]])
+ def test_smoke(self, policy):
+ aug = AutoAugment(policy)
+ in_tensor = torch.rand(10, 3, 50, 50, requires_grad=True)
+ aug(in_tensor)
+ aug.is_intensity_only()
+
+ def test_transform_mat(self):
+ aug = AutoAugment([[("shear_x", 0.9, 4), ("invert", 0.2, None)]])
+ in_tensor = torch.rand(10, 3, 50, 50, requires_grad=True)
+ aug(in_tensor)
+ aug.get_transformation_matrix(in_tensor, params=aug._params)
+
+ def test_reproduce(self):
+ aug = AutoAugment()
+ in_tensor = torch.rand(10, 3, 50, 50, requires_grad=True)
+ out_tensor = aug(in_tensor)
+ out_tensor_2 = aug(in_tensor, params=aug._params)
+ assert_close(out_tensor, out_tensor_2)
+
+ def test_sequential(augment_method, device, dtype):
+ _test_sequential(AutoAugment(), device=device, dtype=dtype)
+
+
+class TestRandAugment:
+ @pytest.mark.parametrize("policy", [None, [[("translate_y", -0.5, 0.5)]]])
+ def test_smoke(self, policy):
+ if policy is None:
+ n = len(randaug_config)
+ else:
+ n = 1
+ aug = RandAugment(n=n, m=15, policy=policy)
+ in_tensor = torch.rand(10, 3, 50, 50, requires_grad=True)
+ aug(in_tensor)
+
+ def test_reproduce(self):
+ aug = RandAugment(n=3, m=15)
+ in_tensor = torch.rand(10, 3, 50, 50, requires_grad=True)
+ out_tensor = aug(in_tensor)
+ out_tensor_2 = aug(in_tensor, params=aug._params)
+ assert_close(out_tensor, out_tensor_2)
+
+ def test_sequential(augment_method, device, dtype):
+ _test_sequential(RandAugment(n=3, m=15), device=device, dtype=dtype)
+
+
+class TestTrivialAugment:
+ @pytest.mark.parametrize("policy", [None, [[("translate_y", -0.5, 0.5)]]])
+ def test_smoke(self, policy):
+ aug = TrivialAugment(policy=policy)
+ in_tensor = torch.rand(10, 3, 50, 50, requires_grad=True)
+ aug(in_tensor)
+
+ def test_reproduce(self):
+ aug = TrivialAugment()
+ in_tensor = torch.rand(10, 3, 50, 50, requires_grad=True)
+ out_tensor = aug(in_tensor)
+ out_tensor_2 = aug(in_tensor, params=aug._params)
+ assert_close(out_tensor, out_tensor_2)
+
+ def test_sequential(augment_method, device, dtype):
+ _test_sequential(TrivialAugment(), device=device, dtype=dtype)
diff --git a/test/augmentation/test_container.py b/test/augmentation/test_container.py
index 2a5897f7d..87218d6e7 100644
--- a/test/augmentation/test_container.py
+++ b/test/augmentation/test_container.py
@@ -67,6 +67,9 @@ class TestVideoSequential:
K.RandomMotionBlur(3, 35.0, 0.5, p=1.0),
K.Normalize(torch.tensor([0.5, 0.5, 0.5]), torch.tensor([0.5, 0.5, 0.5]), p=1.0),
K.Denormalize(torch.tensor([0.5, 0.5, 0.5]), torch.tensor([0.5, 0.5, 0.5]), p=1.0),
+ K.RandomAutoContrast(p=1.0),
+ K.RandomShear((10.0, 10.0), p=1.0),
+ K.RandomTranslate((0.5, 0.5), p=1.0),
],
)
@pytest.mark.parametrize('data_format', ["BCTHW", "BTCHW"])
diff --git a/test/augmentation/test_perspective_rand.py b/test/augmentation/test_perspective_rand.py
index b9ae609f2..3a7fde800 100644
--- a/test/augmentation/test_perspective_rand.py
+++ b/test/augmentation/test_perspective_rand.py
@@ -196,3 +196,23 @@ class TestRandomAffine:
input = utils.tensor_to_gradcheck_var(input) # to var
# TODO: turned off with p=0
assert gradcheck(kornia.augmentation.RandomAffine(10, p=0.0), (input,), raise_exception=True, fast_mode=True)
+
+
+class TestRandomShear:
+ torch.manual_seed(0) # for random reproductibility
+
+ def test_smoke_no_transform(self, device):
+ x_data = torch.rand(1, 2, 8, 9).to(device)
+ aug = kornia.augmentation.RandomShear((10.0, 10.0))
+ out = aug(x_data)
+ assert out.shape == x_data.shape
+ assert aug.inverse(out).shape == x_data.shape
+ assert aug.inverse(out, aug._params).shape == x_data.shape
+
+ def test_gradcheck(self, device):
+ input = torch.rand(1, 2, 5, 7).to(device)
+ input = utils.tensor_to_gradcheck_var(input) # to var
+ # TODO: turned off with p=0
+ assert gradcheck(
+ kornia.augmentation.RandomShear((10.0, 10.0), p=1.0), (input,), raise_exception=True, fast_mode=True
+ )
diff --git a/test/augmentation/test_random_generator.py b/test/augmentation/test_random_generator.py
index cc678f978..02822e5cf 100644
--- a/test/augmentation/test_random_generator.py
+++ b/test/augmentation/test_random_generator.py
@@ -7,6 +7,8 @@ from kornia.augmentation.random_generator import (
ColorJiggleGenerator,
ColorJitterGenerator,
CropGenerator,
+ CutmixGenerator,
+ MixupGenerator,
MotionBlurGenerator,
PerspectiveGenerator,
PlainUniformGenerator,
@@ -15,8 +17,6 @@ from kornia.augmentation.random_generator import (
RectangleEraseGenerator,
ResizedCropGenerator,
center_crop_generator,
- random_cutmix_generator,
- random_mixup_generator,
)
from kornia.testing import assert_close
from kornia.utils._compat import torch_version_ge
@@ -548,16 +548,16 @@ class TestRandomAffineGen(RandomGeneratorBaseTests):
center=torch.tensor([[99.5000, 99.5000], [99.5000, 99.5000]], device=device, dtype=dtype),
scale=torch.tensor([[0.8914, 0.8914], [1.1797, 1.1797]], device=device, dtype=dtype),
angle=torch.tensor([18.8227, 19.1500], device=device, dtype=dtype),
- sx=torch.tensor([19.4077, 11.3319], device=device, dtype=dtype),
- sy=torch.tensor([19.3460, 15.9358], device=device, dtype=dtype),
+ shear_x=torch.tensor([19.4077, 11.3319], device=device, dtype=dtype),
+ shear_y=torch.tensor([19.3460, 15.9358], device=device, dtype=dtype),
)
assert res.keys() == expected.keys()
assert_close(res['translations'], expected['translations'], rtol=1e-4, atol=1e-4)
assert_close(res['center'], expected['center'], rtol=1e-4, atol=1e-4)
assert_close(res['scale'], expected['scale'], rtol=1e-4, atol=1e-4)
assert_close(res['angle'], expected['angle'], rtol=1e-4, atol=1e-4)
- assert_close(res['sx'], expected['sx'], rtol=1e-4, atol=1e-4)
- assert_close(res['sy'], expected['sy'], rtol=1e-4, atol=1e-4)
+ assert_close(res['shear_x'], expected['shear_x'], rtol=1e-4, atol=1e-4)
+ assert_close(res['shear_y'], expected['shear_y'], rtol=1e-4, atol=1e-4)
def test_same_on_batch(self, device, dtype):
torch.manual_seed(42)
@@ -576,16 +576,16 @@ class TestRandomAffineGen(RandomGeneratorBaseTests):
center=torch.tensor([[99.5000, 99.5000], [99.5000, 99.5000]], device=device, dtype=dtype),
scale=torch.tensor([[1.1575, 1.1575], [1.1575, 1.1575]], device=device, dtype=dtype),
angle=torch.tensor([18.8227, 18.8227], device=device, dtype=dtype),
- sx=torch.tensor([13.9045, 13.9045], device=device, dtype=dtype),
- sy=torch.tensor([16.0090, 16.0090], device=device, dtype=dtype),
+ shear_x=torch.tensor([13.9045, 13.9045], device=device, dtype=dtype),
+ shear_y=torch.tensor([16.0090, 16.0090], device=device, dtype=dtype),
)
assert res.keys() == expected.keys()
assert_close(res['translations'], expected['translations'], rtol=1e-4, atol=1e-4)
assert_close(res['center'], expected['center'], rtol=1e-4, atol=1e-4)
assert_close(res['scale'], expected['scale'], rtol=1e-4, atol=1e-4)
assert_close(res['angle'], expected['angle'], rtol=1e-4, atol=1e-4)
- assert_close(res['sx'], expected['sx'], rtol=1e-4, atol=1e-4)
- assert_close(res['sy'], expected['sy'], rtol=1e-4, atol=1e-4)
+ assert_close(res['shear_x'], expected['shear_x'], rtol=1e-4, atol=1e-4)
+ assert_close(res['shear_y'], expected['shear_y'], rtol=1e-4, atol=1e-4)
class TestRandomCropGen(RandomGeneratorBaseTests):
@@ -973,7 +973,7 @@ class TestRandomPosterizeGen(RandomGeneratorBaseTests):
torch.manual_seed(9)
batch_size = 8
res = PosterizeGenerator(bits=torch.tensor([0, 8], device=device, dtype=dtype))(torch.Size([batch_size]))
- expected = dict(bits_factor=torch.tensor([5, 2, 3, 6, 7, 7, 2, 7], device=device, dtype=torch.int32))
+ expected = dict(bits_factor=torch.tensor([5, 2, 4, 6, 7, 7, 2, 8], device=device, dtype=torch.int32))
assert res.keys() == expected.keys()
assert_close(res['bits_factor'], expected['bits_factor'], rtol=1e-4, atol=1e-4)
@@ -1041,28 +1041,25 @@ class TestRandomMixUpGen(RandomGeneratorBaseTests):
@pytest.mark.parametrize('lambda_val', [None, torch.tensor([0.0, 1.0])])
@pytest.mark.parametrize('same_on_batch', [True, False])
def test_valid_param_combinations(self, batch_size, p, lambda_val, same_on_batch, device, dtype):
- random_mixup_generator(
- batch_size=batch_size,
+ MixupGenerator(
p=p,
lambda_val=lambda_val.to(device=device, dtype=dtype) if isinstance(lambda_val, (Tensor)) else lambda_val,
- same_on_batch=same_on_batch,
- )
+ )(torch.Size([batch_size, 3, 200, 200]), same_on_batch=same_on_batch)
@pytest.mark.parametrize(
'lambda_val', [(torch.tensor([-1, 1])), (torch.tensor([0, 2])), (torch.tensor([0, 0.5, 1])), ([0.0, 1.0])]
)
def test_invalid_param_combinations(self, lambda_val, device, dtype):
with pytest.raises(Exception):
- random_mixup_generator(batch_size=8, lambda_val=lambda_val.to(device=device, dtype=dtype))
+ MixupGenerator(p=1.0, lambda_val=lambda_val.to(device=device, dtype=dtype))(
+ torch.Size([8, 3, 200, 200]), same_on_batch=False
+ )
def test_random_gen(self, device, dtype):
torch.manual_seed(42)
batch_size = 8
- res = random_mixup_generator(
- batch_size=batch_size,
- p=0.5,
- lambda_val=torch.tensor([0.0, 1.0], device=device, dtype=dtype),
- same_on_batch=False,
+ res = MixupGenerator(p=0.5, lambda_val=torch.tensor([0.0, 1.0], device=device, dtype=dtype))(
+ torch.Size([batch_size, 3, 200, 200]), same_on_batch=False
)
expected = dict(
mixup_pairs=torch.tensor([6, 1, 0, 7, 2, 5, 3, 4], device=device, dtype=torch.long),
@@ -1077,11 +1074,8 @@ class TestRandomMixUpGen(RandomGeneratorBaseTests):
def test_same_on_batch(self, device, dtype):
torch.manual_seed(9)
batch_size = 8
- res = random_mixup_generator(
- batch_size=batch_size,
- p=0.9999,
- lambda_val=torch.tensor([0.0, 1.0], device=device, dtype=dtype),
- same_on_batch=True,
+ res = MixupGenerator(p=0.999999, lambda_val=torch.tensor([0.0, 1.0], device=device, dtype=dtype))(
+ torch.Size([batch_size, 3, 200, 200]), same_on_batch=True
)
expected = dict(
mixup_pairs=torch.tensor([4, 6, 7, 5, 0, 1, 3, 2], device=device, dtype=torch.long),
@@ -1105,16 +1099,12 @@ class TestRandomCutMixGen(RandomGeneratorBaseTests):
def test_valid_param_combinations(
self, batch_size, p, width, height, num_mix, beta, cut_size, same_on_batch, device, dtype
):
- random_cutmix_generator(
- batch_size=batch_size,
+ CutmixGenerator(
p=p,
- width=width,
- height=height,
num_mix=num_mix,
beta=beta.to(device=device, dtype=dtype) if isinstance(beta, (Tensor)) else beta,
cut_size=cut_size.to(device=device, dtype=dtype) if isinstance(cut_size, (Tensor)) else cut_size,
- same_on_batch=same_on_batch,
- )
+ )(torch.Size([batch_size, 3, height, width]), same_on_batch=same_on_batch)
@pytest.mark.parametrize(
'width,height,num_mix,beta,cut_size',
@@ -1131,55 +1121,56 @@ class TestRandomCutMixGen(RandomGeneratorBaseTests):
@pytest.mark.parametrize('same_on_batch', [True, False])
def test_invalid_param_combinations(self, width, height, num_mix, beta, cut_size, same_on_batch, device, dtype):
with pytest.raises(Exception):
- random_cutmix_generator(
- batch_size=8,
+ CutmixGenerator(
p=0.5,
- width=width,
- height=height,
num_mix=num_mix,
beta=beta.to(device=device, dtype=dtype) if isinstance(beta, (Tensor)) else beta,
- cut_size=beta.to(device=device, dtype=dtype) if isinstance(cut_size, (Tensor)) else cut_size,
- same_on_batch=same_on_batch,
- )
+ cut_size=cut_size.to(device=device, dtype=dtype) if isinstance(cut_size, (Tensor)) else cut_size,
+ )(torch.Size([8, 3, height, width]), same_on_batch=same_on_batch)
def test_random_gen(self, device, dtype):
torch.manual_seed(42)
- batch_size = 2
- res = random_cutmix_generator(
- batch_size=batch_size,
- width=200,
- height=200,
+ image_shape = torch.Size([8, 3, 200, 200])
+ res = CutmixGenerator(
p=0.5,
num_mix=1,
beta=torch.tensor(1.0, device=device, dtype=dtype),
cut_size=torch.tensor([0.0, 1.0], device=device, dtype=dtype),
- same_on_batch=False,
- )
+ )(image_shape, same_on_batch=False)
+
expected = dict(
- mix_pairs=torch.tensor([[0, 1]], device=device, dtype=torch.long),
+ mix_pairs=torch.tensor([[1, 7, 5, 3, 6, 4, 2, 0]], device=device, dtype=torch.long),
crop_src=torch.tensor(
- [[[[71, 108], [70, 108], [70, 107], [71, 107]], [[39, 1], [38, 1], [38, 0], [39, 0]]]],
+ [
+ [
+ [[48.0, 31.0], [47.0, 31.0], [47.0, 30.0], [48.0, 30.0]],
+ [[48.0, 31.0], [47.0, 31.0], [47.0, 30.0], [48.0, 30.0]],
+ [[17.0, 11.0], [141.0, 11.0], [141.0, 135.0], [17.0, 135.0]],
+ [[48.0, 31.0], [47.0, 31.0], [47.0, 30.0], [48.0, 30.0]],
+ [[16.0, 10.0], [147.0, 10.0], [147.0, 141.0], [16.0, 141.0]],
+ [[48.0, 31.0], [47.0, 31.0], [47.0, 30.0], [48.0, 30.0]],
+ [[8.0, 5.0], [171.0, 5.0], [171.0, 168.0], [8.0, 168.0]],
+ [[48.0, 31.0], [47.0, 31.0], [47.0, 30.0], [48.0, 30.0]],
+ ]
+ ],
device=device,
dtype=dtype,
),
+ image_shape=image_shape,
)
- assert res.keys() == expected.keys()
+ assert res.keys() == expected.keys(), res.keys()
assert_close(res['mix_pairs'], expected['mix_pairs'], rtol=1e-4, atol=1e-4)
assert_close(res['crop_src'], expected['crop_src'], rtol=1e-4, atol=1e-4)
def test_same_on_batch(self, device, dtype):
torch.manual_seed(42)
- batch_size = 2
- res = random_cutmix_generator(
- batch_size=batch_size,
- width=200,
- height=200,
+ image_shape = torch.Size([2, 3, 200, 200])
+ res = CutmixGenerator(
p=0.5,
num_mix=1,
beta=torch.tensor(1.0, device=device, dtype=dtype),
cut_size=torch.tensor([0.0, 1.0], device=device, dtype=dtype),
- same_on_batch=True,
- )
+ )(image_shape, same_on_batch=True)
expected = dict(
mix_pairs=torch.tensor([[1, 0]], device=device, dtype=torch.long),
crop_src=torch.tensor(
@@ -1187,7 +1178,8 @@ class TestRandomCutMixGen(RandomGeneratorBaseTests):
device=device,
dtype=dtype,
),
+ image_shape=image_shape,
)
- assert res.keys() == expected.keys()
+ assert res.keys() == expected.keys(), res.keys()
assert_close(res['mix_pairs'], expected['mix_pairs'], rtol=1e-4, atol=1e-4)
assert_close(res['crop_src'], expected['crop_src'], rtol=1e-4, atol=1e-4)