Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Restructure augmentation package (#1515)

twslb69c9e2fd39b
diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile
new file mode 100644
index 000000000..a4f634adf
--- /dev/null
+++ b/.devcontainer/Dockerfile
@@ -0,0 +1,25 @@
+# See here for image contents: https://github.com/microsoft/vscode-dev-containers/blob/main/containers/python-3/.devcontainer/base.Dockerfile
+
+# [Choice] Python version: 3, 3.9, 3.8, 3.7, 3.6
+ARG VARIANT="3.8"
+FROM mcr.microsoft.com/vscode/devcontainers/python:${VARIANT}
+
+# [Option] Install Node.js
+ARG INSTALL_NODE="true"
+ARG NODE_VERSION="lts/*"
+RUN if [ "${INSTALL_NODE}" = "true" ]; then su vscode -c "umask 0002 && . /usr/local/share/nvm/nvm.sh && nvm install ${NODE_VERSION} 2>&1"; fi
+
+# https://exerror.com/importerror-libgl-so-1-cannot-open-shared-object-file-no-such-file-or-directory/
+RUN apt-get update && apt install -y libgl1-mesa-glx
+
+# [Optional] If your pip requirements rarely change, uncomment this section to add them to the image.
+COPY requirements/ /tmp/pip-tmp/requirements/
+COPY docs/requirements.txt /tmp/pip-tmp/docs/
+RUN pip3 --disable-pip-version-check --no-cache-dir install -r /tmp/pip-tmp/requirements/dev.txt && rm -rf /tmp/pip-tmp
+
+# [Optional] Uncomment this section to install additional OS packages.
+# RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \
+# && apt-get -y install --no-install-recommends <your-package-list-here>
+
+# [Optional] Uncomment this line to install global node packages.
+# RUN su vscode -c "source /usr/local/share/nvm/nvm.sh && npm install -g <your-package-here>" 2>&1
diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json
new file mode 100644
index 000000000..6490d3f58
--- /dev/null
+++ b/.devcontainer/devcontainer.json
@@ -0,0 +1,94 @@
+{
+ "name": "Python 3",
+ "build": {
+ "dockerfile": "Dockerfile",
+ "context": "..",
+ "args": {
+ // Update 'VARIANT' to pick a Python version: 3, 3.6, 3.7, 3.8, 3.9, 3.10
+ "VARIANT": "3.8",
+ // Options
+ "INSTALL_NODE": "true",
+ "NODE_VERSION": "lts/*"
+ },
+ },
+ "runArgs": [
+ // Enable GPU passthrough, requires WSL2 on Windows
+ //"--gpus=all",
+ // One of the following options is required for torch multiprocessing
+ //"--ipc=host",
+ //"--shm-size=4gb",
+ ],
+ "settings": {
+ "editor.formatOnSave": true,
+ "editor.rulers": [
+ 120
+ ],
+ "python.pythonPath": "/usr/local/bin/python",
+ "python.defaultInterpreterPath": "/usr/local/bin/python",
+ "python.languageServer": "Pylance",
+ "python.autoComplete.addBrackets": true,
+ "python.analysis.autoImportCompletions": true,
+ "python.analysis.completeFunctionParens": true,
+ "python.analysis.autoSearchPaths": true,
+ "python.analysis.useImportHeuristic": true,
+ "python.analysis.diagnosticMode": "workspace",
+ "python.sortImports": true,
+ "python.sortImports.args": [
+ // isort recommends pyproject.toml
+ // "--settings-path=${workspaceFolder}/pyproject.toml",
+ "--settings-path=${workspaceFolder}/setup.cfg"
+ ],
+ "python.formatting.autopep8Path": "/usr/local/py-utils/bin/autopep8",
+ "python.formatting.blackPath": "/usr/local/py-utils/bin/black",
+ "python.formatting.provider": "black",
+ "python.formatting.blackArgs": [
+ "--config=${workspaceFolder}/pyproject.toml"
+ ],
+ "python.linting.banditPath": "/usr/local/py-utils/bin/bandit",
+ "python.linting.flake8Path": "/usr/local/py-utils/bin/flake8",
+ "python.linting.mypyPath": "/usr/local/py-utils/bin/mypy",
+ "python.linting.pycodestylePath": "/usr/local/py-utils/bin/pycodestyle",
+ "python.linting.pydocstylePath": "/usr/local/py-utils/bin/pydocstyle",
+ "python.linting.pylintPath": "/usr/local/py-utils/bin/pylint",
+ "python.linting.enabled": true,
+ "python.linting.pylintEnabled": false,
+ "python.linting.flake8Enabled": true,
+ "python.linting.flake8Args": [
+ "--config=${workspaceFolder}/setup.cfg",
+ "--verbose"
+ ],
+ "python.testing.pytestArgs": [
+ "test"
+ ],
+ "python.testing.unittestEnabled": false,
+ "python.testing.pytestEnabled": true,
+ "restructuredtext.confPath": "${workspaceFolder}/docs/source",
+ "restructuredtext.builtDocumentationPath": "${workspaceFolder}/docs/build",
+ "restructuredtext.languageServer.disabled": false,
+ "[python]": {
+ "editor.codeActionsOnSave": {
+ "source.organizeImports": true,
+ }
+ }
+ },
+ // Add the IDs of extensions you want installed when the container is created.
+ "extensions": [
+ "ms-python.python",
+ "ms-python.vscode-pylance",
+ "visualstudioexptteam.vscodeintellicode",
+ "kevinrose.vsc-python-indent",
+ "littlefoxteam.vscode-python-test-adapter",
+ "hbenl.vscode-test-explorer",
+ "medo64.render-crlf",
+ "shardulm94.trailing-spaces",
+ "njqdev.vscode-python-typehint",
+ "lextudio.restructuredtext",
+ "trond-snekvik.simple-rst",
+ ],
+ // Use 'forwardPorts' to make a list of ports inside the container available locally.
+ // "forwardPorts": [],
+ // Use 'postCreateCommand' to run commands after the container is created.
+ "postCreateCommand": "pre-commit install && sudo /usr/local/bin/python setup.py develop",
+ // Comment out connect as root instead. More info: https://aka.ms/vscode-remote/containers/non-root.
+ "remoteUser": "vscode"
+}
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index a28239be9..f1f6cf530 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -14,6 +14,7 @@ repos:
- id: trailing-whitespace
- id: check-yaml
- id: pretty-format-json
+ exclude: ^$|.devcontainer
- repo: https://github.com/psf/black
rev: 21.12b0
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ebaf96171..63ddc43d2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,20 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
****
+## :rocket: [0.X.X] - 2022-XX-XX
+### :new: New Features
+- Devcontainer (#1515)
+
+### :lady_beetle: Bug fixes
+
+
+### :exclamation: Changes
+- Restructure augmentation package (#1515)
+
+### :zap: Improvements
+
+
+
## :rocket: [0.6.2] - 2021-12-03
### :new: New Features
- Add face detection API (#1469)
diff --git a/kornia/augmentation/_2d/__init__.py b/kornia/augmentation/_2d/__init__.py
new file mode 100644
index 000000000..5e389e0c6
--- /dev/null
+++ b/kornia/augmentation/_2d/__init__.py
@@ -0,0 +1,3 @@
+from kornia.augmentation._2d.geometric import *
+from kornia.augmentation._2d.intensity import *
+from kornia.augmentation._2d.mix import *
diff --git a/kornia/augmentation/_2d/base.py b/kornia/augmentation/_2d/base.py
new file mode 100644
index 000000000..a463406f7
--- /dev/null
+++ b/kornia/augmentation/_2d/base.py
@@ -0,0 +1,49 @@
+import torch
+
+import kornia
+from kornia.augmentation.base import TensorWithTransformMat, _AugmentationBase
+from kornia.augmentation.utils import _transform_input, _validate_input_dtype
+
+
+class AugmentationBase2D(_AugmentationBase):
+ r"""AugmentationBase2D base class for customized augmentation implementations.
+
+ For any augmentation, the implementation of "generate_parameters" and "apply_transform" are required while the
+ "compute_transformation" is only required when passing "return_transform" as True.
+
+ Args:
+ p: probability for applying an augmentation. This param controls the augmentation probabilities
+ element-wise for a batch.
+ p_batch: probability for applying an augmentation to a batch. This param controls the augmentation
+ probabilities batch-wise.
+ return_transform: if ``True`` return the matrix describing the geometric transformation applied to each
+ input tensor. If ``False`` and the input is a tuple the applied transformation won't be concatenated.
+ 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``.
+ """
+
+ def __check_batching__(self, input: TensorWithTransformMat):
+ if isinstance(input, tuple):
+ inp, mat = input
+ if len(inp.shape) == 4:
+ if len(mat.shape) != 3:
+ raise AssertionError('Input tensor is in batch mode ' 'but transformation matrix is not')
+ if mat.shape[0] != inp.shape[0]:
+ raise AssertionError(
+ f"In batch dimension, input has {inp.shape[0]} but transformation matrix has {mat.shape[0]}"
+ )
+ elif len(inp.shape) in (2, 3):
+ if len(mat.shape) != 2:
+ raise AssertionError("Input tensor is in non-batch mode but transformation matrix is not")
+ else:
+ raise ValueError(f'Unrecognized output shape. Expected 2, 3, or 4, got {len(inp.shape)}')
+
+ def transform_tensor(self, input: torch.Tensor) -> torch.Tensor:
+ """Convert any incoming (H, W), (C, H, W) and (B, C, H, W) into (B, C, H, W)."""
+ _validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])
+ return _transform_input(input)
+
+ def identity_matrix(self, input) -> torch.Tensor:
+ """Return 3x3 identity matrix."""
+ return kornia.eye_like(3, input)
diff --git a/kornia/augmentation/_2d/geometric/__init__.py b/kornia/augmentation/_2d/geometric/__init__.py
new file mode 100644
index 000000000..aa909f451
--- /dev/null
+++ b/kornia/augmentation/_2d/geometric/__init__.py
@@ -0,0 +1,12 @@
+from kornia.augmentation._2d.geometric.affine import RandomAffine
+from kornia.augmentation._2d.geometric.center_crop import CenterCrop
+from kornia.augmentation._2d.geometric.crop import RandomCrop
+from kornia.augmentation._2d.geometric.elastic_transform import RandomElasticTransform
+from kornia.augmentation._2d.geometric.fisheye import RandomFisheye
+from kornia.augmentation._2d.geometric.horizontal_flip import RandomHorizontalFlip
+from kornia.augmentation._2d.geometric.pad import PadTo
+from kornia.augmentation._2d.geometric.perspective import RandomPerspective
+from kornia.augmentation._2d.geometric.resized_crop import RandomResizedCrop
+from kornia.augmentation._2d.geometric.rotation import RandomRotation
+from kornia.augmentation._2d.geometric.thin_plate_spline import RandomThinPlateSpline
+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
new file mode 100644
index 000000000..96180f19e
--- /dev/null
+++ b/kornia/augmentation/_2d/geometric/affine.py
@@ -0,0 +1,131 @@
+from typing import Dict, Optional, Tuple, Union, cast
+
+import torch
+
+from kornia.augmentation import random_generator as rg
+from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
+from kornia.constants import Resample, SamplePadding
+from kornia.geometry.conversions import deg2rad
+from kornia.geometry.transform import get_affine_matrix2d, warp_affine
+
+
+class RandomAffine(GeometricAugmentationBase2D):
+ r"""Apply a random 2D affine transformation to a tensor image.
+
+ .. image:: _static/img/RandomAffine.png
+
+ The transformation is computed so that the image center is kept invariant.
+
+ Args:
+ p: probability of applying the transformation.
+ degrees: Range of degrees to select from.
+ If degrees is a number instead of sequence like (min, max), the range of degrees
+ will be (-degrees, +degrees). Set to 0 to deactivate rotations.
+ 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.
+ scale: scaling factor interval.
+ If (a, b) represents isotropic scaling, the scale is randomly sampled from the range a <= scale <= b.
+ If (a, b, c, d), the scale is randomly sampled from the range a <= scale_x <= b, c <= scale_y <= d.
+ Will keep original scale by default.
+ 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).
+ return_transform: if ``True`` return the matrix describing the transformation applied to each.
+ same_on_batch: apply the same transformation across the batch.
+ align_corners: interpolation flag.
+ 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)`, Optional: :math:`(B, 3, 3)`
+ - Output: :math:`(B, C, H, W)`
+
+ .. note::
+ This function internally uses :func:`kornia.geometry.transform.warp_affine`.
+
+ Examples:
+ >>> rng = torch.manual_seed(0)
+ >>> input = torch.rand(1, 1, 3, 3)
+ >>> aug = RandomAffine((-15., 20.), return_transform=True, p=1.)
+ >>> out = aug(input)
+ >>> out
+ (tensor([[[[0.3961, 0.7310, 0.1574],
+ [0.1781, 0.3074, 0.5648],
+ [0.4804, 0.8379, 0.4234]]]]), tensor([[[ 0.9923, -0.1241, 0.1319],
+ [ 0.1241, 0.9923, -0.1164],
+ [ 0.0000, 0.0000, 1.0000]]]))
+ >>> aug.inverse(out)
+ tensor([[[[0.3890, 0.6573, 0.1865],
+ [0.2063, 0.3074, 0.5459],
+ [0.3892, 0.7896, 0.4224]]]])
+ >>> input
+ tensor([[[[0.4963, 0.7682, 0.0885],
+ [0.1320, 0.3074, 0.6341],
+ [0.4901, 0.8964, 0.4556]]]])
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.randn(1, 3, 32, 32)
+ >>> aug = RandomAffine((-15., 20.), p=1.)
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
+ """
+
+ def __init__(
+ self,
+ degrees: Union[torch.Tensor, float, Tuple[float, float]],
+ translate: Optional[Union[torch.Tensor, Tuple[float, float]]] = None,
+ scale: Optional[Union[torch.Tensor, Tuple[float, float], Tuple[float, float, float, float]]] = None,
+ shear: Optional[Union[torch.Tensor, float, Tuple[float, float]]] = None,
+ resample: Union[str, int, Resample] = Resample.BILINEAR.name,
+ return_transform: bool = False,
+ 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, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
+ self._param_generator = cast(rg.AffineGenerator, rg.AffineGenerator(degrees, translate, scale, shear))
+ self.flags = dict(
+ resample=Resample.get(resample), padding_mode=SamplePadding.get(padding_mode), align_corners=align_corners
+ )
+
+ def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.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)),
+ )
+
+ def apply_transform(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ ) -> torch.Tensor:
+ _, _, height, width = input.shape
+ transform = cast(torch.Tensor, transform)
+ return warp_affine(
+ input,
+ transform[:, :2, :],
+ (height, width),
+ self.flags["resample"].name.lower(),
+ align_corners=self.flags["align_corners"],
+ padding_mode=self.flags["padding_mode"].name.lower(),
+ )
+
+ def inverse_transform(
+ self,
+ input: torch.Tensor,
+ transform: Optional[torch.Tensor] = None,
+ size: Optional[Tuple[int, int]] = None,
+ **kwargs,
+ ) -> torch.Tensor:
+ return self.apply_transform(
+ input, params=self._params, transform=torch.as_tensor(transform, device=input.device, dtype=input.dtype)
+ )
diff --git a/kornia/augmentation/_2d/geometric/base.py b/kornia/augmentation/_2d/geometric/base.py
new file mode 100644
index 000000000..0535d6665
--- /dev/null
+++ b/kornia/augmentation/_2d/geometric/base.py
@@ -0,0 +1,96 @@
+import warnings
+from typing import Dict, Optional, Tuple, cast
+
+import torch
+
+from kornia.augmentation._2d.base import AugmentationBase2D
+from kornia.augmentation.base import TensorWithTransformMat
+from kornia.augmentation.utils import _transform_output_shape
+from kornia.utils.helpers import _torch_inverse_cast
+
+
+class GeometricAugmentationBase2D(AugmentationBase2D):
+ r"""GeometricAugmentationBase2D base class for customized geometric augmentation implementations.
+
+ For any augmentation, the implementation of "generate_parameters" and "apply_transform" are required while the
+ "compute_transformation" is only required when passing "return_transform" as True.
+
+ Args:
+ p: probability for applying an augmentation. This param controls the augmentation probabilities
+ element-wise for a batch.
+ p_batch: probability for applying an augmentation to a batch. This param controls the augmentation
+ probabilities batch-wise.
+ return_transform: if ``True`` return the matrix describing the geometric transformation applied to each
+ input tensor. If ``False`` and the input is a tuple the applied transformation won't be concatenated.
+ 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``.
+ """
+
+ def inverse_transform(
+ self,
+ input: torch.Tensor,
+ transform: Optional[torch.Tensor] = None,
+ size: Optional[Tuple[int, int]] = None,
+ **kwargs,
+ ) -> torch.Tensor:
+ """By default, the exact transformation as ``apply_transform`` will be used."""
+ raise NotImplementedError
+
+ def compute_inverse_transformation(self, transform: torch.Tensor):
+ """Compute the inverse transform of given transformation matrices."""
+ return _torch_inverse_cast(transform)
+
+ def get_transformation_matrix(
+ self, input: torch.Tensor, params: Optional[Dict[str, torch.Tensor]] = None
+ ) -> torch.Tensor:
+ if params is not None:
+ transform = self.compute_transformation(input[params['batch_prob']], params)
+ elif not hasattr(self, "_transform_matrix"):
+ params = self.forward_parameters(input.shape)
+ transform = self.identity_matrix(input)
+ transform[params['batch_prob']] = self.compute_transformation(input[params['batch_prob']], params)
+ else:
+ transform = self._transform_matrix
+ return torch.as_tensor(transform, device=input.device, dtype=input.dtype)
+
+ def inverse(
+ self,
+ input: TensorWithTransformMat,
+ params: Optional[Dict[str, torch.Tensor]] = None,
+ size: Optional[Tuple[int, int]] = None,
+ **kwargs,
+ ) -> torch.Tensor:
+ if isinstance(input, (list, tuple)):
+ input, transform = input
+ else:
+ transform = self.get_transformation_matrix(input, params)
+ if params is not None:
+ transform = self.identity_matrix(input)
+ transform[params['batch_prob']] = self.compute_transformation(input[params['batch_prob']], params)
+
+ ori_shape = input.shape
+ in_tensor = self.transform_tensor(input)
+ batch_shape = input.shape
+ if params is None:
+ params = self._params
+ if size is None and "forward_input_shape" in params:
+ # Majorly for cropping functions
+ size = params['forward_input_shape'].numpy().tolist()
+ size = (size[-2], size[-1])
+ if 'batch_prob' not in params:
+ params['batch_prob'] = torch.tensor([True] * batch_shape[0])
+ warnings.warn("`batch_prob` is not found in params. Will assume applying on all data.")
+ output = input.clone()
+ to_apply = params['batch_prob']
+ # if no augmentation needed
+ if torch.sum(to_apply) == 0:
+ output = in_tensor
+ # if all data needs to be augmented
+ elif torch.sum(to_apply) == len(to_apply):
+ transform = self.compute_inverse_transformation(transform)
+ output = self.inverse_transform(in_tensor, transform, size, **kwargs)
+ else:
+ transform[to_apply] = self.compute_inverse_transformation(transform[to_apply])
+ output[to_apply] = self.inverse_transform(in_tensor[to_apply], transform[to_apply], size, **kwargs)
+ return cast(torch.Tensor, _transform_output_shape(output, ori_shape)) if self.keepdim else output
diff --git a/kornia/augmentation/_2d/geometric/center_crop.py b/kornia/augmentation/_2d/geometric/center_crop.py
new file mode 100644
index 000000000..cf524b33d
--- /dev/null
+++ b/kornia/augmentation/_2d/geometric/center_crop.py
@@ -0,0 +1,141 @@
+from typing import Dict, Optional, Tuple, Union, cast
+
+import torch
+
+from kornia.augmentation import random_generator as rg
+from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
+from kornia.constants import Resample
+from kornia.geometry.transform import crop_by_transform_mat, get_perspective_transform
+
+
+class CenterCrop(GeometricAugmentationBase2D):
+ r"""Crop a given image tensor at the center.
+
+ .. image:: _static/img/CenterCrop.png
+
+ Args:
+ size: Desired output size (out_h, out_w) of the crop.
+ If integer, out_h = out_w = size.
+ If Tuple[int, int], out_h = size[0], out_w = size[1].
+ align_corners: interpolation flag.
+ resample: The interpolation mode.
+ return_transform: if ``True`` return the matrix describing the transformation
+ applied to each.
+ p: probability of applying the transformation for the whole batch.
+ keepdim: whether to keep the output shape the same as input (True) or broadcast it
+ to the batch form (False).
+ cropping_mode: The used algorithm to crop. ``slice`` will use advanced slicing to extract the tensor based
+ on the sampled indices. ``resample`` will use `warp_affine` using the affine transformation
+ to extract and resize at once. Use `slice` for efficiency, or `resample` for proper
+ differentiability.
+
+ Shape:
+ - Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
+ - Output: :math:`(B, C, out_h, out_w)`
+
+ .. note::
+ This function internally uses :func:`kornia.geometry.transform.crop_by_boxes`.
+
+ Examples:
+ >>> rng = torch.manual_seed(0)
+ >>> inputs = torch.randn(1, 1, 4, 4)
+ >>> inputs
+ tensor([[[[-1.1258, -1.1524, -0.2506, -0.4339],
+ [ 0.8487, 0.6920, -0.3160, -2.1152],
+ [ 0.3223, -1.2633, 0.3500, 0.3081],
+ [ 0.1198, 1.2377, 1.1168, -0.2473]]]])
+ >>> aug = CenterCrop(2, p=1., cropping_mode="resample")
+ >>> out = aug(inputs)
+ >>> out
+ tensor([[[[ 0.6920, -0.3160],
+ [-1.2633, 0.3500]]]])
+ >>> aug.inverse(out, padding_mode="border")
+ tensor([[[[ 0.6920, 0.6920, -0.3160, -0.3160],
+ [ 0.6920, 0.6920, -0.3160, -0.3160],
+ [-1.2633, -1.2633, 0.3500, 0.3500],
+ [-1.2633, -1.2633, 0.3500, 0.3500]]]])
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.randn(1, 3, 32, 32)
+ >>> aug = CenterCrop(2, p=1., cropping_mode="resample")
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
+ """
+
+ def __init__(
+ self,
+ size: Union[int, Tuple[int, int]],
+ align_corners: bool = True,
+ resample: Union[str, int, Resample] = Resample.BILINEAR.name,
+ return_transform: bool = False,
+ p: float = 1.0,
+ keepdim: bool = False,
+ cropping_mode: str = "slice",
+ ) -> None:
+ # same_on_batch is always True for CenterCrop
+ # Since PyTorch does not support ragged tensor. So cropping function happens batch-wisely.
+ super().__init__(p=1.0, return_transform=return_transform, same_on_batch=True, p_batch=p, keepdim=keepdim)
+ if isinstance(size, tuple):
+ self.size = (size[0], size[1])
+ elif isinstance(size, int):
+ self.size = (size, size)
+ else:
+ raise Exception(f"Invalid size type. Expected (int, tuple(int, int). " f"Got: {type(size)}.")
+
+ self.flags = dict(
+ resample=Resample.get(resample), cropping_mode=cropping_mode, align_corners=align_corners, size=self.size
+ )
+
+ def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
+ return rg.center_crop_generator(batch_shape[0], batch_shape[-2], batch_shape[-1], self.size, self.device)
+
+ def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
+ transform: torch.Tensor = get_perspective_transform(params["src"].to(input), params["dst"].to(input))
+ transform = transform.expand(input.shape[0], -1, -1)
+ return transform
+
+ def apply_transform(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ ) -> torch.Tensor:
+ if self.flags["cropping_mode"] == "resample": # uses bilinear interpolation to crop
+ transform = cast(torch.Tensor, transform)
+ return crop_by_transform_mat(
+ input,
+ transform[:, :2, :],
+ self.size,
+ self.flags["resample"].name.lower(),
+ "zeros",
+ self.flags["align_corners"],
+ )
+ if self.flags["cropping_mode"] == "slice": # uses advanced slicing to crop
+ # TODO: implement as separated function `crop_and_resize_iterative`
+ B, C, _, _ = input.shape
+ H, W = self.size
+ out = torch.empty(B, C, H, W, device=input.device, dtype=input.dtype)
+ for i in range(B):
+ x1 = int(params["src"][i, 0, 0])
+ x2 = int(params["src"][i, 1, 0]) + 1
+ y1 = int(params["src"][i, 0, 1])
+ y2 = int(params["src"][i, 3, 1]) + 1
+ out[i] = input[i : i + 1, :, y1:y2, x1:x2]
+ return out
+ raise NotImplementedError(f"Not supported type: {self.flags['cropping_mode']}.")
+
+ def inverse_transform(
+ self,
+ input: torch.Tensor,
+ transform: Optional[torch.Tensor] = None,
+ size: Optional[Tuple[int, int]] = None,
+ **kwargs,
+ ) -> torch.Tensor:
+ if self.flags["cropping_mode"] != "resample":
+ raise NotImplementedError(
+ f"`inverse` is only applicable for resample cropping mode. Got {self.flags['cropping_mode']}."
+ )
+ if size is None:
+ size = self.size
+ mode = self.flags["resample"].name.lower() if "mode" not in kwargs else kwargs["mode"]
+ align_corners = self.flags["align_corners"] if "align_corners" not in kwargs else kwargs["align_corners"]
+ padding_mode = "zeros" if "padding_mode" not in kwargs else kwargs["padding_mode"]
+ transform = cast(torch.Tensor, transform)
+ return crop_by_transform_mat(input, transform[:, :2, :], size, mode, padding_mode, align_corners)
diff --git a/kornia/augmentation/_2d/geometric/crop.py b/kornia/augmentation/_2d/geometric/crop.py
new file mode 100644
index 000000000..4e94bf419
--- /dev/null
+++ b/kornia/augmentation/_2d/geometric/crop.py
@@ -0,0 +1,261 @@
+from typing import Dict, List, Optional, Tuple, Union, cast
+
+import torch
+from torch.nn.functional import pad
+
+from kornia.augmentation import random_generator as rg
+from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
+from kornia.augmentation.base import TensorWithTransformMat
+from kornia.augmentation.utils import _transform_input
+from kornia.constants import Resample
+from kornia.geometry.transform import crop_by_transform_mat, get_perspective_transform
+
+
+class RandomCrop(GeometricAugmentationBase2D):
+ r"""Crop random patches of a tensor image on a given size.
+
+ .. image:: _static/img/RandomCrop.png
+
+ Args:
+ p: probability of applying the transformation for the whole batch.
+ size: Desired output size (out_h, out_w) of the crop.
+ Must be Tuple[int, int], then out_h = size[0], out_w = size[1].
+ padding: Optional padding on each border
+ of the image. Default is None, i.e no padding. If a sequence of length
+ 4 is provided, it is used to pad left, top, right, bottom borders
+ respectively. If a sequence of length 2 is provided, it is used to
+ pad left/right, top/bottom borders, respectively.
+ pad_if_needed: It will pad the image if smaller than the
+ desired size to avoid raising an exception. Since cropping is done
+ after padding, the padding seems to be done at a random offset.
+ fill: Pixel fill value for constant fill. Default is 0. If a tuple of
+ length 3, it is used to fill R, G, B channels respectively.
+ This value is only used when the padding_mode is constant.
+ padding_mode: Type of padding. Should be: constant, edge, reflect or symmetric.
+ resample: the interpolation mode.
+ return_transform: if ``True`` return the matrix describing the transformation applied to each
+ input tensor. If ``False`` and the input is a tuple the applied transformation
+ won't be concatenated.
+ same_on_batch: apply the same transformation across the batch.
+ align_corners: interpolation flag.
+ keepdim: whether to keep the output shape the same as input (True) or broadcast it
+ to the batch form (False).
+ cropping_mode: The used algorithm to crop. ``slice`` will use advanced slicing to extract the tensor based
+ on the sampled indices. ``resample`` will use `warp_affine` using the affine transformation
+ to extract and resize at once. Use `slice` for efficiency, or `resample` for proper
+ differentiability.
+
+ Shape:
+ - Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
+ - Output: :math:`(B, C, out_h, out_w)`
+
+ Note:
+ Input tensor must be float and normalized into [0, 1] for the best differentiability support.
+ Additionally, this function accepts another transformation tensor (:math:`(B, 3, 3)`), then the
+ applied transformation will be merged int to the input transformation tensor and returned.
+
+ Examples:
+ >>> _ = torch.manual_seed(0)
+ >>> inputs = torch.arange(1*1*3*3.).view(1, 1, 3, 3)
+ >>> aug = RandomCrop((2, 2), p=1., cropping_mode="resample")
+ >>> out = aug(inputs)
+ >>> out
+ tensor([[[[3., 4.],
+ [6., 7.]]]])
+ >>> aug.inverse(out, padding_mode="border")
+ tensor([[[[3., 4., 4.],
+ [3., 4., 4.],
+ [6., 7., 7.]]]])
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.randn(1, 3, 32, 32)
+ >>> aug = RandomCrop((2, 2), p=1., cropping_mode="resample")
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
+ """
+
+ def __init__(
+ self,
+ size: Tuple[int, int],
+ padding: Optional[Union[int, Tuple[int, int], Tuple[int, int, int, int]]] = None,
+ pad_if_needed: Optional[bool] = False,
+ fill: int = 0,
+ padding_mode: str = "constant",
+ resample: Union[str, int, Resample] = Resample.BILINEAR.name,
+ return_transform: bool = False,
+ same_on_batch: bool = False,
+ align_corners: bool = True,
+ p: float = 1.0,
+ keepdim: bool = False,
+ cropping_mode: str = "slice",
+ ) -> None:
+ # Since PyTorch does not support ragged tensor. So cropping function happens batch-wisely.
+ super().__init__(
+ p=1.0, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=p, keepdim=keepdim
+ )
+ self._param_generator = cast(rg.CropGenerator, rg.CropGenerator(size))
+ self.flags = dict(
+ size=size,
+ padding=padding,
+ pad_if_needed=pad_if_needed,
+ fill=fill,
+ padding_mode=padding_mode,
+ resample=Resample.get(resample),
+ align_corners=align_corners,
+ cropping_mode=cropping_mode,
+ )
+
+ def compute_padding(self, shape: torch.Size) -> List[int]:
+ if len(shape) != 4:
+ raise AssertionError(f"Expected BCHW. Got {shape}.")
+ padding = [0, 0, 0, 0]
+ if self.flags["padding"] is not None:
+ if isinstance(self.flags["padding"], int):
+ padding = [self.flags["padding"]] * 4
+ elif isinstance(self.flags["padding"], tuple) and len(self.flags["padding"]) == 2:
+ padding = [
+ self.flags["padding"][1],
+ self.flags["padding"][1],
+ self.flags["padding"][0],
+ self.flags["padding"][0],
+ ]
+ elif isinstance(self.flags["padding"], tuple) and len(self.flags["padding"]) == 4:
+ padding = [
+ self.flags["padding"][3],
+ self.flags["padding"][2],
+ self.flags["padding"][1],
+ self.flags["padding"][0],
+ ]
+ else:
+ raise RuntimeError(f"Expect `padding` to be a scalar, or length 2/4 list. Got {self.flags['padding']}.")
+
+ if self.flags["pad_if_needed"] and shape[-2] < self.flags["size"][0]:
+ padding = [0, 0, (self.flags["size"][0] - shape[-2]), self.flags["size"][0] - shape[-2]]
+
+ if self.flags["pad_if_needed"] and shape[-1] < self.flags["size"][1]:
+ padding = [self.flags["size"][1] - shape[-1], self.flags["size"][1] - shape[-1], 0, 0]
+
+ return padding
+
+ def precrop_padding(self, input: torch.Tensor, padding: List[int] = None) -> torch.Tensor:
+ if padding is None:
+ padding = self.compute_padding(input.shape)
+
+ input = pad(input, padding, value=self.flags["fill"], mode=self.flags["padding_mode"])
+
+ return input
+
+ def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
+ transform: torch.Tensor = get_perspective_transform(params["src"].to(input), params["dst"].to(input))
+ return transform
+
+ def apply_transform(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ ) -> torch.Tensor:
+ if self.flags["cropping_mode"] == "resample": # uses bilinear interpolation to crop
+ transform = cast(torch.Tensor, transform)
+ return crop_by_transform_mat(
+ input,
+ transform,
+ self.flags["size"],
+ mode=self.flags["resample"].name.lower(),
+ padding_mode="zeros",
+ align_corners=self.flags["align_corners"],
+ )
+ if self.flags["cropping_mode"] == "slice": # uses advanced slicing to crop
+ B, C, _, _ = input.shape
+ out = torch.empty(B, C, *self.flags["size"], device=input.device, dtype=input.dtype)
+ for i in range(B):
+ x1 = int(params["src"][i, 0, 0])
+ x2 = int(params["src"][i, 1, 0]) + 1
+ y1 = int(params["src"][i, 0, 1])
+ y2 = int(params["src"][i, 3, 1]) + 1
+ out[i] = input[i : i + 1, :, y1:y2, x1:x2]
+ return out
+ raise NotImplementedError(f"Not supported type: {self.flags['cropping_mode']}.")
+
+ def inverse_transform(
+ self,
+ input: torch.Tensor,
+ transform: Optional[torch.Tensor] = None,
+ size: Optional[Tuple[int, int]] = None,
+ **kwargs,
+ ) -> torch.Tensor:
+ if self.flags["cropping_mode"] != "resample":
+ raise NotImplementedError(
+ f"`inverse` is only applicable for resample cropping mode. Got {self.flags['cropping_mode']}."
+ )
+ size = cast(Tuple[int, int], size)
+ mode = self.flags["resample"].name.lower() if "mode" not in kwargs else kwargs["mode"]
+ align_corners = self.flags["align_corners"] if "align_corners" not in kwargs else kwargs["align_corners"]
+ padding_mode = "zeros" if "padding_mode" not in kwargs else kwargs["padding_mode"]
+ transform = cast(torch.Tensor, transform)
+ return crop_by_transform_mat(input, transform[:, :2, :], size, mode, padding_mode, align_corners)
+
+ def inverse(
+ self,
+ input: TensorWithTransformMat,
+ params: Optional[Dict[str, torch.Tensor]] = None,
+ size: Optional[Tuple[int, int]] = None,
+ **kwargs,
+ ) -> torch.Tensor:
+ out = super().inverse(input, params, size, **kwargs)
+ if params is None:
+ params = self._params
+ if "padding_size" in params:
+ padding_size = params["padding_size"].unique(dim=0).cpu().squeeze().numpy().tolist()
+ padding_size = [-padding_size[0], -padding_size[1], -padding_size[2], -padding_size[3]]
+ else:
+ padding_size = [0, 0, 0, 0]
+ return self.precrop_padding(out, padding_size)
+
+ def forward_parameters_precrop(self, batch_shape) -> Dict[str, torch.Tensor]:
+ input_pad = self.compute_padding(batch_shape)
+ batch_shape_new = (
+ *batch_shape[:2],
+ batch_shape[2] + input_pad[2] + input_pad[3], # original height + top + bottom padding
+ batch_shape[3] + input_pad[0] + input_pad[1], # original width + left + right padding
+ )
+ padding_size = torch.tensor(tuple(input_pad), dtype=torch.long).expand(batch_shape[0], -1)
+ _params = super().forward_parameters(batch_shape_new)
+ _params.update({"padding_size": padding_size})
+ return _params
+
+ def forward(
+ self,
+ input: TensorWithTransformMat,
+ params: Optional[Dict[str, torch.Tensor]] = None,
+ return_transform: Optional[bool] = None,
+ ) -> TensorWithTransformMat:
+ padding_size = params.get("padding_size") if params else None
+ if padding_size is not None:
+ input_pad = padding_size.unique(dim=0).cpu().squeeze().numpy().tolist()
+ else:
+ input_pad = None
+
+ if isinstance(input, (tuple, list)):
+ input_temp = _transform_input(input[0])
+ input_pad = self.compute_padding(input[0].shape) if input_pad is None else input_pad
+ _input = (self.precrop_padding(input_temp, input_pad), input[1])
+ else:
+ input = cast(torch.Tensor, input) # TODO: weird that cast is not working under this context.
+ input_temp = _transform_input(input)
+ input_pad = self.compute_padding(input_temp.shape) if input_pad is None else input_pad
+ _input = self.precrop_padding(input_temp, input_pad) # type: ignore
+ out = super().forward(_input, params, return_transform)
+
+ # Update the actual input size for inverse
+ if "padding_size" not in self._params:
+ _padding_size = torch.tensor(tuple(input_pad), device=input_temp.device, dtype=torch.long).expand(
+ input_temp.size(0), -1
+ )
+ self._params.update({"padding_size": _padding_size})
+
+ if not self._params["batch_prob"].all():
+ # undo the pre-crop if nothing happened.
+ if isinstance(out, tuple) and isinstance(input, tuple):
+ return input[0], out[1]
+ if isinstance(out, tuple) and not isinstance(input, tuple):
+ return input, out[1]
+ return input
+ return out
diff --git a/kornia/augmentation/_2d/geometric/elastic_transform.py b/kornia/augmentation/_2d/geometric/elastic_transform.py
new file mode 100644
index 000000000..c88ab1230
--- /dev/null
+++ b/kornia/augmentation/_2d/geometric/elastic_transform.py
@@ -0,0 +1,94 @@
+from typing import Dict, Optional, Tuple
+
+import torch
+
+from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
+from kornia.geometry.transform import elastic_transform2d
+
+
+class RandomElasticTransform(GeometricAugmentationBase2D):
+ r"""Add random elastic transformation to a tensor image.
+
+ .. image:: _static/img/RandomElasticTransform.png
+
+ Args:
+ kernel_size: the size of the Gaussian kernel.
+ sigma: The standard deviation of the Gaussian in the y and x directions,
+ respectively. Larger sigma results in smaller pixel displacements.
+ alpha: The scaling factor that controls the intensity of the deformation
+ in the y and x directions, respectively.
+ align_corners: Interpolation flag used by `grid_sample`.
+ mode: Interpolation mode used by `grid_sample`. Either 'bilinear' or 'nearest'.
+ padding_mode: The padding used by ```grid_sample```. Either 'zeros', 'border' or 'refection'.
+
+ return_transform: if ``True`` return the matrix describing the transformation applied to each
+ input tensor. If ``False`` and the input is a tuple the applied transformation won't be concatenated.
+ same_on_batch: apply the same transformation across the batch.
+ p: probability of applying the transformation.
+
+ .. note::
+ This function internally uses :func:`kornia.geometry.transform.elastic_transform2d`.
+
+ Examples:
+ >>> img = torch.ones(1, 1, 2, 2)
+ >>> out = RandomElasticTransform()(img)
+ >>> out.shape
+ torch.Size([1, 1, 2, 2])
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.randn(1, 3, 32, 32)
+ >>> aug = RandomElasticTransform(p=1.)
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
+ """
+
+ def __init__(
+ self,
+ kernel_size: Tuple[int, int] = (63, 63),
+ sigma: Tuple[float, float] = (32.0, 32.0),
+ alpha: Tuple[float, float] = (1.0, 1.0),
+ align_corners: bool = False,
+ mode: str = "bilinear",
+ padding_mode: str = "zeros",
+ return_transform: bool = False,
+ same_on_batch: bool = False,
+ p: float = 0.5,
+ keepdim: bool = False,
+ ) -> None:
+ super().__init__(
+ p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim
+ )
+ self.flags = dict(
+ kernel_size=kernel_size,
+ sigma=sigma,
+ alpha=alpha,
+ align_corners=align_corners,
+ mode=mode,
+ padding_mode=padding_mode,
+ )
+
+ def generate_parameters(self, shape: torch.Size) -> Dict[str, torch.Tensor]:
+ B, _, H, W = shape
+ if self.same_on_batch:
+ noise = torch.rand(1, 2, H, W, device=self.device, dtype=self.dtype).repeat(B, 1, 1, 1)
+ else:
+ noise = torch.rand(B, 2, H, W, device=self.device, dtype=self.dtype)
+ return dict(noise=noise * 2 - 1)
+
+ # TODO: It is incorrect to return identity
+ def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
+ return self.identity_matrix(input)
+
+ def apply_transform(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ ) -> torch.Tensor:
+ return elastic_transform2d(
+ input,
+ params["noise"].to(input),
+ self.flags["kernel_size"],
+ self.flags["sigma"],
+ self.flags["alpha"],
+ self.flags["align_corners"],
+ self.flags["mode"],
+ self.flags["padding_mode"],
+ )
diff --git a/kornia/augmentation/_2d/geometric/fisheye.py b/kornia/augmentation/_2d/geometric/fisheye.py
new file mode 100644
index 000000000..9f30f1df6
--- /dev/null
+++ b/kornia/augmentation/_2d/geometric/fisheye.py
@@ -0,0 +1,94 @@
+from typing import Dict, Optional, cast
+
+import torch
+
+from kornia.augmentation import random_generator as rg
+from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
+from kornia.geometry.transform import remap
+from kornia.utils import create_meshgrid
+
+
+class RandomFisheye(GeometricAugmentationBase2D):
+ r"""Add random camera radial distortion.
+
+ .. image:: _static/img/RandomFisheye.png
+
+ Args:
+ center_x: Ranges to sample respect to x-coordinate center with shape (2,).
+ center_y: Ranges to sample respect to y-coordinate center with shape (2,).
+ gamma: Ranges to sample for the gamma values respect to optical center with shape (2,).
+ return_transform: if ``True`` return the matrix describing the transformation applied to each
+ input tensor. If ``False`` and the input is a tuple the applied transformation won't be concatenated.
+ same_on_batch: apply the same transformation across the batch.
+ p: probability of applying the transformation.
+ keepdim: whether to keep the output shape the same as input (True) or broadcast it
+ to the batch form (False).
+ Examples:
+ >>> img = torch.ones(1, 1, 2, 2)
+ >>> center_x = torch.tensor([-.3, .3])
+ >>> center_y = torch.tensor([-.3, .3])
+ >>> gamma = torch.tensor([.9, 1.])
+ >>> out = RandomFisheye(center_x, center_y, gamma)(img)
+ >>> out.shape
+ torch.Size([1, 1, 2, 2])
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.randn(1, 3, 32, 32)
+ >>> aug = RandomFisheye(center_x, center_y, gamma, p=1.)
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
+ """
+
+ def __init__(
+ self,
+ center_x: torch.Tensor,
+ center_y: torch.Tensor,
+ gamma: torch.Tensor,
+ return_transform: bool = False,
+ same_on_batch: bool = False,
+ p: float = 0.5,
+ keepdim: bool = False,
+ ) -> None:
+ super().__init__(
+ p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim
+ )
+ self._check_tensor(center_x)
+ self._check_tensor(center_y)
+ self._check_tensor(gamma)
+ self._param_generator = cast(
+ rg.PlainUniformGenerator,
+ rg.PlainUniformGenerator(
+ (center_x[:, None], "center_x", None, None),
+ (center_y[:, None], "center_y", None, None),
+ (gamma[:, None], "gamma", None, None),
+ ),
+ )
+
+ def _check_tensor(self, data: torch.Tensor) -> None:
+ if not isinstance(data, torch.Tensor):
+ raise TypeError(f"Invalid input type. Expected torch.Tensor - got: {type(data)}")
+
+ if len(data.shape) != 1 and data.shape[0] != 2:
+ raise ValueError(f"Tensor must be of shape (2,). Got: {data.shape}.")
+
+ # TODO: It is incorrect to return identity
+ def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
+ return self.identity_matrix(input)
+
+ def apply_transform(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ ) -> torch.Tensor:
+ # create the initial sampling fields
+ B, _, H, W = input.shape
+ grid = create_meshgrid(H, W, normalized_coordinates=True)
+ field_x = grid[..., 0].to(input) # 1xHxW
+ field_y = grid[..., 1].to(input) # 1xHxW
+ # vectorize the random parameters
+ center_x = params["center_x"].view(B, 1, 1).to(input)
+ center_y = params["center_y"].view(B, 1, 1).to(input)
+ gamma = params["gamma"].view(B, 1, 1).to(input)
+ # compute and apply the distances respect to the camera optical center
+ distance = ((center_x - field_x) ** 2 + (center_y - field_y) ** 2) ** 0.5
+ field_x = field_x + field_x * distance ** gamma # BxHxw
+ field_y = field_y + field_y * distance ** gamma # BxHxW
+ return remap(input, field_x, field_y, normalized_coordinates=True, align_corners=True)
diff --git a/kornia/augmentation/_2d/geometric/horizontal_flip.py b/kornia/augmentation/_2d/geometric/horizontal_flip.py
new file mode 100644
index 000000000..8a094dc55
--- /dev/null
+++ b/kornia/augmentation/_2d/geometric/horizontal_flip.py
@@ -0,0 +1,79 @@
+from typing import Dict, Optional, Tuple
+
+import torch
+
+from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
+from kornia.geometry.transform import hflip
+
+
+class RandomHorizontalFlip(GeometricAugmentationBase2D):
+ r"""Apply a random horizontal flip to a tensor image or a batch of tensor images with a given probability.
+
+ .. image:: _static/img/RandomHorizontalFlip.png
+
+ Input should be a tensor of shape (C, H, W) or a batch of tensors :math:`(B, C, H, W)`.
+ If Input is a tuple it is assumed that the first element contains the aforementioned tensors and the second,
+ the corresponding transformation matrix that has been applied to them. In this case the module
+ will Horizontally flip the tensors and concatenate the corresponding transformation matrix to the
+ previous one. This is especially useful when using this functionality as part of an ``nn.Sequential`` module.
+
+ Args:
+ p: probability of the image being flipped.
+ return_transform: if ``True`` return the matrix describing the transformation applied to each
+ input tensor. If ``False`` and the input is a tuple the applied transformation
+ won't be concatenated.
+ 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)`, Optional: :math:`(B, 3, 3)`
+ - Output: :math:`(B, C, H, W)`
+
+ .. note::
+ This function internally uses :func:`kornia.geometry.transform.hflip`.
+
+ Examples:
+ >>> input = torch.tensor([[[[0., 0., 0.],
+ ... [0., 0., 0.],
+ ... [0., 1., 1.]]]])
+ >>> seq = RandomHorizontalFlip(p=1.0, return_transform=True)
+ >>> seq(input)
+ (tensor([[[[0., 0., 0.],
+ [0., 0., 0.],
+ [1., 1., 0.]]]]), tensor([[[-1., 0., 2.],
+ [ 0., 1., 0.],
+ [ 0., 0., 1.]]]))
+ >>> seq.inverse(seq(input)).equal(input)
+ True
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.randn(1, 3, 32, 32)
+ >>> seq = RandomHorizontalFlip(p=1.0)
+ >>> (seq(input) == seq(input, params=seq._params)).all()
+ tensor(True)
+ """
+
+ def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
+ w: int = int(params["forward_input_shape"][-1])
+ flip_mat: torch.Tensor = torch.tensor(
+ [[-1, 0, w - 1], [0, 1, 0], [0, 0, 1]], device=input.device, dtype=input.dtype
+ )
+
+ return flip_mat.repeat(input.size(0), 1, 1)
+
+ def apply_transform(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ ) -> torch.Tensor:
+ return hflip(input)
+
+ def inverse_transform(
+ self,
+ input: torch.Tensor,
+ transform: Optional[torch.Tensor] = None,
+ size: Optional[Tuple[int, int]] = None,
+ **kwargs,
+ ) -> torch.Tensor:
+ return self.apply_transform(
+ input, params=self._params, transform=torch.as_tensor(transform, device=input.device, dtype=input.dtype)
+ )
diff --git a/kornia/augmentation/_2d/geometric/pad.py b/kornia/augmentation/_2d/geometric/pad.py
new file mode 100644
index 000000000..aae0c9ed5
--- /dev/null
+++ b/kornia/augmentation/_2d/geometric/pad.py
@@ -0,0 +1,83 @@
+from typing import Dict, Optional, Tuple, Union, cast
+
+import torch
+
+from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
+
+
+class PadTo(GeometricAugmentationBase2D):
+ r"""Pad the given sample to a specific size.
+
+ Args:
+ size: a tuple of ints in the format (height, width) that give the spatial
+ dimensions to pad inputs to.
+ pad_mode: the type of padding to perform on the image (valid values
+ are those accepted by torch.nn.functional.pad)
+ pad_value: fill value for 'constant' padding applied to the image
+ p: probability of the image being flipped.
+ return_transform: if ``True`` return the matrix describing the transformation applied to each
+ input tensor. If ``False`` and the input is a tuple the applied transformation
+ won't be concatenated.
+ 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)`, Optional: :math:`(B, 3, 3)`
+ - Output: :math:`(B, C, H, W)`
+
+ .. note::
+ This function internally uses :func:`torch.nn.functional.pad`.
+
+ Examples:
+ >>> img = torch.tensor([[[[0., 0., 0.],
+ ... [0., 0., 0.],
+ ... [0., 0., 0.]]]])
+ >>> pad = PadTo((4, 5), pad_value=1.)
+ >>> out = pad(img)
+ >>> out
+ tensor([[[[0., 0., 0., 1., 1.],
+ [0., 0., 0., 1., 1.],
+ [0., 0., 0., 1., 1.],
+ [1., 1., 1., 1., 1.]]]])
+ >>> pad.inverse(out)
+ tensor([[[[0., 0., 0.],
+ [0., 0., 0.],
+ [0., 0., 0.]]]])
+ """
+
+ def __init__(
+ self,
+ size: Tuple[int, int],
+ pad_mode: str = "constant",
+ pad_value: Union[int, float] = 0,
+ return_transform: bool = False,
+ keepdim: bool = False,
+ ) -> None:
+ super().__init__(p=1.0, return_transform=return_transform, same_on_batch=True, p_batch=1.0, keepdim=keepdim)
+ self.flags = dict(size=size, pad_mode=pad_mode, pad_value=pad_value)
+
+ # TODO: It is incorrect to return identity
+ # TODO: Having a resampled version with ``warp_affine``
+ def compute_transformation(self, image: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
+ return self.identity_matrix(image)
+
+ def apply_transform(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ ) -> torch.Tensor:
+ _, _, height, width = input.shape
+ height_pad: int = self.flags["size"][0] - height
+ width_pad: int = self.flags["size"][1] - width
+ return torch.nn.functional.pad(
+ input, [0, width_pad, 0, height_pad], mode=self.flags["pad_mode"], value=self.flags["pad_value"]
+ )
+
+ def inverse_transform(
+ self,
+ input: torch.Tensor,
+ transform: Optional[torch.Tensor] = None,
+ size: Optional[Tuple[int, int]] = None,
+ **kwargs
+ ) -> torch.Tensor:
+ size = cast(Tuple[int, int], size)
+ return input[..., : size[0], : size[1]]
diff --git a/kornia/augmentation/_2d/geometric/perspective.py b/kornia/augmentation/_2d/geometric/perspective.py
new file mode 100644
index 000000000..d2be34092
--- /dev/null
+++ b/kornia/augmentation/_2d/geometric/perspective.py
@@ -0,0 +1,96 @@
+from typing import Any, Dict, Optional, Tuple, Union, cast
+
+import torch
+
+from kornia.augmentation import random_generator as rg
+from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
+from kornia.constants import Resample
+from kornia.geometry.transform import get_perspective_transform, warp_perspective
+
+
+class RandomPerspective(GeometricAugmentationBase2D):
+ r"""Apply a random perspective transformation to an image tensor with a given probability.
+
+ .. image:: _static/img/RandomPerspective.png
+
+ Args:
+ p: probability of the image being perspectively transformed.
+ distortion_scale: the degree of distortion, ranged from 0 to 1.
+ resample: the interpolation method to use.
+ return_transform: if ``True`` return the matrix describing the transformation
+ applied to each.
+ same_on_batch: apply the same transformation across the batch. Default: False.
+ align_corners: interpolation flag.
+ 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)`, Optional: :math:`(B, 3, 3)`
+ - Output: :math:`(B, C, H, W)`
+
+ .. note::
+ This function internally uses :func:`kornia.geometry.transform.warp_pespective`.
+
+ Examples:
+ >>> rng = torch.manual_seed(0)
+ >>> inputs= torch.tensor([[[[1., 0., 0.],
+ ... [0., 1., 0.],
+ ... [0., 0., 1.]]]])
+ >>> aug = RandomPerspective(0.5, p=0.5)
+ >>> out = aug(inputs)
+ >>> out
+ tensor([[[[0.0000, 0.2289, 0.0000],
+ [0.0000, 0.4800, 0.0000],
+ [0.0000, 0.0000, 0.0000]]]])
+ >>> aug.inverse(out)
+ tensor([[[[0.0500, 0.0961, 0.0000],
+ [0.2011, 0.3144, 0.0000],
+ [0.0031, 0.0130, 0.0053]]]])
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.randn(1, 3, 32, 32)
+ >>> aug = RandomPerspective(0.5, p=1.)
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
+ """
+
+ def __init__(
+ self,
+ distortion_scale: Union[torch.Tensor, float] = 0.5,
+ resample: Union[str, int, Resample] = Resample.BILINEAR.name,
+ return_transform: bool = False,
+ same_on_batch: bool = False,
+ align_corners: bool = False,
+ p: float = 0.5,
+ keepdim: bool = False,
+ ) -> None:
+ super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
+ self._param_generator = cast(rg.PerspectiveGenerator, rg.PerspectiveGenerator(distortion_scale))
+ self.flags: Dict[str, Any] = dict(align_corners=align_corners, resample=Resample.get(resample))
+
+ def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
+ return get_perspective_transform(params["start_points"].to(input), params["end_points"].to(input))
+
+ def apply_transform(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ ) -> torch.Tensor:
+ _, _, height, width = input.shape
+ transform = cast(torch.Tensor, transform)
+ return warp_perspective(
+ input,
+ transform,
+ (height, width),
+ mode=self.flags["resample"].name.lower(),
+ align_corners=self.flags["align_corners"],
+ )
+
+ def inverse_transform(
+ self,
+ input: torch.Tensor,
+ transform: Optional[torch.Tensor] = None,
+ size: Optional[Tuple[int, int]] = None,
+ **kwargs,
+ ) -> torch.Tensor:
+ return self.apply_transform(
+ input, params=self._params, transform=torch.as_tensor(transform, device=input.device, dtype=input.dtype)
+ )
diff --git a/kornia/augmentation/_2d/geometric/resized_crop.py b/kornia/augmentation/_2d/geometric/resized_crop.py
new file mode 100644
index 000000000..93a9be703
--- /dev/null
+++ b/kornia/augmentation/_2d/geometric/resized_crop.py
@@ -0,0 +1,139 @@
+from typing import Dict, Optional, Tuple, Union, cast
+
+import torch
+
+from kornia.augmentation import random_generator as rg
+from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
+from kornia.constants import Resample
+from kornia.geometry.transform import crop_by_transform_mat, get_perspective_transform, resize
+
+
+class RandomResizedCrop(GeometricAugmentationBase2D):
+ r"""Crop random patches in an image tensor and resizes to a given size.
+
+ .. image:: _static/img/RandomResizedCrop.png
+
+ Args:
+ size: Desired output size (out_h, out_w) of each edge.
+ Must be Tuple[int, int], then out_h = size[0], out_w = size[1].
+ scale: range of size of the origin size cropped.
+ ratio: range of aspect ratio of the origin aspect ratio cropped.
+ resample: the interpolation mode.
+ return_transform: if ``True`` return the matrix describing the transformation applied to each
+ input tensor. If ``False`` and the input is a tuple the applied transformation
+ won't be concatenated.
+ same_on_batch: apply the same transformation across the batch.
+ align_corners: interpolation flag.
+ keepdim: whether to keep the output shape the same as input (True) or broadcast it
+ to the batch form (False).
+ cropping_mode: The used algorithm to crop. ``slice`` will use advanced slicing to extract the tensor based
+ on the sampled indices. ``resample`` will use `warp_affine` using the affine transformation
+ to extract and resize at once. Use `slice` for efficiency, or `resample` for proper
+ differentiability.
+
+ Shape:
+ - Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
+ - Output: :math:`(B, C, out_h, out_w)`
+
+ Note:
+ Input tensor must be float and normalized into [0, 1] for the best differentiability support.
+ Additionally, this function accepts another transformation tensor (:math:`(B, 3, 3)`), then the
+ applied transformation will be merged int to the input transformation tensor and returned.
+
+ Example:
+ >>> rng = torch.manual_seed(0)
+ >>> inputs = torch.tensor([[[0., 1., 2.],
+ ... [3., 4., 5.],
+ ... [6., 7., 8.]]])
+ >>> aug = RandomResizedCrop(size=(3, 3), scale=(3., 3.), ratio=(2., 2.), p=1., cropping_mode="resample")
+ >>> out = aug(inputs)
+ >>> out
+ tensor([[[[1.0000, 1.5000, 2.0000],
+ [4.0000, 4.5000, 5.0000],
+ [7.0000, 7.5000, 8.0000]]]])
+ >>> aug.inverse(out, padding_mode="border")
+ tensor([[[[1., 1., 2.],
+ [4., 4., 5.],
+ [7., 7., 8.]]]])
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.randn(1, 3, 32, 32)
+ >>> aug = RandomResizedCrop(size=(3, 3), scale=(3., 3.), ratio=(2., 2.), p=1., cropping_mode="resample")
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
+ """
+
+ def __init__(
+ self,
+ size: Tuple[int, int],
+ scale: Union[torch.Tensor, Tuple[float, float]] = (0.08, 1.0),
+ ratio: Union[torch.Tensor, Tuple[float, float]] = (3.0 / 4.0, 4.0 / 3.0),
+ resample: Union[str, int, Resample] = Resample.BILINEAR.name,
+ return_transform: bool = False,
+ same_on_batch: bool = False,
+ align_corners: bool = True,
+ p: float = 1.0,
+ keepdim: bool = False,
+ cropping_mode: str = "slice",
+ ) -> None:
+ # Since PyTorch does not support ragged tensor. So cropping function happens all the time.
+ super().__init__(
+ p=1.0, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=p, keepdim=keepdim
+ )
+ self._param_generator = cast(rg.ResizedCropGenerator, rg.ResizedCropGenerator(size, scale, ratio))
+ self.flags = dict(
+ size=size, resample=Resample.get(resample), align_corners=align_corners, cropping_mode=cropping_mode
+ )
+
+ def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
+ transform: torch.Tensor = get_perspective_transform(params["src"].to(input), params["dst"].to(input))
+ transform = transform.expand(input.shape[0], -1, -1)
+ return transform
+
+ def apply_transform(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ ) -> torch.Tensor:
+ if self.flags["cropping_mode"] == "resample": # uses bilinear interpolation to crop
+ transform = cast(torch.Tensor, transform)
+ return crop_by_transform_mat(
+ input,
+ transform,
+ self.flags["size"],
+ mode=self.flags["resample"].name.lower(),
+ padding_mode="zeros",
+ align_corners=self.flags["align_corners"],
+ )
+ if self.flags["cropping_mode"] == "slice": # uses advanced slicing to crop
+ B, C, _, _ = input.shape
+ out = torch.empty(B, C, *self.flags["size"], device=input.device, dtype=input.dtype)
+ for i in range(B):
+ x1 = int(params["src"][i, 0, 0])
+ x2 = int(params["src"][i, 1, 0]) + 1
+ y1 = int(params["src"][i, 0, 1])
+ y2 = int(params["src"][i, 3, 1]) + 1
+ out[i] = resize(
+ input[i : i + 1, :, y1:y2, x1:x2],
+ self.flags["size"],
+ interpolation=(self.flags["resample"].name).lower(),
+ align_corners=self.flags["align_corners"],
+ )
+ return out
+ raise NotImplementedError(f"Not supported type: {self.flags['cropping_mode']}.")
+
+ def inverse_transform(
+ self,
+ input: torch.Tensor,
+ transform: Optional[torch.Tensor] = None,
+ size: Optional[Tuple[int, int]] = None,
+ **kwargs,
+ ) -> torch.Tensor:
+ if self.flags["cropping_mode"] != "resample":
+ raise NotImplementedError(
+ f"`inverse` is only applicable for resample cropping mode. Got {self.flags['cropping_mode']}."
+ )
+ size = cast(Tuple[int, int], size)
+ mode = self.flags["resample"].name.lower() if "mode" not in kwargs else kwargs["mode"]
+ align_corners = self.flags["align_corners"] if "align_corners" not in kwargs else kwargs["align_corners"]
+ padding_mode = "zeros" if "padding_mode" not in kwargs else kwargs["padding_mode"]
+ transform = cast(torch.Tensor, transform)
+ return crop_by_transform_mat(input, transform[:, :2, :], size, mode, padding_mode, align_corners)
diff --git a/kornia/augmentation/_2d/geometric/rotation.py b/kornia/augmentation/_2d/geometric/rotation.py
new file mode 100644
index 000000000..e65b9deb2
--- /dev/null
+++ b/kornia/augmentation/_2d/geometric/rotation.py
@@ -0,0 +1,116 @@
+from typing import Dict, List, Optional, Tuple, Union, cast
+
+import torch
+
+from kornia.augmentation import random_generator as rg
+from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
+from kornia.constants import Resample
+from kornia.geometry.transform import affine
+from kornia.geometry.transform.affwarp import _compute_rotation_matrix, _compute_tensor_center
+
+
+class RandomRotation(GeometricAugmentationBase2D):
+ r"""Apply a random rotation to a tensor image or a batch of tensor images given an amount of degrees.
+
+ .. image:: _static/img/RandomRotation.png
+
+ Args:
+ p: probability of applying the transformation.
+ degrees: range of degrees to select from. If degrees is a number the
+ range of degrees to select from will be (-degrees, +degrees).
+ resample: Default: the interpolation mode.
+ return_transform: if ``True`` return the matrix describing the transformation applied to each
+ input tensor. If ``False`` and the input is a tuple the applied transformation
+ won't be concatenated.
+ same_on_batch: apply the same transformation across the batch.
+ align_corners: interpolation flag.
+ 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)`, Optional: :math:`(B, 3, 3)`
+ - Output: :math:`(B, C, H, W)`
+
+ .. note::
+ This function internally uses :func:`kornia.geometry.transform.affine`.
+
+ Examples:
+ >>> rng = torch.manual_seed(0)
+ >>> input = torch.tensor([[1., 0., 0., 2.],
+ ... [0., 0., 0., 0.],
+ ... [0., 1., 2., 0.],
+ ... [0., 0., 1., 2.]])
+ >>> aug = RandomRotation(degrees=45.0, return_transform=True, p=1.)
+ >>> out = aug(input)
+ >>> out[0]
+ tensor([[[[0.9824, 0.0088, 0.0000, 1.9649],
+ [0.0000, 0.0029, 0.0000, 0.0176],
+ [0.0029, 1.0000, 1.9883, 0.0000],
+ [0.0000, 0.0088, 1.0117, 1.9649]]]])
+ >>> out[1]
+ tensor([[[ 1.0000, -0.0059, 0.0088],
+ [ 0.0059, 1.0000, -0.0088],
+ [ 0.0000, 0.0000, 1.0000]]])
+ >>> aug.inverse(out)
+ tensor([[[[9.6526e-01, 8.6824e-03, 1.7263e-02, 1.9305e+00],
+ [8.6398e-03, 2.9485e-03, 5.8971e-03, 1.7365e-02],
+ [2.9054e-03, 9.9416e-01, 1.9825e+00, 2.3134e-02],
+ [2.5777e-05, 1.1640e-02, 9.9992e-01, 1.9392e+00]]]])
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.randn(1, 3, 32, 32)
+ >>> aug = RandomRotation(degrees=45.0, p=1.)
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
+ """
+
+ # Note: Extra params, center=None, fill=0 in TorchVision
+
+ def __init__(
+ self,
+ degrees: Union[torch.Tensor, float, Tuple[float, float], List[float]],
+ resample: Union[str, int, Resample] = Resample.BILINEAR.name,
+ return_transform: bool = False,
+ same_on_batch: bool = False,
+ align_corners: bool = True,
+ p: float = 0.5,
+ keepdim: bool = False,
+ ) -> None:
+ super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
+ self._param_generator = cast(
+ rg.PlainUniformGenerator, rg.PlainUniformGenerator((degrees, "degrees", 0.0, (-360.0, 360.0)))
+ )
+ self.flags = dict(resample=Resample.get(resample), align_corners=align_corners)
+
+ def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
+ # TODO: Update to use `get_rotation_matrix2d`
+ angles: torch.Tensor = params["degrees"].to(input)
+
+ center: torch.Tensor = _compute_tensor_center(input)
+ rotation_mat: torch.Tensor = _compute_rotation_matrix(angles, center.expand(angles.shape[0], -1))
+
+ # rotation_mat is B x 2 x 3 and we need a B x 3 x 3 matrix
+ trans_mat: torch.Tensor = torch.eye(3, device=input.device, dtype=input.dtype).repeat(input.shape[0], 1, 1)
+ trans_mat[:, 0] = rotation_mat[:, 0]
+ trans_mat[:, 1] = rotation_mat[:, 1]
+
+ return trans_mat
+
+ def apply_transform(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ ) -> torch.Tensor:
+ transform = cast(torch.Tensor, transform)
+ return affine(
+ input, transform[..., :2, :3], self.flags["resample"].name.lower(), "zeros", self.flags["align_corners"]
+ )
+
+ def inverse_transform(
+ self,
+ input: torch.Tensor,
+ transform: Optional[torch.Tensor] = None,
+ size: Optional[Tuple[int, int]] = None,
+ **kwargs,
+ ) -> torch.Tensor:
+ return self.apply_transform(
+ input, params=self._params, transform=torch.as_tensor(transform, device=input.device, dtype=input.dtype)
+ )
diff --git a/kornia/augmentation/_2d/geometric/thin_plate_spline.py b/kornia/augmentation/_2d/geometric/thin_plate_spline.py
new file mode 100644
index 000000000..79d284429
--- /dev/null
+++ b/kornia/augmentation/_2d/geometric/thin_plate_spline.py
@@ -0,0 +1,72 @@
+from typing import Dict, Optional
+
+import torch
+
+from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
+from kornia.geometry.transform import get_tps_transform, warp_image_tps
+
+
+class RandomThinPlateSpline(GeometricAugmentationBase2D):
+ r"""Add random noise to the Thin Plate Spline algorithm.
+
+ .. image:: _static/img/RandomThinPlateSpline.png
+
+ Args:
+ scale: the scale factor to apply to the destination points.
+ align_corners: Interpolation flag used by ``grid_sample``.
+ mode: Interpolation mode used by `grid_sample`. Either 'bilinear' or 'nearest'.
+ return_transform: if ``True`` return the matrix describing the transformation applied to each
+ input tensor. If ``False`` and the input is a tuple the applied transformation won't be concatenated.
+ same_on_batch: apply the same transformation across the batch.
+ p: probability of applying the transformation.
+ keepdim: whether to keep the output shape the same as input (True) or broadcast it
+ to the batch form (False).
+ .. note::
+ This function internally uses :func:`kornia.geometry.transform.warp_image_tps`.
+
+ Examples:
+ >>> img = torch.ones(1, 1, 2, 2)
+ >>> out = RandomThinPlateSpline()(img)
+ >>> out.shape
+ torch.Size([1, 1, 2, 2])
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.randn(1, 3, 32, 32)
+ >>> aug = RandomThinPlateSpline(p=1.)
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
+ """
+
+ def __init__(
+ self,
+ scale: float = 0.2,
+ align_corners: bool = False,
+ return_transform: bool = False,
+ same_on_batch: bool = False,
+ p: float = 0.5,
+ keepdim: bool = False,
+ ) -> None:
+ super().__init__(
+ p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim
+ )
+ self.flags = dict(align_corners=align_corners)
+ self.dist = torch.distributions.Uniform(-scale, scale)
+
+ def generate_parameters(self, shape: torch.Size) -> Dict[str, torch.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]]]).repeat(B, 1, 1) # Bx5x2
+ dst = src + self.dist.rsample(src.shape)
+ return dict(src=src, dst=dst)
+
+ # TODO: It is incorrect to return identity
+ def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
+ return self.identity_matrix(input)
+
+ def apply_transform(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ ) -> torch.Tensor:
+ src = params["src"].to(input)
+ dst = params["dst"].to(input)
+ # NOTE: warp_image_tps need to use inverse parameters
+ kernel, affine = get_tps_transform(dst, src)
+ return warp_image_tps(input, src, kernel, affine, self.flags["align_corners"])
diff --git a/kornia/augmentation/_2d/geometric/vertical_flip.py b/kornia/augmentation/_2d/geometric/vertical_flip.py
new file mode 100644
index 000000000..bcf8068da
--- /dev/null
+++ b/kornia/augmentation/_2d/geometric/vertical_flip.py
@@ -0,0 +1,73 @@
+from typing import Dict, Optional, Tuple
+
+import torch
+
+from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
+from kornia.geometry.transform import vflip
+
+
+class RandomVerticalFlip(GeometricAugmentationBase2D):
+ r"""Apply a random vertical flip to a tensor image or a batch of tensor images with a given probability.
+
+ .. image:: _static/img/RandomVerticalFlip.png
+
+ Args:
+ p: probability of the image being flipped.
+ return_transform: if ``True`` return the matrix describing the transformation applied to each
+ input tensor. If ``False`` and the input is a tuple the applied transformation
+ won't be concatenated.
+ 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)`, Optional: :math:`(B, 3, 3)`
+ - Output: :math:`(B, C, H, W)`
+
+ .. note::
+ This function internally uses :func:`kornia.geometry.transform.vflip`.
+
+ Examples:
+ >>> input = torch.tensor([[[[0., 0., 0.],
+ ... [0., 0., 0.],
+ ... [0., 1., 1.]]]])
+ >>> seq = RandomVerticalFlip(p=1.0, return_transform=True)
+ >>> seq(input)
+ (tensor([[[[0., 1., 1.],
+ [0., 0., 0.],
+ [0., 0., 0.]]]]), tensor([[[ 1., 0., 0.],
+ [ 0., -1., 2.],
+ [ 0., 0., 1.]]]))
+ >>> seq.inverse(seq(input)).equal(input)
+ True
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.randn(1, 3, 32, 32)
+ >>> seq = RandomVerticalFlip(p=1.0)
+ >>> (seq(input) == seq(input, params=seq._params)).all()
+ tensor(True)
+ """
+
+ def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
+ h: int = int(params["forward_input_shape"][-2])
+ flip_mat: torch.Tensor = torch.tensor(
+ [[1, 0, 0], [0, -1, h - 1], [0, 0, 1]], device=input.device, dtype=input.dtype
+ )
+
+ return flip_mat.repeat(input.size(0), 1, 1)
+
+ def apply_transform(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ ) -> torch.Tensor:
+ return vflip(input)
+
+ def inverse_transform(
+ self,
+ input: torch.Tensor,
+ transform: Optional[torch.Tensor] = None,
+ size: Optional[Tuple[int, int]] = None,
+ **kwargs,
+ ) -> torch.Tensor:
+ return self.apply_transform(
+ input, params=self._params, transform=torch.as_tensor(transform, device=input.device, dtype=input.dtype)
+ )
diff --git a/kornia/augmentation/_2d/intensity/__init__.py b/kornia/augmentation/_2d/intensity/__init__.py
new file mode 100644
index 000000000..de44fc401
--- /dev/null
+++ b/kornia/augmentation/_2d/intensity/__init__.py
@@ -0,0 +1,15 @@
+from kornia.augmentation._2d.intensity.box_blur import RandomBoxBlur
+from kornia.augmentation._2d.intensity.channel_shuffle import RandomChannelShuffle
+from kornia.augmentation._2d.intensity.color_jitter import ColorJitter
+from kornia.augmentation._2d.intensity.denormalize import Denormalize
+from kornia.augmentation._2d.intensity.earasing import RandomErasing
+from kornia.augmentation._2d.intensity.equalize import RandomEqualize
+from kornia.augmentation._2d.intensity.gaussian_blur import RandomGaussianBlur
+from kornia.augmentation._2d.intensity.gaussian_noise import RandomGaussianNoise
+from kornia.augmentation._2d.intensity.grayscale import RandomGrayscale
+from kornia.augmentation._2d.intensity.invert import RandomInvert
+from kornia.augmentation._2d.intensity.motion_blur import RandomMotionBlur
+from kornia.augmentation._2d.intensity.normalize import Normalize
+from kornia.augmentation._2d.intensity.posterize import RandomPosterize
+from kornia.augmentation._2d.intensity.sharpness import RandomSharpness
+from kornia.augmentation._2d.intensity.solarize import RandomSolarize
diff --git a/kornia/augmentation/_2d/intensity/base.py b/kornia/augmentation/_2d/intensity/base.py
new file mode 100644
index 000000000..a75f8ab94
--- /dev/null
+++ b/kornia/augmentation/_2d/intensity/base.py
@@ -0,0 +1,27 @@
+from typing import Dict
+
+import torch
+
+from kornia.augmentation._2d.base import AugmentationBase2D
+
+
+class IntensityAugmentationBase2D(AugmentationBase2D):
+ r"""IntensityAugmentationBase2D base class for customized intensity augmentation implementations.
+
+ For any augmentation, the implementation of "generate_parameters" and "apply_transform" are required while the
+ "compute_transformation" is only required when passing "return_transform" as True.
+
+ Args:
+ p: probability for applying an augmentation. This param controls the augmentation probabilities
+ element-wise for a batch.
+ p_batch: probability for applying an augmentation to a batch. This param controls the augmentation
+ probabilities batch-wise.
+ return_transform: if ``True`` return the matrix describing the geometric transformation applied to each
+ input tensor. If ``False`` and the input is a tuple the applied transformation won't be concatenated.
+ 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``.
+ """
+
+ def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
+ return self.identity_matrix(input)
diff --git a/kornia/augmentation/_2d/intensity/box_blur.py b/kornia/augmentation/_2d/intensity/box_blur.py
new file mode 100644
index 000000000..5b9cac9c7
--- /dev/null
+++ b/kornia/augmentation/_2d/intensity/box_blur.py
@@ -0,0 +1,62 @@
+from typing import Dict, Optional, Tuple
+
+import torch
+
+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
+from kornia.filters import box_blur
+
+
+class RandomBoxBlur(IntensityAugmentationBase2D):
+ """Add random blur with a box filter to an image tensor.
+
+ .. image:: _static/img/RandomBoxBlur.png
+
+ Args:
+ kernel_size: the blurring kernel size.
+ border_type: the padding mode to be applied before convolving.
+ The expected modes are: ``constant``, ``reflect``, ``replicate`` or ``circular``.
+ normalized: if True, L1 norm of the kernel is set to 1.
+ return_transform: if ``True`` return the matrix describing the transformation applied to each
+ input tensor. If ``False`` and the input is a tuple the applied transformation won't be concatenated.
+ same_on_batch (bool): apply the same transformation across the batch.
+ p: probability of applying the transformation.
+ keepdim: whether to keep the output shape the same as input (True) or broadcast it
+ to the batch form (False).
+ .. note::
+ This function internally uses :func:`kornia.filters.box_blur`.
+
+ Examples:
+ >>> img = torch.ones(1, 1, 24, 24)
+ >>> out = RandomBoxBlur((7, 7))(img)
+ >>> out.shape
+ torch.Size([1, 1, 24, 24])
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.randn(1, 3, 32, 32)
+ >>> aug = RandomBoxBlur((7, 7), p=1.)
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
+ """
+
+ def __init__(
+ self,
+ kernel_size: Tuple[int, int] = (3, 3),
+ border_type: str = "reflect",
+ normalized: bool = True,
+ return_transform: bool = False,
+ same_on_batch: bool = False,
+ p: float = 0.5,
+ keepdim: bool = False,
+ ) -> None:
+ super().__init__(
+ p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim
+ )
+ self.flags = dict(kernel_size=kernel_size, border_type=border_type, normalized=normalized)
+
+ def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
+ return self.identity_matrix(input)
+
+ def apply_transform(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ ) -> torch.Tensor:
+ return box_blur(input, self.flags["kernel_size"], self.flags["border_type"], self.flags["normalized"])
diff --git a/kornia/augmentation/_2d/intensity/channel_shuffle.py b/kornia/augmentation/_2d/intensity/channel_shuffle.py
new file mode 100644
index 000000000..8d06093ee
--- /dev/null
+++ b/kornia/augmentation/_2d/intensity/channel_shuffle.py
@@ -0,0 +1,54 @@
+from typing import Dict, Optional
+
+import torch
+
+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
+
+
+class RandomChannelShuffle(IntensityAugmentationBase2D):
+ r"""Shuffle the channels of a batch of multi-dimensional images.
+
+ .. image:: _static/img/RandomChannelShuffle.png
+
+ Args:
+ return_transform: if ``True`` return the matrix describing the transformation applied to each
+ input tensor. If ``False`` and the input is a tuple the applied transformation won't be concatenated.
+ same_on_batch: apply the same transformation across the batch.
+ p: probability of applying the transformation.
+
+ Examples:
+ >>> rng = torch.manual_seed(0)
+ >>> img = torch.arange(1*2*2*2.).view(1,2,2,2)
+ >>> RandomChannelShuffle()(img)
+ tensor([[[[4., 5.],
+ [6., 7.]],
+ <BLANKLINE>
+ [[0., 1.],
+ [2., 3.]]]])
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.randn(1, 3, 32, 32)
+ >>> aug = RandomChannelShuffle(p=1.)
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
+ """
+
+ def __init__(
+ self, return_transform: bool = False, same_on_batch: bool = False, p: float = 0.5, keepdim: bool = False
+ ) -> None:
+ super().__init__(
+ p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim
+ )
+
+ def generate_parameters(self, shape: torch.Size) -> Dict[str, torch.Tensor]:
+ B, C, _, _ = shape
+ channels = torch.rand(B, C).argsort(dim=1)
+ return dict(channels=channels)
+
+ def apply_transform(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ ) -> torch.Tensor:
+ out = torch.empty_like(input)
+ for i in range(out.shape[0]):
+ out[i] = input[i, params["channels"][i]]
+ return out
diff --git a/kornia/augmentation/_2d/intensity/color_jitter.py b/kornia/augmentation/_2d/intensity/color_jitter.py
new file mode 100644
index 000000000..71570b57c
--- /dev/null
+++ b/kornia/augmentation/_2d/intensity/color_jitter.py
@@ -0,0 +1,97 @@
+from typing import Dict, List, Optional, Tuple, Union, cast
+
+import torch
+
+from kornia.augmentation import random_generator as rg
+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
+from kornia.constants import pi
+from kornia.enhance import adjust_brightness, adjust_contrast, adjust_hue, adjust_saturation
+
+
+class ColorJitter(IntensityAugmentationBase2D):
+ r"""Apply a random transformation to the brightness, contrast, saturation and hue of a tensor image.
+
+ .. image:: _static/img/ColorJitter.png
+
+ Args:
+ p: probability of applying the transformation.
+ brightness: The brightness factor to apply.
+ contrast: The contrast factor to apply.
+ saturation: The saturation factor to apply.
+ hue: The hue factor to apply.
+ return_transform: if ``True`` return the matrix describing the transformation applied to each
+ input tensor. If ``False`` and the input is a tuple the applied transformation
+ won't be concatenated.
+ 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)`, Optional: :math:`(B, 3, 3)`
+ - Output: :math:`(B, C, H, W)`
+
+ .. note::
+ This function internally uses :func:`kornia.enhance.adjust_brightness`,
+ :func:`kornia.enhance.adjust_contrast`. :func:`kornia.enhance.adjust_saturation`,
+ :func:`kornia.enhance.adjust_hue`.
+
+ Examples:
+ >>> rng = torch.manual_seed(0)
+ >>> inputs = torch.ones(1, 3, 3, 3)
+ >>> aug = ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.)
+ >>> aug(inputs)
+ tensor([[[[0.9993, 0.9993, 0.9993],
+ [0.9993, 0.9993, 0.9993],
+ [0.9993, 0.9993, 0.9993]],
+ <BLANKLINE>
+ [[0.9993, 0.9993, 0.9993],
+ [0.9993, 0.9993, 0.9993],
+ [0.9993, 0.9993, 0.9993]],
+ <BLANKLINE>
+ [[0.9993, 0.9993, 0.9993],
+ [0.9993, 0.9993, 0.9993],
+ [0.9993, 0.9993, 0.9993]]]])
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.randn(1, 3, 32, 32)
+ >>> aug = ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.)
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
+ """
+
+ def __init__(
+ self,
+ brightness: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.0,
+ contrast: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.0,
+ saturation: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.0,
+ hue: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.0,
+ return_transform: bool = False,
+ same_on_batch: bool = False,
+ p: float = 1.0,
+ keepdim: bool = False,
+ ) -> None:
+ super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
+ self.brightness = brightness
+ self.contrast = contrast
+ self.saturation = saturation
+ self.hue = hue
+ self._param_generator = cast(
+ rg.ColorJitterGenerator, rg.ColorJitterGenerator(brightness, contrast, saturation, hue)
+ )
+
+ def apply_transform(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ ) -> torch.Tensor:
+ transforms = [
+ lambda img: adjust_brightness(img, params["brightness_factor"] - 1),
+ lambda img: adjust_contrast(img, params["contrast_factor"]),
+ lambda img: adjust_saturation(img, params["saturation_factor"]),
+ lambda img: adjust_hue(img, params["hue_factor"] * 2 * pi),
+ ]
+
+ jittered = input
+ for idx in params["order"].tolist():
+ t = transforms[idx]
+ jittered = t(jittered)
+
+ return jittered
diff --git a/kornia/augmentation/_2d/intensity/denormalize.py b/kornia/augmentation/_2d/intensity/denormalize.py
new file mode 100644
index 000000000..2ffde8537
--- /dev/null
+++ b/kornia/augmentation/_2d/intensity/denormalize.py
@@ -0,0 +1,62 @@
+from typing import Dict, List, Optional, Tuple, Union
+
+import torch
+
+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
+from kornia.enhance import denormalize
+
+
+class Denormalize(IntensityAugmentationBase2D):
+ r"""Denormalize tensor images with mean and standard deviation.
+
+ .. math::
+ \text{input[channel] = (input[channel] * std[channel]) + mean[channel]}
+
+ Where `mean` is :math:`(M_1, ..., M_n)` and `std` :math:`(S_1, ..., S_n)` for `n` channels,
+
+ Args:
+ mean: Mean for each channel.
+ std: Standard deviations for each channel.
+
+ Return:
+ Denormalised tensor with same size as input :math:`(*, C, H, W)`.
+
+ .. note::
+ This function internally uses :func:`kornia.enhance.denormalize`.
+
+ Examples:
+
+ >>> norm = Denormalize(mean=torch.zeros(1, 4), std=torch.ones(1, 4))
+ >>> x = torch.rand(1, 4, 3, 3)
+ >>> out = norm(x)
+ >>> out.shape
+ torch.Size([1, 4, 3, 3])
+ """
+
+ def __init__(
+ self,
+ mean: Union[torch.Tensor, Tuple[float], List[float], float],
+ std: Union[torch.Tensor, Tuple[float], List[float], float],
+ return_transform: bool = False,
+ p: float = 1.0,
+ keepdim: bool = False,
+ ) -> None:
+ super().__init__(p=p, return_transform=return_transform, same_on_batch=True, keepdim=keepdim)
+ if isinstance(mean, float):
+ mean = torch.tensor([mean])
+
+ if isinstance(std, float):
+ std = torch.tensor([std])
+
+ if isinstance(mean, (tuple, list)):
+ mean = torch.tensor(mean)
+
+ if isinstance(std, (tuple, list)):
+ std = torch.tensor(std)
+
+ self.flags = dict(mean=mean, std=std)
+
+ def apply_transform(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ ) -> torch.Tensor:
+ return denormalize(input, self.flags["mean"], self.flags["std"])
diff --git a/kornia/augmentation/_2d/intensity/earasing.py b/kornia/augmentation/_2d/intensity/earasing.py
new file mode 100644
index 000000000..acb6586c2
--- /dev/null
+++ b/kornia/augmentation/_2d/intensity/earasing.py
@@ -0,0 +1,82 @@
+from typing import Dict, Optional, Tuple, Union, cast
+
+import torch
+
+from kornia.augmentation import random_generator as rg
+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
+from kornia.geometry.bbox import bbox_generator, bbox_to_mask
+
+
+class RandomErasing(IntensityAugmentationBase2D):
+ r"""Erase a random rectangle of a tensor image according to a probability p value.
+
+ .. image:: _static/img/RandomErasing.png
+
+ The operator removes image parts and fills them with zero values at a selected rectangle
+ for each of the images in the batch.
+
+ The rectangle will have an area equal to the original image area multiplied by a value uniformly
+ sampled between the range [scale[0], scale[1]) and an aspect ratio sampled
+ between [ratio[0], ratio[1])
+
+ Args:
+ p: probability that the random erasing operation will be performed.
+ scale: range of proportion of erased area against input image.
+ ratio: range of aspect ratio of erased area.
+ 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)`, Optional: :math:`(B, 3, 3)`
+ - Output: :math:`(B, C, H, W)`
+
+ Note:
+ Input tensor must be float and normalized into [0, 1] for the best differentiability support.
+ Additionally, this function accepts another transformation tensor (:math:`(B, 3, 3)`), then the
+ applied transformation will be merged int to the input transformation tensor and returned.
+
+ Examples:
+ >>> rng = torch.manual_seed(0)
+ >>> inputs = torch.ones(1, 1, 3, 3)
+ >>> aug = RandomErasing((.4, .8), (.3, 1/.3), p=0.5)
+ >>> aug(inputs)
+ tensor([[[[1., 0., 0.],
+ [1., 0., 0.],
+ [1., 0., 0.]]]])
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.randn(1, 3, 32, 32)
+ >>> aug = RandomErasing((.4, .8), (.3, 1/.3), p=1.)
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
+ """
+
+ # Note: Extra params, inplace=False in Torchvision.
+ def __init__(
+ self,
+ scale: Union[torch.Tensor, Tuple[float, float]] = (0.02, 0.33),
+ ratio: Union[torch.Tensor, Tuple[float, float]] = (0.3, 3.3),
+ value: float = 0.0,
+ return_transform: bool = False,
+ same_on_batch: bool = False,
+ p: float = 0.5,
+ keepdim: bool = False,
+ ) -> None:
+ super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
+ self.scale = scale
+ self.ratio = ratio
+ self.value: float = float(value)
+ self._param_generator = cast(rg.RectangleEraseGenerator, rg.RectangleEraseGenerator(scale, ratio, float(value)))
+
+ def apply_transform(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ ) -> torch.Tensor:
+ _, c, h, w = input.size()
+ values = params["values"].unsqueeze(-1).unsqueeze(-1).unsqueeze(-1).repeat(1, *input.shape[1:]).to(input)
+
+ bboxes = bbox_generator(params["xs"], params["ys"], params["widths"], params["heights"])
+ mask = bbox_to_mask(bboxes, w, h) # Returns B, H, W
+ mask = mask.unsqueeze(1).repeat(1, c, 1, 1).to(input) # Transform to B, c, H, W
+ transformed = torch.where(mask == 1.0, values, input)
+ return transformed
diff --git a/kornia/augmentation/_2d/intensity/equalize.py b/kornia/augmentation/_2d/intensity/equalize.py
new file mode 100644
index 000000000..618576c78
--- /dev/null
+++ b/kornia/augmentation/_2d/intensity/equalize.py
@@ -0,0 +1,56 @@
+from typing import Dict, Optional
+
+import torch
+
+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
+from kornia.enhance import equalize
+
+
+class RandomEqualize(IntensityAugmentationBase2D):
+ r"""Equalize given tensor image or a batch of tensor images randomly.
+
+ .. image:: _static/img/RandomEqualize.png
+
+ Args:
+ p: Probability to equalize an image.
+ same_on_batch: apply the same transformation across the batch.
+ return_transform: if ``True`` return the matrix describing the transformation applied to each
+ input tensor. If ``False`` and the input is a tuple the applied transformation
+ won't be concatenated.
+ 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)`, Optional: :math:`(B, 3, 3)`
+ - Output: :math:`(B, C, H, W)`
+
+ .. note::
+ This function internally uses :func:`kornia.enhance.equalize`.
+
+ Examples:
+ >>> rng = torch.manual_seed(0)
+ >>> input = torch.rand(1, 1, 5, 5)
+ >>> equalize = RandomEqualize(p=1.)
+ >>> equalize(input)
+ tensor([[[[0.4963, 0.7682, 0.0885, 0.1320, 0.3074],
+ [0.6341, 0.4901, 0.8964, 0.4556, 0.6323],
+ [0.3489, 0.4017, 0.0223, 0.1689, 0.2939],
+ [0.5185, 0.6977, 0.8000, 0.1610, 0.2823],
+ [0.6816, 0.9152, 0.3971, 0.8742, 0.4194]]]])
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.rand(1, 3, 32, 32)
+ >>> aug = RandomEqualize(p=1.)
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
+ """
+
+ def __init__(
+ self, same_on_batch: bool = False, return_transform: bool = False, p: float = 0.5, keepdim: bool = False
+ ) -> None:
+ super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
+
+ def apply_transform(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ ) -> torch.Tensor:
+ return equalize(input)
diff --git a/kornia/augmentation/_2d/intensity/gaussian_blur.py b/kornia/augmentation/_2d/intensity/gaussian_blur.py
new file mode 100644
index 000000000..d642e1aff
--- /dev/null
+++ b/kornia/augmentation/_2d/intensity/gaussian_blur.py
@@ -0,0 +1,72 @@
+from typing import Dict, Optional, Tuple
+
+import torch
+
+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
+from kornia.constants import BorderType
+from kornia.filters import gaussian_blur2d
+
+
+class RandomGaussianBlur(IntensityAugmentationBase2D):
+ r"""Apply gaussian blur given tensor image or a batch of tensor images randomly.
+
+ .. image:: _static/img/RandomGaussianBlur.png
+
+ Args:
+ kernel_size: the size of the kernel.
+ sigma: the standard deviation of the kernel.
+ border_type: the padding mode to be applied before convolving.
+ The expected modes are: ``constant``, ``reflect``, ``replicate`` or ``circular``.
+ return_transform: if ``True`` return the matrix describing the transformation applied to each
+ input tensor. If ``False`` and the input is a tuple the applied transformation won't be concatenated.
+ same_on_batch: apply the same transformation across the batch.
+ p: probability of applying the transformation.
+ keepdim: whether to keep the output shape the same as input (True) or broadcast it
+ to the batch form (False).
+
+ Shape:
+ - Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
+ - Output: :math:`(B, C, H, W)`
+
+ .. note::
+ This function internally uses :func:`kornia.filters.gaussian_blur2d`.
+
+ Examples:
+ >>> rng = torch.manual_seed(0)
+ >>> input = torch.rand(1, 1, 5, 5)
+ >>> blur = RandomGaussianBlur((3, 3), (0.1, 2.0), p=1.)
+ >>> blur(input)
+ tensor([[[[0.6699, 0.4645, 0.3193, 0.1741, 0.1955],
+ [0.5422, 0.6657, 0.6261, 0.6527, 0.5195],
+ [0.3826, 0.2638, 0.1902, 0.1620, 0.2141],
+ [0.6329, 0.6732, 0.5634, 0.4037, 0.2049],
+ [0.8307, 0.6753, 0.7147, 0.5768, 0.7097]]]])
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.randn(1, 3, 32, 32)
+ >>> aug = RandomGaussianBlur((3, 3), (0.1, 2.0), p=1.)
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
+ """
+
+ def __init__(
+ self,
+ kernel_size: Tuple[int, int],
+ sigma: Tuple[float, float],
+ border_type: str = "reflect",
+ return_transform: bool = False,
+ same_on_batch: bool = False,
+ p: float = 0.5,
+ keepdim: bool = False,
+ ) -> None:
+ super().__init__(
+ p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim
+ )
+ self.flags = dict(kernel_size=kernel_size, sigma=sigma, border_type=BorderType.get(border_type))
+
+ def apply_transform(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ ) -> torch.Tensor:
+ return gaussian_blur2d(
+ input, self.flags["kernel_size"], self.flags["sigma"], self.flags["border_type"].name.lower()
+ )
diff --git a/kornia/augmentation/_2d/intensity/gaussian_noise.py b/kornia/augmentation/_2d/intensity/gaussian_noise.py
new file mode 100644
index 000000000..b155882ad
--- /dev/null
+++ b/kornia/augmentation/_2d/intensity/gaussian_noise.py
@@ -0,0 +1,57 @@
+from typing import Dict, Optional
+
+import torch
+
+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
+
+
+class RandomGaussianNoise(IntensityAugmentationBase2D):
+ r"""Add gaussian noise to a batch of multi-dimensional images.
+
+ .. image:: _static/img/RandomGaussianNoise.png
+
+ Args:
+ mean: The mean of the gaussian distribution.
+ std: The standard deviation of the gaussian distribution.
+ return_transform: if ``True`` return the matrix describing the transformation applied to each
+ input tensor. If ``False`` and the input is a tuple the applied transformation won't be concatenated.
+ same_on_batch: apply the same transformation across the batch.
+ p: probability of applying the transformation.
+ keepdim: whether to keep the output shape the same as input (True) or broadcast it
+ to the batch form (False).
+ Examples:
+ >>> rng = torch.manual_seed(0)
+ >>> img = torch.ones(1, 1, 2, 2)
+ >>> RandomGaussianNoise(mean=0., std=1., p=1.)(img)
+ tensor([[[[ 2.5410, 0.7066],
+ [-1.1788, 1.5684]]]])
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.randn(1, 3, 32, 32)
+ >>> aug = RandomGaussianNoise(mean=0., std=1., p=1.)
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
+ """
+
+ def __init__(
+ self,
+ mean: float = 0.0,
+ std: float = 1.0,
+ return_transform: bool = False,
+ same_on_batch: bool = False,
+ p: float = 0.5,
+ keepdim: bool = False,
+ ) -> None:
+ super().__init__(
+ p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim
+ )
+ self.flags = dict(mean=mean, std=std)
+
+ def generate_parameters(self, shape: torch.Size) -> Dict[str, torch.Tensor]:
+ noise = torch.randn(shape)
+ return dict(noise=noise)
+
+ def apply_transform(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ ) -> torch.Tensor:
+ return input + params["noise"].to(input.device) * self.flags["std"] + self.flags["mean"]
diff --git a/kornia/augmentation/_2d/intensity/grayscale.py b/kornia/augmentation/_2d/intensity/grayscale.py
new file mode 100644
index 000000000..a289a7b68
--- /dev/null
+++ b/kornia/augmentation/_2d/intensity/grayscale.py
@@ -0,0 +1,65 @@
+from typing import Dict, Optional
+
+import torch
+
+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
+from kornia.color import rgb_to_grayscale
+
+
+class RandomGrayscale(IntensityAugmentationBase2D):
+ r"""Apply random transformation to Grayscale according to a probability p value.
+
+ .. image:: _static/img/RandomGrayscale.png
+
+ Args:
+ p: probability of the image to be transformed to grayscale.
+ return_transform: if ``True`` return the matrix describing the transformation applied to each
+ input tensor. If ``False`` and the input is a tuple the applied transformation
+ won't be concatenated.
+ 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)`, Optional: :math:`(B, 3, 3)`
+ - Output: :math:`(B, C, H, W)`
+
+ .. note::
+ This function internally uses :func:`kornia.color.rgb_to_grayscale`.
+
+ Examples:
+ >>> rng = torch.manual_seed(0)
+ >>> inputs = torch.randn((1, 3, 3, 3))
+ >>> aug = RandomGrayscale(p=1.0)
+ >>> aug(inputs)
+ tensor([[[[-1.1344, -0.1330, 0.1517],
+ [-0.0791, 0.6711, -0.1413],
+ [-0.1717, -0.9023, 0.0819]],
+ <BLANKLINE>
+ [[-1.1344, -0.1330, 0.1517],
+ [-0.0791, 0.6711, -0.1413],
+ [-0.1717, -0.9023, 0.0819]],
+ <BLANKLINE>
+ [[-1.1344, -0.1330, 0.1517],
+ [-0.0791, 0.6711, -0.1413],
+ [-0.1717, -0.9023, 0.0819]]]])
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.randn(1, 3, 32, 32)
+ >>> aug = RandomGrayscale(p=1.0)
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
+ """
+
+ def __init__(
+ self, return_transform: bool = False, same_on_batch: bool = False, p: float = 0.1, keepdim: bool = False
+ ) -> None:
+ super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
+
+ def apply_transform(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ ) -> torch.Tensor:
+ # Make sure it returns (*, 3, H, W)
+ grayscale = torch.ones_like(input)
+ grayscale[:] = rgb_to_grayscale(input)
+ return grayscale
diff --git a/kornia/augmentation/_2d/intensity/invert.py b/kornia/augmentation/_2d/intensity/invert.py
new file mode 100644
index 000000000..25c40721e
--- /dev/null
+++ b/kornia/augmentation/_2d/intensity/invert.py
@@ -0,0 +1,60 @@
+from typing import Dict, Optional, Union
+
+import torch
+
+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
+from kornia.enhance import invert
+
+
+class RandomInvert(IntensityAugmentationBase2D):
+ r"""Invert the tensor images values randomly.
+
+ .. image:: _static/img/RandomInvert.png
+
+ Args:
+ max_val: The expected maximum value in the input tensor. The shape has to
+ according to the input tensor shape, or at least has to work with broadcasting.
+ return_transform: if ``True`` return the matrix describing the transformation applied to each
+ input tensor. If ``False`` and the input is a tuple the applied transformation won't be concatenated.
+ same_on_batch: apply the same transformation across the batch.
+ p: probability of applying the transformation.
+ keepdim: whether to keep the output shape the same as input (True) or broadcast it
+ to the batch form (False).
+ .. note::
+ This function internally uses :func:`kornia.enhance.invert`.
+
+ Examples:
+ >>> rng = torch.manual_seed(0)
+ >>> img = torch.rand(1, 1, 5, 5)
+ >>> inv = RandomInvert()
+ >>> inv(img)
+ tensor([[[[0.4963, 0.7682, 0.0885, 0.1320, 0.3074],
+ [0.6341, 0.4901, 0.8964, 0.4556, 0.6323],
+ [0.3489, 0.4017, 0.0223, 0.1689, 0.2939],
+ [0.5185, 0.6977, 0.8000, 0.1610, 0.2823],
+ [0.6816, 0.9152, 0.3971, 0.8742, 0.4194]]]])
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.randn(1, 3, 32, 32)
+ >>> aug = RandomInvert(p=1.)
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
+ """
+
+ def __init__(
+ self,
+ max_val: Union[float, torch.Tensor] = torch.tensor(1.0),
+ return_transform: bool = False,
+ same_on_batch: bool = False,
+ p: float = 0.5,
+ keepdim: bool = False,
+ ) -> None:
+ super().__init__(
+ p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim
+ )
+ self.flags = dict(max_val=max_val)
+
+ def apply_transform(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ ) -> torch.Tensor:
+ return invert(input, torch.as_tensor(self.flags["max_val"], device=input.device, dtype=input.dtype))
diff --git a/kornia/augmentation/_2d/intensity/motion_blur.py b/kornia/augmentation/_2d/intensity/motion_blur.py
new file mode 100644
index 000000000..b8bd77ed4
--- /dev/null
+++ b/kornia/augmentation/_2d/intensity/motion_blur.py
@@ -0,0 +1,96 @@
+from typing import Dict, Optional, Tuple, Union, cast
+
+import torch
+
+from kornia.augmentation import random_generator as rg
+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
+from kornia.constants import BorderType, Resample
+from kornia.filters import motion_blur
+
+
+class RandomMotionBlur(IntensityAugmentationBase2D):
+ r"""Perform motion blur on 2D images (4D tensor).
+
+ .. image:: _static/img/RandomMotionBlur.png
+
+ Args:
+ p: probability of applying the transformation.
+ kernel_size: motion kernel size (odd and positive).
+ If int, the kernel will have a fixed size.
+ If Tuple[int, int], it will randomly generate the value from the range batch-wisely.
+ angle: angle of the motion blur in degrees (anti-clockwise rotation).
+ If float, it will generate the value from (-angle, angle).
+ direction: forward/backward direction of the motion blur.
+ Lower values towards -1.0 will point the motion blur towards the back (with angle provided via angle),
+ while higher values towards 1.0 will point the motion blur forward. A value of 0.0 leads to a
+ uniformly (but still angled) motion blur.
+ If float, it will generate the value from (-direction, direction).
+ If Tuple[int, int], it will randomly generate the value from the range.
+ border_type: the padding mode to be applied before convolving.
+ CONSTANT = 0, REFLECT = 1, REPLICATE = 2, CIRCULAR = 3.
+ resample: the interpolation mode.
+ 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)`, Optional: :math:`(B, 3, 3)`
+ - Output: :math:`(B, C, H, W)`
+
+ Note:
+ Input tensor must be float and normalized into [0, 1] for the best differentiability support.
+ Additionally, this function accepts another transformation tensor (:math:`(B, 3, 3)`), then the
+ applied transformation will be merged int to the input transformation tensor and returned.
+
+ Please set ``resample`` to ``'bilinear'`` if more meaningful gradients wanted.
+
+ .. note::
+ This function internally uses :func:`kornia.filters.motion_blur`.
+
+ Examples:
+ >>> rng = torch.manual_seed(0)
+ >>> input = torch.ones(1, 1, 5, 5)
+ >>> motion_blur = RandomMotionBlur(3, 35., 0.5, p=1.)
+ >>> motion_blur(input)
+ tensor([[[[0.5773, 1.0000, 1.0000, 1.0000, 0.7561],
+ [0.5773, 1.0000, 1.0000, 1.0000, 0.7561],
+ [0.5773, 1.0000, 1.0000, 1.0000, 0.7561],
+ [0.5773, 1.0000, 1.0000, 1.0000, 0.7561],
+ [0.5773, 1.0000, 1.0000, 1.0000, 0.7561]]]])
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.randn(1, 3, 32, 32)
+ >>> aug = RandomMotionBlur(3, 35., 0.5, p=1.)
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
+ """
+
+ def __init__(
+ self,
+ kernel_size: Union[int, Tuple[int, int]],
+ angle: Union[torch.Tensor, float, Tuple[float, float]],
+ direction: Union[torch.Tensor, float, Tuple[float, float]],
+ border_type: Union[int, str, BorderType] = BorderType.CONSTANT.name,
+ resample: Union[str, int, Resample] = Resample.NEAREST.name,
+ return_transform: bool = False,
+ same_on_batch: bool = False,
+ p: float = 0.5,
+ keepdim: bool = False,
+ ) -> None:
+ super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
+ self._param_generator = rg.MotionBlurGenerator(kernel_size, angle, direction)
+ self.flags = dict(border_type=BorderType.get(border_type), resample=Resample.get(resample))
+
+ def apply_transform(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ ) -> torch.Tensor:
+ kernel_size: int = cast(int, params["ksize_factor"].unique().item())
+ angle = params["angle_factor"]
+ direction = params["direction_factor"]
+ return motion_blur(
+ input,
+ kernel_size,
+ angle,
+ direction,
+ border_type=self.flags["border_type"].name.lower(),
+ mode=self.flags["resample"].name.lower(),
+ )
diff --git a/kornia/augmentation/_2d/intensity/normalize.py b/kornia/augmentation/_2d/intensity/normalize.py
new file mode 100644
index 000000000..a4f393109
--- /dev/null
+++ b/kornia/augmentation/_2d/intensity/normalize.py
@@ -0,0 +1,68 @@
+from typing import Dict, List, Optional, Tuple, Union
+
+import torch
+
+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
+from kornia.enhance import normalize
+
+
+class Normalize(IntensityAugmentationBase2D):
+ r"""Normalize tensor images with mean and standard deviation.
+
+ .. math::
+ \text{input[channel] = (input[channel] - mean[channel]) / std[channel]}
+
+ Where `mean` is :math:`(M_1, ..., M_n)` and `std` :math:`(S_1, ..., S_n)` for `n` channels,
+
+ Args:
+ mean: Mean for each channel.
+ std: Standard deviations for each channel.
+ return_transform: if ``True`` return the matrix describing the transformation applied to each
+ input tensor. If ``False`` and the input is a tuple the applied transformation
+ won't be concatenated.
+ 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).
+
+ Return:
+ Normalised tensor with same size as input :math:`(*, C, H, W)`.
+
+ .. note::
+ This function internally uses :func:`kornia.enhance.normalize`.
+
+ Examples:
+
+ >>> norm = Normalize(mean=torch.zeros(4), std=torch.ones(4))
+ >>> x = torch.rand(1, 4, 3, 3)
+ >>> out = norm(x)
+ >>> out.shape
+ torch.Size([1, 4, 3, 3])
+ """
+
+ def __init__(
+ self,
+ mean: Union[torch.Tensor, Tuple[float], List[float], float],
+ std: Union[torch.Tensor, Tuple[float], List[float], float],
+ return_transform: bool = False,
+ p: float = 1.0,
+ keepdim: bool = False,
+ ) -> None:
+ super().__init__(p=p, return_transform=return_transform, same_on_batch=True, keepdim=keepdim)
+ if isinstance(mean, float):
+ mean = torch.tensor([mean])
+
+ if isinstance(std, float):
+ std = torch.tensor([std])
+
+ if isinstance(mean, (tuple, list)):
+ mean = torch.tensor(mean)
+
+ if isinstance(std, (tuple, list)):
+ std = torch.tensor(std)
+
+ self.flags = dict(mean=mean, std=std)
+
+ def apply_transform(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ ) -> torch.Tensor:
+ return normalize(input, self.flags["mean"], self.flags["std"])
diff --git a/kornia/augmentation/_2d/intensity/posterize.py b/kornia/augmentation/_2d/intensity/posterize.py
new file mode 100644
index 000000000..459295c4a
--- /dev/null
+++ b/kornia/augmentation/_2d/intensity/posterize.py
@@ -0,0 +1,65 @@
+from typing import Dict, Optional, Tuple, Union, cast
+
+import torch
+
+from kornia.augmentation import random_generator as rg
+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
+from kornia.enhance import posterize
+
+
+class RandomPosterize(IntensityAugmentationBase2D):
+ r"""Posterize given tensor image or a batch of tensor images randomly.
+
+ .. image:: _static/img/RandomPosterize.png
+
+ 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).
+ same_on_batch: apply the same transformation across the batch.
+ return_transform: if ``True`` return the matrix describing the transformation applied to each
+ input tensor. If ``False`` and the input is a tuple the applied transformation won't be concatenated.
+ 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)`, Optional: :math:`(B, 3, 3)`
+ - Output: :math:`(B, C, H, W)`
+
+ .. note::
+ This function internally uses :func:`kornia.enhance.posterize`.
+
+ Examples:
+ >>> rng = torch.manual_seed(0)
+ >>> input = torch.rand(1, 1, 5, 5)
+ >>> 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]]]])
+
+ 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(input) == aug(input, params=aug._params)).all()
+ tensor(True)
+ """
+
+ def __init__(
+ self,
+ bits: Union[int, Tuple[int, int], torch.Tensor] = 3,
+ same_on_batch: bool = False,
+ return_transform: bool = False,
+ p: float = 0.5,
+ keepdim: bool = False,
+ ) -> None:
+ super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
+ self._param_generator = cast(rg.PosterizeGenerator, rg.PosterizeGenerator(bits))
+
+ def apply_transform(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ ) -> torch.Tensor:
+ return posterize(input, params["bits_factor"])
diff --git a/kornia/augmentation/_2d/intensity/sharpness.py b/kornia/augmentation/_2d/intensity/sharpness.py
new file mode 100644
index 000000000..80b10e159
--- /dev/null
+++ b/kornia/augmentation/_2d/intensity/sharpness.py
@@ -0,0 +1,66 @@
+from typing import Dict, Optional, Tuple, Union, cast
+
+import torch
+
+from kornia.augmentation import random_generator as rg
+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
+from kornia.enhance import sharpness
+
+
+class RandomSharpness(IntensityAugmentationBase2D):
+ r"""Sharpen given tensor image or a batch of tensor images randomly.
+
+ .. image:: _static/img/RandomSharpness.png
+
+ Args:
+ p: probability of applying the transformation.
+ sharpness: factor of sharpness strength. Must be above 0.
+ same_on_batch: apply the same transformation across the batch.
+ return_transform: if ``True`` return the matrix describing the transformation applied to each
+ input tensor. If ``False`` and the input is a tuple the applied transformation won't be concatenated.
+ 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)`, Optional: :math:`(B, 3, 3)`
+ - Output: :math:`(B, C, H, W)`
+
+ .. note::
+ This function internally uses :func:`kornia.enhance.sharpness`.
+
+ Examples:
+ >>> rng = torch.manual_seed(0)
+ >>> input = torch.rand(1, 1, 5, 5)
+ >>> sharpness = RandomSharpness(1., p=1.)
+ >>> sharpness(input)
+ tensor([[[[0.4963, 0.7682, 0.0885, 0.1320, 0.3074],
+ [0.6341, 0.4810, 0.7367, 0.4177, 0.6323],
+ [0.3489, 0.4428, 0.1562, 0.2443, 0.2939],
+ [0.5185, 0.6462, 0.7050, 0.2288, 0.2823],
+ [0.6816, 0.9152, 0.3971, 0.8742, 0.4194]]]])
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.randn(1, 3, 32, 32)
+ >>> aug = RandomSharpness(1., p=1.)
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
+ """
+
+ def __init__(
+ self,
+ sharpness: Union[torch.Tensor, float, Tuple[float, float], torch.Tensor] = 0.5,
+ same_on_batch: bool = False,
+ return_transform: bool = False,
+ p: float = 0.5,
+ keepdim: bool = False,
+ ) -> None:
+ super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
+ self._param_generator = cast(
+ rg.PlainUniformGenerator, rg.PlainUniformGenerator((sharpness, "sharpness", 0.0, (0, float("inf"))))
+ )
+
+ def apply_transform(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ ) -> torch.Tensor:
+ factor = params["sharpness"]
+ return sharpness(input, factor)
diff --git a/kornia/augmentation/_2d/intensity/solarize.py b/kornia/augmentation/_2d/intensity/solarize.py
new file mode 100644
index 000000000..bda2673a8
--- /dev/null
+++ b/kornia/augmentation/_2d/intensity/solarize.py
@@ -0,0 +1,80 @@
+from typing import Dict, List, Optional, Tuple, Union, cast
+
+import torch
+
+from kornia.augmentation import random_generator as rg
+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
+from kornia.enhance import solarize
+
+
+class RandomSolarize(IntensityAugmentationBase2D):
+ r"""Solarize given tensor image or a batch of tensor images randomly.
+
+ .. image:: _static/img/RandomSolarize.png
+
+ Args:
+ p: probability of applying the transformation.
+ thresholds:
+ If float x, threshold will be generated from (0.5 - x, 0.5 + x).
+ If tuple (x, y), threshold will be generated from (x, y).
+ additions:
+ If float x, addition will be generated from (-x, x).
+ If tuple (x, y), addition will be generated from (x, y).
+ same_on_batch: apply the same transformation across the batch.
+ return_transform: if ``True`` return the matrix describing the transformation applied to each
+ input tensor. If ``False`` and the input is a tuple the applied transformation won't be concatenated.
+ 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)`, Optional: :math:`(B, 3, 3)`
+ - Output: :math:`(B, C, H, W)`
+
+ .. note::
+ This function internally uses :func:`kornia.enhance.solarize`.
+
+ Examples:
+ >>> rng = torch.manual_seed(0)
+ >>> input = torch.rand(1, 1, 5, 5)
+ >>> solarize = RandomSolarize(0.1, 0.1, p=1.)
+ >>> solarize(input)
+ tensor([[[[0.4132, 0.1412, 0.1790, 0.2226, 0.3980],
+ [0.2754, 0.4194, 0.0130, 0.4538, 0.2771],
+ [0.4394, 0.4923, 0.1129, 0.2594, 0.3844],
+ [0.3909, 0.2118, 0.1094, 0.2516, 0.3728],
+ [0.2278, 0.0000, 0.4876, 0.0353, 0.5100]]]])
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.randn(1, 3, 32, 32)
+ >>> aug = RandomSolarize(0.1, 0.1, p=1.)
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
+ """
+
+ def __init__(
+ self,
+ thresholds: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.1,
+ additions: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.1,
+ same_on_batch: bool = False,
+ return_transform: bool = False,
+ p: float = 0.5,
+ keepdim: bool = False,
+ ) -> None:
+ super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
+ self._param_generator = cast(
+ rg.PlainUniformGenerator,
+ rg.PlainUniformGenerator(
+ (thresholds, "thresholds", 0.5, (0.0, 1.0)), (additions, "additions", 0.0, (-0.5, 0.5))
+ ),
+ )
+
+ def apply_transform(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ ) -> torch.Tensor:
+ thresholds = params["thresholds"]
+ additions: Optional[torch.Tensor]
+ if "additions" in params:
+ additions = params["additions"]
+ else:
+ additions = None
+ return solarize(input, thresholds, additions)
diff --git a/kornia/augmentation/_2d/mix/__init__.py b/kornia/augmentation/_2d/mix/__init__.py
new file mode 100644
index 000000000..20a67c3af
--- /dev/null
+++ b/kornia/augmentation/_2d/mix/__init__.py
@@ -0,0 +1,2 @@
+from kornia.augmentation._2d.mix.cutmix import RandomCutMix
+from kornia.augmentation._2d.mix.mixup import RandomMixUp
diff --git a/kornia/augmentation/_2d/mix/base.py b/kornia/augmentation/_2d/mix/base.py
new file mode 100644
index 000000000..215b3d99c
--- /dev/null
+++ b/kornia/augmentation/_2d/mix/base.py
@@ -0,0 +1,106 @@
+from typing import Dict, Optional, Tuple
+
+import torch
+
+from kornia.augmentation.base import TensorWithTransformMat, _BasicAugmentationBase
+from kornia.augmentation.utils import _transform_input, _transform_output_shape, _validate_input_dtype
+
+
+class MixAugmentationBase(_BasicAugmentationBase):
+ r"""MixAugmentationBase base class for customized mix augmentation implementations.
+
+ For any augmentation, the implementation of "generate_parameters" and "apply_transform" are required.
+ "apply_transform" will need to handle the probabilities internally.
+
+ Args:
+ p: probability for applying an augmentation. This param controls if to apply the augmentation for the batch.
+ p_batch: probability for applying an augmentation to a batch. This param controls the augmentation
+ probabilities batch-wise.
+ 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``.
+ """
+
+ def __init__(self, p: float, p_batch: float, same_on_batch: bool = False, keepdim: bool = False) -> None:
+ super().__init__(p, p_batch=p_batch, same_on_batch=same_on_batch, keepdim=keepdim)
+
+ def __check_batching__(self, input: TensorWithTransformMat):
+ if isinstance(input, tuple):
+ inp, mat = input
+ if len(inp.shape) == 4:
+ if len(mat.shape) != 3:
+ raise AssertionError('Input tensor is in batch mode ' 'but transformation matrix is not')
+ if mat.shape[0] != inp.shape[0]:
+ raise AssertionError(
+ f"In batch dimension, input has {inp.shape[0]} but transformation matrix has {mat.shape[0]}"
+ )
+ elif len(inp.shape) in (2, 3):
+ if len(mat.shape) != 2:
+ raise AssertionError("Input tensor is in non-batch mode but transformation matrix is not")
+ else:
+ raise ValueError(f'Unrecognized output shape. Expected 2, 3, or 4, got {len(inp.shape)}')
+
+ def __unpack_input__( # type: ignore
+ self, input: TensorWithTransformMat
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
+ if isinstance(input, tuple):
+ in_tensor = input[0]
+ in_transformation = input[1]
+ return in_tensor, in_transformation
+ in_tensor = input
+ return in_tensor, None
+
+ def transform_tensor(self, input: torch.Tensor) -> torch.Tensor:
+ """Convert any incoming (H, W), (C, H, W) and (B, C, H, W) into (B, C, H, W)."""
+ _validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])
+ return _transform_input(input)
+
+ def apply_transform( # type: ignore
+ self, input: torch.Tensor, label: torch.Tensor, params: Dict[str, torch.Tensor]
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
+ raise NotImplementedError
+
+ def apply_func( # type: ignore
+ self, in_tensor: torch.Tensor, label: torch.Tensor, params: Dict[str, torch.Tensor]
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
+ to_apply = params['batch_prob']
+
+ # if no augmentation needed
+ if torch.sum(to_apply) == 0:
+ output = in_tensor
+ # if all data needs to be augmented
+ elif torch.sum(to_apply) == len(to_apply):
+ output, label = self.apply_transform(in_tensor, label, params)
+ else:
+ raise ValueError(
+ "Mix augmentations must be performed batch-wisely. Element-wise augmentation is not supported."
+ )
+
+ return output, label
+
+ def forward( # type: ignore
+ self,
+ input: TensorWithTransformMat,
+ label: Optional[torch.Tensor] = None,
+ params: Optional[Dict[str, torch.Tensor]] = None,
+ ) -> Tuple[TensorWithTransformMat, torch.Tensor]:
+ in_tensor, in_trans = self.__unpack_input__(input)
+ ori_shape = in_tensor.shape
+ in_tensor = self.transform_tensor(in_tensor)
+ # If label is not provided, it would output the indices instead.
+ if label is None:
+ if isinstance(input, (tuple, list)):
+ device = input[0].device
+ else:
+ device = input.device
+ label = torch.arange(0, in_tensor.size(0), device=device, dtype=torch.long)
+ if params is None:
+ batch_shape = in_tensor.shape
+ params = self.forward_parameters(batch_shape)
+ self._params = params
+
+ output, lab = self.apply_func(in_tensor, label, self._params)
+ output = _transform_output_shape(output, ori_shape) if self.keepdim else output # type: ignore
+ if in_trans is not None:
+ return (output, in_trans), lab
+ return output, lab
diff --git a/kornia/augmentation/mix_augmentation.py b/kornia/augmentation/_2d/mix/cutmix.py
similarity index 57%
rename from kornia/augmentation/mix_augmentation.py
rename to kornia/augmentation/_2d/mix/cutmix.py
index 53da1054b..7d6d9092c 100644
--- a/kornia/augmentation/mix_augmentation.py
+++ b/kornia/augmentation/_2d/mix/cutmix.py
@@ -1,112 +1,13 @@
import warnings
-from typing import cast, Dict, Optional, Tuple, Union
+from typing import Dict, Optional, Tuple, Union, cast
import torch
+from kornia.augmentation import random_generator as rg
+from kornia.augmentation._2d.mix.base import MixAugmentationBase
+from kornia.augmentation.utils import _shape_validation
from kornia.geometry.bbox import bbox_to_mask, infer_bbox_shape
-from . import random_generator as rg
-from .base import MixAugmentationBase
-from .utils import _shape_validation
-
-
-class RandomMixUp(MixAugmentationBase):
- r"""Apply MixUp augmentation to a batch of tensor images.
-
- .. image:: _static/img/RandomMixUp.png
-
- Implementation for `mixup: BEYOND EMPIRICAL RISK MINIMIZATION` :cite:`zhang2018mixup`.
-
- The function returns (inputs, labels), in which the inputs is the tensor that contains the mixup images
- while the labels is a :math:`(B, 3)` tensor that contains (label_batch, label_permuted_batch, lambda) for
- each image.
-
- The implementation is on top of the following repository:
- `https://github.com/hongyi-zhang/mixup/blob/master/cifar/utils.py
- <https://github.com/hongyi-zhang/mixup/blob/master/cifar/utils.py>`_.
-
- The loss and accuracy are computed as:
-
- .. code-block:: python
-
- def loss_mixup(y, logits):
- criterion = F.cross_entropy
- loss_a = criterion(logits, y[:, 0].long(), reduction='none')
- loss_b = criterion(logits, y[:, 1].long(), reduction='none')
- return ((1 - y[:, 2]) * loss_a + y[:, 2] * loss_b).mean()
-
- .. code-block:: python
-
- def acc_mixup(y, logits):
- pred = torch.argmax(logits, dim=1).to(y.device)
- return (1 - y[:, 2]) * pred.eq(y[:, 0]).float() + y[:, 2] * pred.eq(y[:, 1]).float()
-
- Args:
- p (float): probability for applying an augmentation to a batch. This param controls the augmentation
- probabilities batch-wisely.
- lambda_val (float or torch.Tensor, optional): min-max value of mixup strength. Default is 0-1.
- same_on_batch (bool): apply the same transformation across the batch.
- This flag will not maintain permutation order. Default: False.
- keepdim (bool): whether to keep the output shape the same as input (True) or broadcast it
- to the batch form (False). Default: False
-
- Inputs:
- - Input image tensors, shape of :math:`(B, C, H, W)`.
- - Label: raw labels, shape of :math:`(B)`.
-
- Returns:
- Tuple[torch.Tensor, torch.Tensor]:
- - Adjusted image, shape of :math:`(B, C, H, W)`.
- - Raw labels, permuted labels and lambdas for each mix, shape of :math:`(B, 3)`.
-
- Note:
- This implementation would randomly mixup images in a batch. Ideally, the larger batch size would be preferred.
-
- Examples:
- >>> rng = torch.manual_seed(1)
- >>> input = torch.rand(2, 1, 3, 3)
- >>> label = torch.tensor([0, 1])
- >>> mixup = RandomMixUp()
- >>> mixup(input, label)
- (tensor([[[[0.7576, 0.2793, 0.4031],
- [0.7347, 0.0293, 0.7999],
- [0.3971, 0.7544, 0.5695]]],
- <BLANKLINE>
- <BLANKLINE>
- [[[0.4388, 0.6387, 0.5247],
- [0.6826, 0.3051, 0.4635],
- [0.4550, 0.5725, 0.4980]]]]), tensor([[0.0000, 0.0000, 0.1980],
- [1.0000, 1.0000, 0.4162]]))
- """
-
- def __init__(
- self,
- lambda_val: Optional[Union[torch.Tensor, Tuple[float, float]]] = None,
- same_on_batch: bool = False,
- p: float = 1.0,
- keepdim: bool = False,
- ) -> None:
- super().__init__(p=1.0, p_batch=p, same_on_batch=same_on_batch, keepdim=keepdim)
- self._param_generator = cast(rg.MixupGenerator, rg.MixupGenerator(lambda_val, p=p))
-
- def apply_transform( # type: ignore
- self, input: torch.Tensor, label: torch.Tensor, params: Dict[str, torch.Tensor]
- ) -> Tuple[torch.Tensor, torch.Tensor]:
- input_permute = input.index_select(dim=0, index=params["mixup_pairs"].to(input.device))
- labels_permute = label.index_select(dim=0, index=params["mixup_pairs"].to(label.device))
-
- lam = params["mixup_lambdas"].view(-1, 1, 1, 1).expand_as(input).to(label.device)
- inputs = input * (1 - lam) + input_permute * lam
- out_labels = torch.stack(
- [
- label.to(input.dtype),
- labels_permute.to(input.dtype),
- params["mixup_lambdas"].to(label.device, input.dtype),
- ],
- dim=-1,
- ).to(label.device)
- return inputs, out_labels
-
class RandomCutMix(MixAugmentationBase):
r"""Apply CutMix augmentation to a batch of tensor images.
@@ -203,7 +104,7 @@ class RandomCutMix(MixAugmentationBase):
warnings.warn(
"height and width can be inferred automatically now. "
"The height and width arguments will be removed finally.",
- category=DeprecationWarning
+ category=DeprecationWarning,
)
self._param_generator = cast(rg.CutmixGenerator, rg.CutmixGenerator(cut_size, beta, num_mix, p=p))
diff --git a/kornia/augmentation/_2d/mix/mixup.py b/kornia/augmentation/_2d/mix/mixup.py
new file mode 100644
index 000000000..4f68fc865
--- /dev/null
+++ b/kornia/augmentation/_2d/mix/mixup.py
@@ -0,0 +1,104 @@
+from typing import Dict, Optional, Tuple, Union, cast
+
+import torch
+
+from kornia.augmentation import random_generator as rg
+from kornia.augmentation._2d.mix.base import MixAugmentationBase
+
+
+class RandomMixUp(MixAugmentationBase):
+ r"""Apply MixUp augmentation to a batch of tensor images.
+
+ .. image:: _static/img/RandomMixUp.png
+
+ Implementation for `mixup: BEYOND EMPIRICAL RISK MINIMIZATION` :cite:`zhang2018mixup`.
+
+ The function returns (inputs, labels), in which the inputs is the tensor that contains the mixup images
+ while the labels is a :math:`(B, 3)` tensor that contains (label_batch, label_permuted_batch, lambda) for
+ each image.
+
+ The implementation is on top of the following repository:
+ `https://github.com/hongyi-zhang/mixup/blob/master/cifar/utils.py
+ <https://github.com/hongyi-zhang/mixup/blob/master/cifar/utils.py>`_.
+
+ The loss and accuracy are computed as:
+
+ .. code-block:: python
+
+ def loss_mixup(y, logits):
+ criterion = F.cross_entropy
+ loss_a = criterion(logits, y[:, 0].long(), reduction='none')
+ loss_b = criterion(logits, y[:, 1].long(), reduction='none')
+ return ((1 - y[:, 2]) * loss_a + y[:, 2] * loss_b).mean()
+
+ .. code-block:: python
+
+ def acc_mixup(y, logits):
+ pred = torch.argmax(logits, dim=1).to(y.device)
+ return (1 - y[:, 2]) * pred.eq(y[:, 0]).float() + y[:, 2] * pred.eq(y[:, 1]).float()
+
+ Args:
+ p (float): probability for applying an augmentation to a batch. This param controls the augmentation
+ probabilities batch-wisely.
+ lambda_val (float or torch.Tensor, optional): min-max value of mixup strength. Default is 0-1.
+ same_on_batch (bool): apply the same transformation across the batch.
+ This flag will not maintain permutation order. Default: False.
+ keepdim (bool): whether to keep the output shape the same as input (True) or broadcast it
+ to the batch form (False). Default: False
+
+ Inputs:
+ - Input image tensors, shape of :math:`(B, C, H, W)`.
+ - Label: raw labels, shape of :math:`(B)`.
+
+ Returns:
+ Tuple[torch.Tensor, torch.Tensor]:
+ - Adjusted image, shape of :math:`(B, C, H, W)`.
+ - Raw labels, permuted labels and lambdas for each mix, shape of :math:`(B, 3)`.
+
+ Note:
+ This implementation would randomly mixup images in a batch. Ideally, the larger batch size would be preferred.
+
+ Examples:
+ >>> rng = torch.manual_seed(1)
+ >>> input = torch.rand(2, 1, 3, 3)
+ >>> label = torch.tensor([0, 1])
+ >>> mixup = RandomMixUp()
+ >>> mixup(input, label)
+ (tensor([[[[0.7576, 0.2793, 0.4031],
+ [0.7347, 0.0293, 0.7999],
+ [0.3971, 0.7544, 0.5695]]],
+ <BLANKLINE>
+ <BLANKLINE>
+ [[[0.4388, 0.6387, 0.5247],
+ [0.6826, 0.3051, 0.4635],
+ [0.4550, 0.5725, 0.4980]]]]), tensor([[0.0000, 0.0000, 0.1980],
+ [1.0000, 1.0000, 0.4162]]))
+ """
+
+ def __init__(
+ self,
+ lambda_val: Optional[Union[torch.Tensor, Tuple[float, float]]] = None,
+ same_on_batch: bool = False,
+ p: float = 1.0,
+ keepdim: bool = False,
+ ) -> None:
+ super().__init__(p=1.0, p_batch=p, same_on_batch=same_on_batch, keepdim=keepdim)
+ self._param_generator = cast(rg.MixupGenerator, rg.MixupGenerator(lambda_val, p=p))
+
+ def apply_transform( # type: ignore
+ self, input: torch.Tensor, label: torch.Tensor, params: Dict[str, torch.Tensor]
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
+ input_permute = input.index_select(dim=0, index=params["mixup_pairs"].to(input.device))
+ labels_permute = label.index_select(dim=0, index=params["mixup_pairs"].to(label.device))
+
+ lam = params["mixup_lambdas"].view(-1, 1, 1, 1).expand_as(input).to(label.device)
+ inputs = input * (1 - lam) + input_permute * lam
+ out_labels = torch.stack(
+ [
+ label.to(input.dtype),
+ labels_permute.to(input.dtype),
+ params["mixup_lambdas"].to(label.device, input.dtype),
+ ],
+ dim=-1,
+ ).to(label.device)
+ return inputs, out_labels
diff --git a/kornia/augmentation/_3d/__init__.py b/kornia/augmentation/_3d/__init__.py
new file mode 100644
index 000000000..5e2e9cd14
--- /dev/null
+++ b/kornia/augmentation/_3d/__init__.py
@@ -0,0 +1,2 @@
+from kornia.augmentation._3d.geometric import *
+from kornia.augmentation._3d.intensity import *
diff --git a/kornia/augmentation/_3d/base.py b/kornia/augmentation/_3d/base.py
new file mode 100644
index 000000000..f715da861
--- /dev/null
+++ b/kornia/augmentation/_3d/base.py
@@ -0,0 +1,47 @@
+import torch
+
+import kornia
+from kornia.augmentation.base import TensorWithTransformMat, _AugmentationBase
+from kornia.augmentation.utils import _transform_input3d, _validate_input_dtype
+
+
+class AugmentationBase3D(_AugmentationBase):
+ r"""AugmentationBase3D base class for customized augmentation implementations.
+
+ For any augmentation, the implementation of "generate_parameters" and "apply_transform" are required while the
+ "compute_transformation" is only required when passing "return_transform" as True.
+
+ Args:
+ p: probability for applying an augmentation. This param controls the augmentation probabilities
+ element-wise for a batch.
+ p_batch: probability for applying an augmentation to a batch. This param controls the augmentation
+ probabilities batch-wise.
+ return_transform: if ``True`` return the matrix describing the geometric transformation applied to each
+ input tensor. If ``False`` and the input is a tuple the applied transformation won't be concatenated.
+ same_on_batch: apply the same transformation across the batch.
+ """
+
+ def __check_batching__(self, input: TensorWithTransformMat):
+ if isinstance(input, tuple):
+ inp, mat = input
+ if len(inp.shape) == 5:
+ if len(mat.shape) != 3:
+ raise AssertionError('Input tensor is in batch mode ' 'but transformation matrix is not')
+ if mat.shape[0] != inp.shape[0]:
+ raise AssertionError(
+ f"In batch dimension, input has {inp.shape[0]} but transformation matrix has {mat.shape[0]}"
+ )
+ elif len(inp.shape) in (3, 4):
+ if len(mat.shape) != 2:
+ raise AssertionError("Input tensor is in non-batch mode but transformation matrix is not")
+ else:
+ raise ValueError(f'Unrecognized output shape. Expected 3, 4 or 5, got {len(inp.shape)}')
+
+ def transform_tensor(self, input: torch.Tensor) -> torch.Tensor:
+ """Convert any incoming (D, H, W), (C, D, H, W) and (B, C, D, H, W) into (B, C, D, H, W)."""
+ _validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])
+ return _transform_input3d(input)
+
+ def identity_matrix(self, input) -> torch.Tensor:
+ """Return 4x4 identity matrix."""
+ return kornia.eye_like(4, input)
diff --git a/kornia/augmentation/_3d/geometric/__init__.py b/kornia/augmentation/_3d/geometric/__init__.py
new file mode 100644
index 000000000..d4566573e
--- /dev/null
+++ b/kornia/augmentation/_3d/geometric/__init__.py
@@ -0,0 +1,8 @@
+from kornia.augmentation._3d.geometric.affine import RandomAffine3D
+from kornia.augmentation._3d.geometric.center_crop import CenterCrop3D
+from kornia.augmentation._3d.geometric.crop import RandomCrop3D
+from kornia.augmentation._3d.geometric.depthical_flip import RandomDepthicalFlip3D
+from kornia.augmentation._3d.geometric.horizontal_flip import RandomHorizontalFlip3D
+from kornia.augmentation._3d.geometric.perspective import RandomPerspective3D
+from kornia.augmentation._3d.geometric.rotation import RandomRotation3D
+from kornia.augmentation._3d.geometric.vertical_flip import RandomVerticalFlip3D
diff --git a/kornia/augmentation/_3d/geometric/affine.py b/kornia/augmentation/_3d/geometric/affine.py
new file mode 100644
index 000000000..9b5481ed0
--- /dev/null
+++ b/kornia/augmentation/_3d/geometric/affine.py
@@ -0,0 +1,156 @@
+from typing import Dict, Optional, Tuple, Union, cast
+
+import torch
+
+from kornia.augmentation import random_generator as rg
+from kornia.augmentation._3d.base import AugmentationBase3D
+from kornia.constants import Resample
+from kornia.geometry import deg2rad, get_affine_matrix3d, warp_affine3d
+
+
+class RandomAffine3D(AugmentationBase3D):
+ r"""Apply affine transformation 3D volumes (5D tensor).
+
+ The transformation is computed so that the center is kept invariant.
+
+ Args:
+ degrees: Range of yaw (x-axis), pitch (y-axis), roll (z-axis) to select from.
+ If degrees is a number, then yaw, pitch, roll will be generated from the range of (-degrees, +degrees).
+ If degrees is a tuple of (min, max), then yaw, pitch, roll will be generated from the range of (min, max).
+ If degrees is a list of floats [a, b, c], then yaw, pitch, roll will be generated from (-a, a), (-b, b)
+ and (-c, c).
+ If degrees is a list of tuple ((a, b), (m, n), (x, y)), then yaw, pitch, roll will be generated from
+ (a, b), (m, n) and (x, y).
+ Set to 0 to deactivate rotations.
+ translate: tuple of maximum absolute fraction for horizontal, vertical and
+ depthical translations (dx,dy,dz). For example translate=(a, b, c), then
+ horizontal shift will be randomly sampled in the range -img_width * a < dx < img_width * a
+ vertical shift will be randomly sampled in the range -img_height * b < dy < img_height * b.
+ depthical shift will be randomly sampled in the range -img_depth * c < dz < img_depth * c.
+ Will not translate by default.
+ scale: scaling factor interval.
+ If (a, b) represents isotropic scaling, the scale is randomly sampled from the range a <= scale <= b.
+ If ((a, b), (c, d), (e, f)), the scale is randomly sampled from the range a <= scale_x <= b,
+ c <= scale_y <= d, e <= scale_z <= f. Will keep original scale by default.
+ shears: Range of degrees to select from.
+ If shear is a number, a shear to the 6 facets in the range (-shear, +shear) will be applied.
+ If shear is a tuple of 2 values, a shear to the 6 facets in the range (shear[0], shear[1]) will be applied.
+ If shear is a tuple of 6 values, a shear to the i-th facet in the range (-shear[i], shear[i])
+ will be applied.
+ If shear is a tuple of 6 tuples, a shear to the i-th facet in the range (-shear[i, 0], shear[i, 1])
+ will be applied.
+ resample:
+ return_transform: if ``True`` return the matrix describing the transformation
+ applied to each.
+ same_on_batch: apply the same transformation across the batch.
+ align_corners: interpolation flag.
+ keepdim: whether to keep the output shape the same as input (True) or broadcast it
+ to the batch form (False). Default: False.
+
+ Shape:
+ - Input: :math:`(C, D, H, W)` or :math:`(B, C, D, H, W)`, Optional: :math:`(B, 4, 4)`
+ - Output: :math:`(B, C, D, H, W)`
+
+ Note:
+ Input tensor must be float and normalized into [0, 1] for the best differentiability support.
+ Additionally, this function accepts another transformation tensor (:math:`(B, 4, 4)`), then the
+ applied transformation will be merged int to the input transformation tensor and returned.
+
+ Examples:
+ >>> rng = torch.manual_seed(0)
+ >>> input = torch.rand(1, 1, 3, 3, 3)
+ >>> aug = RandomAffine3D((15., 20., 20.), p=1., return_transform=True)
+ >>> aug(input)
+ (tensor([[[[[0.4503, 0.4763, 0.1680],
+ [0.2029, 0.4267, 0.3515],
+ [0.3195, 0.5436, 0.3706]],
+ <BLANKLINE>
+ [[0.5255, 0.3508, 0.4858],
+ [0.0795, 0.1689, 0.4220],
+ [0.5306, 0.7234, 0.6879]],
+ <BLANKLINE>
+ [[0.2971, 0.2746, 0.3471],
+ [0.4924, 0.4960, 0.6460],
+ [0.3187, 0.4556, 0.7596]]]]]), tensor([[[ 0.9722, -0.0603, 0.2262, -0.1381],
+ [ 0.1131, 0.9669, -0.2286, 0.1486],
+ [-0.2049, 0.2478, 0.9469, 0.0102],
+ [ 0.0000, 0.0000, 0.0000, 1.0000]]]))
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.rand(1, 3, 32, 32, 32)
+ >>> aug = RandomAffine3D((15., 20., 20.), p=1.)
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
+ """
+
+ def __init__(
+ self,
+ degrees: Union[
+ torch.Tensor,
+ float,
+ Tuple[float, float],
+ Tuple[float, float, float],
+ Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float]],
+ ],
+ translate: Optional[Union[torch.Tensor, Tuple[float, float, float]]] = None,
+ scale: Optional[
+ Union[
+ torch.Tensor, Tuple[float, float], Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float]]
+ ]
+ ] = None,
+ shears: Union[
+ torch.Tensor,
+ float,
+ Tuple[float, float],
+ Tuple[float, float, float, float, float, float],
+ Tuple[
+ Tuple[float, float],
+ Tuple[float, float],
+ Tuple[float, float],
+ Tuple[float, float],
+ Tuple[float, float],
+ Tuple[float, float],
+ ],
+ ] = None,
+ resample: Union[str, int, Resample] = Resample.BILINEAR.name,
+ return_transform: bool = False,
+ same_on_batch: bool = False,
+ align_corners: bool = False,
+ p: float = 0.5,
+ keepdim: bool = False,
+ ) -> None:
+ super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
+ self.degrees = degrees
+ self.shears = shears
+ self.translate = translate
+ self.scale = scale
+
+ self.flags = dict(resample=Resample.get(resample), align_corners=align_corners)
+ self._param_generator = cast(rg.AffineGenerator3D, rg.AffineGenerator3D(degrees, translate, scale, shears))
+
+ def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
+ transform: torch.Tensor = get_affine_matrix3d(
+ params["translations"],
+ params["center"],
+ params["scale"],
+ params["angles"],
+ deg2rad(params["sxy"]),
+ deg2rad(params["sxz"]),
+ deg2rad(params["syx"]),
+ deg2rad(params["syz"]),
+ deg2rad(params["szx"]),
+ deg2rad(params["szy"]),
+ ).to(input)
+ return transform
+
+ def apply_transform(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ ) -> torch.Tensor:
+ transform = cast(torch.Tensor, transform)
+ return warp_affine3d(
+ input,
+ transform[:, :3, :],
+ (input.shape[-3], input.shape[-2], input.shape[-1]),
+ self.flags["resample"].name.lower(),
+ align_corners=self.flags["align_corners"],
+ )
diff --git a/kornia/augmentation/_3d/geometric/center_crop.py b/kornia/augmentation/_3d/geometric/center_crop.py
new file mode 100644
index 000000000..fa7b04f8d
--- /dev/null
+++ b/kornia/augmentation/_3d/geometric/center_crop.py
@@ -0,0 +1,103 @@
+from typing import Dict, Optional, Tuple, Union, cast
+
+import torch
+
+from kornia.augmentation import random_generator as rg
+from kornia.augmentation._3d.base import AugmentationBase3D
+from kornia.constants import Resample
+from kornia.geometry import crop_by_transform_mat3d, get_perspective_transform3d
+
+
+class CenterCrop3D(AugmentationBase3D):
+ r"""Apply center crop on 3D volumes (5D tensor).
+
+ Args:
+ p: probability of applying the transformation for the whole batch.
+ size (Tuple[int, int, int] or int): Desired output size (out_d, out_h, out_w) of the crop.
+ If integer, out_d = out_h = out_w = size.
+ If Tuple[int, int, int], out_d = size[0], out_h = size[1], out_w = size[2].
+ resample:
+ return_transform: if ``True`` return the matrix describing the transformation applied to each
+ input tensor. If ``False`` and the input is a tuple the applied transformation won't be concatenated.
+ align_corners: interpolation flag.
+ keepdim: whether to keep the output shape the same as input (True) or broadcast it
+ to the batch form (False).
+
+ Shape:
+ - Input: :math:`(C, D, H, W)` or :math:`(B, C, D, H, W)`, Optional: :math:`(B, 4, 4)`
+ - Output: :math:`(B, C, out_d, out_h, out_w)`
+
+ Note:
+ Input tensor must be float and normalized into [0, 1] for the best differentiability support.
+ Additionally, this function accepts another transformation tensor (:math:`(B, 4, 4)`), then the
+ applied transformation will be merged int to the input transformation tensor and returned.
+
+ Examples:
+ >>> rng = torch.manual_seed(0)
+ >>> inputs = torch.randn(1, 1, 2, 4, 6)
+ >>> inputs
+ tensor([[[[[-1.1258, -1.1524, -0.2506, -0.4339, 0.8487, 0.6920],
+ [-0.3160, -2.1152, 0.3223, -1.2633, 0.3500, 0.3081],
+ [ 0.1198, 1.2377, 1.1168, -0.2473, -1.3527, -1.6959],
+ [ 0.5667, 0.7935, 0.5988, -1.5551, -0.3414, 1.8530]],
+ <BLANKLINE>
+ [[ 0.7502, -0.5855, -0.1734, 0.1835, 1.3894, 1.5863],
+ [ 0.9463, -0.8437, -0.6136, 0.0316, -0.4927, 0.2484],
+ [ 0.4397, 0.1124, 0.6408, 0.4412, -0.1023, 0.7924],
+ [-0.2897, 0.0525, 0.5229, 2.3022, -1.4689, -1.5867]]]]])
+ >>> aug = CenterCrop3D(2, p=1.)
+ >>> aug(inputs)
+ tensor([[[[[ 0.3223, -1.2633],
+ [ 1.1168, -0.2473]],
+ <BLANKLINE>
+ [[-0.6136, 0.0316],
+ [ 0.6408, 0.4412]]]]])
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.rand(1, 3, 32, 32, 32)
+ >>> aug = CenterCrop3D(24, p=1.)
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
+ """
+
+ def __init__(
+ self,
+ size: Union[int, Tuple[int, int, int]],
+ align_corners: bool = True,
+ resample: Union[str, int, Resample] = Resample.BILINEAR.name,
+ return_transform: bool = False,
+ p: float = 1.0,
+ keepdim: bool = False,
+ ) -> None:
+ # same_on_batch is always True for CenterCrop
+ # Since PyTorch does not support ragged tensor. So cropping function happens batch-wisely.
+ super().__init__(p=1.0, return_transform=return_transform, same_on_batch=True, p_batch=p, keepdim=keepdim)
+ if isinstance(size, tuple):
+ size = (size[0], size[1], size[2])
+ elif isinstance(size, int):
+ size = (size, size, size)
+ else:
+ raise Exception(f"Invalid size type. Expected (int, tuple(int, int int). Got: {size}.")
+ self.flags = dict(size=size, align_corners=align_corners, resample=Resample.get(resample))
+
+ def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
+ return rg.center_crop_generator3d(
+ batch_shape[0], batch_shape[-3], batch_shape[-2], batch_shape[-1], self.flags["size"], device=self.device
+ )
+
+ def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
+ transform: torch.Tensor = get_perspective_transform3d(params["src"].to(input), params["dst"].to(input))
+ transform = transform.expand(input.shape[0], -1, -1)
+ return transform
+
+ def apply_transform(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ ) -> torch.Tensor:
+ transform = cast(torch.Tensor, transform)
+ return crop_by_transform_mat3d(
+ input,
+ transform,
+ self.flags["size"],
+ mode=self.flags["resample"].name.lower(),
+ align_corners=self.flags["align_corners"],
+ )
diff --git a/kornia/augmentation/_3d/geometric/crop.py b/kornia/augmentation/_3d/geometric/crop.py
new file mode 100644
index 000000000..7bffb86a4
--- /dev/null
+++ b/kornia/augmentation/_3d/geometric/crop.py
@@ -0,0 +1,151 @@
+from typing import Dict, Optional, Tuple, Union, cast
+
+import torch
+from torch.nn.functional import pad
+
+from kornia.augmentation import random_generator as rg
+from kornia.augmentation._3d.base import AugmentationBase3D, TensorWithTransformMat
+from kornia.constants import Resample
+from kornia.geometry import crop_by_transform_mat3d, get_perspective_transform3d
+
+
+class RandomCrop3D(AugmentationBase3D):
+ r"""Apply random crop on 3D volumes (5D tensor).
+
+ Crops random sub-volumes on a given size.
+
+ Args:
+ p: probability of applying the transformation for the whole batch.
+ size: Desired output size (out_d, out_h, out_w) of the crop.
+ Must be Tuple[int, int, int], then out_d = size[0], out_h = size[1], out_w = size[2].
+ padding: Optional padding on each border of the image.
+ Default is None, i.e no padding. If a sequence of length 6 is provided, it is used to pad
+ left, top, right, bottom, front, back borders respectively.
+ If a sequence of length 3 is provided, it is used to pad left/right,
+ top/bottom, front/back borders, respectively.
+ pad_if_needed: It will pad the image if smaller than the
+ desired size to avoid raising an exception. Since cropping is done
+ after padding, the padding seems to be done at a random offset.
+ fill: Pixel fill value for constant fill. Default is 0. If a tuple of
+ length 3, it is used to fill R, G, B channels respectively.
+ This value is only used when the padding_mode is constant.
+ padding_mode: Type of padding. Should be: constant, edge, reflect or symmetric. Default is constant.
+ resample:
+ return_transform: if ``True`` return the matrix describing the transformation applied to each
+ input tensor. If ``False`` and the input is a tuple the applied transformation won't be concatenated
+ same_on_batch: apply the same transformation across the batch.
+ align_corners: interpolation flag.
+ keepdim: whether to keep the output shape the same as input (True) or broadcast it
+ to the batch form (False).
+
+ Shape:
+ - Input: :math:`(C, D, H, W)` or :math:`(B, C, D, H, W)`, Optional: :math:`(B, 4, 4)`
+ - Output: :math:`(B, C, , out_d, out_h, out_w)`
+
+ Note:
+ Input tensor must be float and normalized into [0, 1] for the best differentiability support.
+ Additionally, this function accepts another transformation tensor (:math:`(B, 4, 4)`), then the
+ applied transformation will be merged int to the input transformation tensor and returned.
+
+ Examples:
+ >>> rng = torch.manual_seed(0)
+ >>> inputs = torch.randn(1, 1, 3, 3, 3)
+ >>> aug = RandomCrop3D((2, 2, 2), p=1.)
+ >>> aug(inputs)
+ tensor([[[[[-1.1258, -1.1524],
+ [-0.4339, 0.8487]],
+ <BLANKLINE>
+ [[-1.2633, 0.3500],
+ [ 0.1665, 0.8744]]]]])
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.rand(1, 3, 32, 32, 32)
+ >>> aug = RandomCrop3D((24, 24, 24), p=1.)
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
+ """
+
+ def __init__(
+ self,
+ size: Tuple[int, int, int],
+ padding: Optional[Union[int, Tuple[int, int, int], Tuple[int, int, int, int, int, int]]] = None,
+ pad_if_needed: Optional[bool] = False,
+ fill: int = 0,
+ padding_mode: str = "constant",
+ resample: Union[str, int, Resample] = Resample.BILINEAR.name,
+ return_transform: bool = False,
+ same_on_batch: bool = False,
+ align_corners: bool = True,
+ p: float = 1.0,
+ keepdim: bool = False,
+ ) -> None:
+ # Since PyTorch does not support ragged tensor. So cropping function happens batch-wisely.
+ super().__init__(
+ p=1.0, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=p, keepdim=keepdim
+ )
+ self.flags = dict(
+ size=size,
+ padding=padding,
+ pad_if_needed=pad_if_needed,
+ padding_mode=padding_mode,
+ fill=fill,
+ resample=Resample.get(resample),
+ align_corners=align_corners,
+ )
+ self._param_generator = cast(rg.CropGenerator3D, rg.CropGenerator3D(size, None))
+
+ def precrop_padding(self, input: torch.Tensor) -> torch.Tensor:
+ padding = self.flags["padding"]
+ if padding is not None:
+ if isinstance(padding, int):
+ padding = [padding, padding, padding, padding, padding, padding]
+ elif isinstance(padding, (tuple, list)) and len(padding) == 3:
+ padding = [padding[0], padding[0], padding[1], padding[1], padding[2], padding[2]]
+ elif isinstance(padding, (tuple, list)) and len(padding) == 6:
+ padding = [padding[0], padding[1], padding[2], padding[3], padding[4], padding[5]] # type: ignore
+ else:
+ raise ValueError(f"`padding` must be an integer, 3-element-list or 6-element-list. Got {padding}.")
+ input = pad(input, padding, value=self.flags["fill"], mode=self.flags["padding_mode"])
+
+ if self.flags["pad_if_needed"] and input.shape[-3] < self.flags["size"][0]:
+ padding = [0, 0, 0, 0, self.flags["size"][0] - input.shape[-3], self.flags["size"][0] - input.shape[-3]]
+ input = pad(input, padding, value=self.flags["fill"], mode=self.flags["padding_mode"])
+
+ if self.flags["pad_if_needed"] and input.shape[-2] < self.flags["size"][1]:
+ padding = [0, 0, (self.flags["size"][1] - input.shape[-2]), self.flags["size"][1] - input.shape[-2], 0, 0]
+ input = pad(input, padding, value=self.flags["fill"], mode=self.flags["padding_mode"])
+
+ if self.flags["pad_if_needed"] and input.shape[-1] < self.flags["size"][2]:
+ padding = [self.flags["size"][2] - input.shape[-1], self.flags["size"][2] - input.shape[-1], 0, 0, 0, 0]
+ input = pad(input, padding, value=self.flags["fill"], mode=self.flags["padding_mode"])
+
+ return input
+
+ def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
+ transform: torch.Tensor = get_perspective_transform3d(params["src"].to(input), params["dst"].to(input))
+ transform = transform.expand(input.shape[0], -1, -1)
+ return transform
+
+ def apply_transform(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ ) -> torch.Tensor:
+ transform = cast(torch.Tensor, transform)
+ return crop_by_transform_mat3d(
+ input,
+ transform,
+ self.flags["size"],
+ mode=self.flags["resample"].name.lower(),
+ align_corners=self.flags["align_corners"],
+ )
+
+ def forward( # type: ignore
+ self,
+ input: TensorWithTransformMat,
+ params: Optional[Dict[str, torch.Tensor]] = None,
+ return_transform: Optional[bool] = None,
+ ) -> TensorWithTransformMat:
+ if type(input) is tuple:
+ input = (self.precrop_padding(input[0]), input[1])
+ else:
+ input = self.precrop_padding(input) # type:ignore
+ return super().forward(input, params, return_transform)
diff --git a/kornia/augmentation/_3d/geometric/depthical_flip.py b/kornia/augmentation/_3d/geometric/depthical_flip.py
new file mode 100644
index 000000000..0800dbbd2
--- /dev/null
+++ b/kornia/augmentation/_3d/geometric/depthical_flip.py
@@ -0,0 +1,77 @@
+from typing import Dict, Optional
+
+import torch
+
+from kornia.augmentation._3d.base import AugmentationBase3D
+
+
+class RandomDepthicalFlip3D(AugmentationBase3D):
+ r"""Apply random flip along the depth axis of 3D volumes (5D tensor).
+
+ Input should be a tensor of shape :math:`(C, D, H, W)` or a batch of tensors :math:`(*, C, D, H, W)`.
+ If Input is a tuple it is assumed that the first element contains the aforementioned tensors and the second,
+ the corresponding transformation matrix that has been applied to them. In this case the module
+ will Depthically flip the tensors and concatenate the corresponding transformation matrix to the
+ previous one. This is especially useful when using this functionality as part of an ``nn.Sequential`` module.
+
+ Args:
+ p: probability of the image being flipped.
+ return_transform: if ``True`` return the matrix describing the transformation applied to each
+ input tensor. If ``False`` and the input is a tuple the applied transformation
+ won't be concatenated.
+ 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, D, H, W)` or :math:`(B, C, D, H, W)`, Optional: :math:`(B, 4, 4)`
+ - Output: :math:`(B, C, D, H, W)`
+
+ Note:
+ Input tensor must be float and normalized into [0, 1] for the best differentiability support.
+ Additionally, this function accepts another transformation tensor (:math:`(B, 4, 4)`), then the
+ applied transformation will be merged int to the input transformation tensor and returned.
+
+ Examples:
+ >>> x = torch.eye(3).repeat(3, 1, 1)
+ >>> seq = RandomDepthicalFlip3D(p=1.0, return_transform=True)
+ >>> seq(x)
+ (tensor([[[[[1., 0., 0.],
+ [0., 1., 0.],
+ [0., 0., 1.]],
+ <BLANKLINE>
+ [[1., 0., 0.],
+ [0., 1., 0.],
+ [0., 0., 1.]],
+ <BLANKLINE>
+ [[1., 0., 0.],
+ [0., 1., 0.],
+ [0., 0., 1.]]]]]), tensor([[[ 1., 0., 0., 0.],
+ [ 0., 1., 0., 0.],
+ [ 0., 0., -1., 2.],
+ [ 0., 0., 0., 1.]]]))
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.rand(1, 3, 32, 32, 32)
+ >>> aug = RandomDepthicalFlip3D(p=1.)
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
+
+ """
+
+ def __init__(
+ self, return_transform: bool = False, same_on_batch: bool = False, p: float = 0.5, keepdim: bool = False
+ ) -> None:
+ super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
+
+ def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
+ d: int = input.shape[-3]
+ flip_mat: torch.Tensor = torch.tensor(
+ [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, -1, d - 1], [0, 0, 0, 1]], device=input.device, dtype=input.dtype
+ )
+ return flip_mat.repeat(input.size(0), 1, 1)
+
+ def apply_transform(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ ) -> torch.Tensor:
+ return torch.flip(input, [-3])
diff --git a/kornia/augmentation/_3d/geometric/horizontal_flip.py b/kornia/augmentation/_3d/geometric/horizontal_flip.py
new file mode 100644
index 000000000..28b5b253c
--- /dev/null
+++ b/kornia/augmentation/_3d/geometric/horizontal_flip.py
@@ -0,0 +1,70 @@
+from typing import Dict, Optional
+
+import torch
+
+from kornia.augmentation._3d.base import AugmentationBase3D
+
+
+class RandomHorizontalFlip3D(AugmentationBase3D):
+ r"""Apply random horizontal flip to 3D volumes (5D tensor).
+
+ Args:
+ p: probability of the image being flipped.
+ return_transform: if ``True`` return the matrix describing the transformation applied to each
+ input tensor. If ``False`` and the input is a tuple the applied transformation
+ won't be concatenated.
+ 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, D, H, W)` or :math:`(B, C, D, H, W)`, Optional: :math:`(B, 4, 4)`
+ - Output: :math:`(B, C, D, H, W)`
+
+ Note:
+ Input tensor must be float and normalized into [0, 1] for the best differentiability support.
+ Additionally, this function accepts another transformation tensor (:math:`(B, 4, 4)`), then the
+ applied transformation will be merged int to the input transformation tensor and returned.
+
+ Examples:
+ >>> x = torch.eye(3).repeat(3, 1, 1)
+ >>> seq = RandomHorizontalFlip3D(p=1.0, return_transform=True)
+ >>> seq(x)
+ (tensor([[[[[0., 0., 1.],
+ [0., 1., 0.],
+ [1., 0., 0.]],
+ <BLANKLINE>
+ [[0., 0., 1.],
+ [0., 1., 0.],
+ [1., 0., 0.]],
+ <BLANKLINE>
+ [[0., 0., 1.],
+ [0., 1., 0.],
+ [1., 0., 0.]]]]]), tensor([[[-1., 0., 0., 2.],
+ [ 0., 1., 0., 0.],
+ [ 0., 0., 1., 0.],
+ [ 0., 0., 0., 1.]]]))
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.rand(1, 3, 32, 32, 32)
+ >>> aug = RandomHorizontalFlip3D(p=1.)
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
+ """
+
+ def __init__(
+ self, return_transform: bool = False, same_on_batch: bool = False, p: float = 0.5, keepdim: bool = False
+ ) -> None:
+ super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
+
+ def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
+ w: int = input.shape[-1]
+ flip_mat: torch.Tensor = torch.tensor(
+ [[-1, 0, 0, w - 1], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]], device=input.device, dtype=input.dtype
+ )
+ return flip_mat.repeat(input.size(0), 1, 1)
+
+ def apply_transform(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ ) -> torch.Tensor:
+ return torch.flip(input, [-1])
diff --git a/kornia/augmentation/_3d/geometric/perspective.py b/kornia/augmentation/_3d/geometric/perspective.py
new file mode 100644
index 000000000..27e5e3fe9
--- /dev/null
+++ b/kornia/augmentation/_3d/geometric/perspective.py
@@ -0,0 +1,94 @@
+from typing import Dict, Optional, Union, cast
+
+import torch
+
+from kornia.augmentation import random_generator as rg
+from kornia.augmentation._3d.base import AugmentationBase3D
+from kornia.constants import Resample
+from kornia.geometry import get_perspective_transform3d, warp_perspective3d
+
+
+class RandomPerspective3D(AugmentationBase3D):
+ r"""Apply andom perspective transformation to 3D volumes (5D tensor).
+
+ Args:
+ p: probability of the image being perspectively transformed.
+ distortion_scale: it controls the degree of distortion and ranges from 0 to 1.
+ resample:
+ return_transform: if ``True`` return the matrix describing the transformation applied to each.
+ same_on_batch: apply the same transformation across the batch.
+ align_corners: interpolation flag.
+ keepdim: whether to keep the output shape the same as input (True) or broadcast it
+ to the batch form (False).
+
+ Shape:
+ - Input: :math:`(C, D, H, W)` or :math:`(B, C, D, H, W)`, Optional: :math:`(B, 4, 4)`
+ - Output: :math:`(B, C, D, H, W)`
+
+ Note:
+ Input tensor must be float and normalized into [0, 1] for the best differentiability support.
+ Additionally, this function accepts another transformation tensor (:math:`(B, 4, 4)`), then the
+ applied transformation will be merged int to the input transformation tensor and returned.
+
+ Examples:
+ >>> rng = torch.manual_seed(0)
+ >>> inputs= torch.tensor([[[
+ ... [[1., 0., 0.],
+ ... [0., 1., 0.],
+ ... [0., 0., 1.]],
+ ... [[1., 0., 0.],
+ ... [0., 1., 0.],
+ ... [0., 0., 1.]],
+ ... [[1., 0., 0.],
+ ... [0., 1., 0.],
+ ... [0., 0., 1.]]
+ ... ]]])
+ >>> aug = RandomPerspective3D(0.5, p=1., align_corners=True)
+ >>> aug(inputs)
+ tensor([[[[[0.3976, 0.5507, 0.0000],
+ [0.0901, 0.3668, 0.0000],
+ [0.0000, 0.0000, 0.0000]],
+ <BLANKLINE>
+ [[0.2651, 0.4657, 0.0000],
+ [0.1390, 0.5174, 0.0000],
+ [0.0000, 0.0000, 0.0000]],
+ <BLANKLINE>
+ [[0.0000, 0.1153, 0.0000],
+ [0.0000, 0.0000, 0.0000],
+ [0.0000, 0.0000, 0.0000]]]]])
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.rand(1, 3, 32, 32, 32)
+ >>> aug = RandomPerspective3D(0.5, p=1.)
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
+ """
+
+ def __init__(
+ self,
+ distortion_scale: Union[torch.Tensor, float] = 0.5,
+ resample: Union[str, int, Resample] = Resample.BILINEAR.name,
+ return_transform: bool = False,
+ same_on_batch: bool = False,
+ align_corners: bool = False,
+ p: float = 0.5,
+ keepdim: bool = False,
+ ) -> None:
+ super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
+ self.flags = dict(resample=Resample.get(resample), align_corners=align_corners)
+ self._param_generator = cast(rg.PerspectiveGenerator3D, rg.PerspectiveGenerator3D(distortion_scale))
+
+ def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
+ return get_perspective_transform3d(params["start_points"], params["end_points"]).to(input)
+
+ def apply_transform(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ ) -> torch.Tensor:
+ transform = cast(torch.Tensor, transform)
+ return warp_perspective3d(
+ input,
+ transform,
+ (input.shape[-3], input.shape[-2], input.shape[-1]),
+ flags=self.flags["resample"].name.lower(),
+ align_corners=self.flags["align_corners"],
+ )
diff --git a/kornia/augmentation/_3d/geometric/rotation.py b/kornia/augmentation/_3d/geometric/rotation.py
new file mode 100644
index 000000000..5e025a4b4
--- /dev/null
+++ b/kornia/augmentation/_3d/geometric/rotation.py
@@ -0,0 +1,115 @@
+from typing import Dict, Optional, Tuple, Union, cast
+
+import torch
+
+from kornia.augmentation import random_generator as rg
+from kornia.augmentation._3d.base import AugmentationBase3D
+from kornia.constants import Resample
+from kornia.geometry import affine3d
+from kornia.geometry.transform.affwarp import _compute_rotation_matrix3d, _compute_tensor_center3d
+
+
+class RandomRotation3D(AugmentationBase3D):
+ r"""Apply random rotations to 3D volumes (5D tensor).
+
+ Input should be a tensor of shape (C, D, H, W) or a batch of tensors :math:`(B, C, D, H, W)`.
+ If Input is a tuple it is assumed that the first element contains the aforementioned tensors and the second,
+ the corresponding transformation matrix that has been applied to them. In this case the module
+ will rotate the tensors and concatenate the corresponding transformation matrix to the
+ previous one. This is especially useful when using this functionality as part of an ``nn.Sequential`` module.
+
+ Args:
+ degrees: Range of degrees to select from.
+ If degrees is a number, then yaw, pitch, roll will be generated from the range of (-degrees, +degrees).
+ If degrees is a tuple of (min, max), then yaw, pitch, roll will be generated from the range of (min, max).
+ If degrees is a list of floats [a, b, c], then yaw, pitch, roll will be generated from (-a, a), (-b, b)
+ and (-c, c).
+ If degrees is a list of tuple ((a, b), (m, n), (x, y)), then yaw, pitch, roll will be generated from
+ (a, b), (m, n) and (x, y).
+ Set to 0 to deactivate rotations.
+ resample:
+ return_transform: if ``True`` return the matrix describing the transformation applied to each
+ input tensor. If ``False`` and the input is a tuple the applied transformation won't be concatenated.
+ same_on_batch: apply the same transformation across the batch.
+ align_corners: interpolation flag.
+ keepdim: whether to keep the output shape the same as input (True) or broadcast it
+ to the batch form (False).
+
+ Shape:
+ - Input: :math:`(C, D, H, W)` or :math:`(B, C, D, H, W)`, Optional: :math:`(B, 4, 4)`
+ - Output: :math:`(B, C, D, H, W)`
+
+ Note:
+ Input tensor must be float and normalized into [0, 1] for the best differentiability support.
+ Additionally, this function accepts another transformation tensor (:math:`(B, 4, 4)`), then the
+ applied transformation will be merged int to the input transformation tensor and returned.
+
+ Examples:
+ >>> rng = torch.manual_seed(0)
+ >>> input = torch.rand(1, 1, 3, 3, 3)
+ >>> aug = RandomRotation3D((15., 20., 20.), p=1.0, return_transform=True)
+ >>> aug(input)
+ (tensor([[[[[0.3819, 0.4886, 0.2111],
+ [0.1196, 0.3833, 0.4722],
+ [0.3432, 0.5951, 0.4223]],
+ <BLANKLINE>
+ [[0.5553, 0.4374, 0.2780],
+ [0.2423, 0.1689, 0.4009],
+ [0.4516, 0.6376, 0.7327]],
+ <BLANKLINE>
+ [[0.1605, 0.3112, 0.3673],
+ [0.4931, 0.4620, 0.5700],
+ [0.3505, 0.4685, 0.8092]]]]]), tensor([[[ 0.9722, 0.1131, -0.2049, 0.1196],
+ [-0.0603, 0.9669, 0.2478, -0.1545],
+ [ 0.2262, -0.2286, 0.9469, 0.0556],
+ [ 0.0000, 0.0000, 0.0000, 1.0000]]]))
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.rand(1, 3, 32, 32, 32)
+ >>> aug = RandomRotation3D((15., 20., 20.), p=1.)
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
+ """
+
+ def __init__(
+ self,
+ degrees: Union[
+ torch.Tensor,
+ float,
+ Tuple[float, float, float],
+ Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float]],
+ ],
+ resample: Union[str, int, Resample] = Resample.BILINEAR.name,
+ return_transform: bool = False,
+ same_on_batch: bool = False,
+ align_corners: bool = False,
+ p: float = 0.5,
+ keepdim: bool = False,
+ ) -> None:
+ super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
+ self.flags = dict(resample=Resample.get(resample), align_corners=align_corners)
+ self._param_generator = cast(rg.RotationGenerator3D, rg.RotationGenerator3D(degrees))
+
+ def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
+ yaw: torch.Tensor = params["yaw"].to(input)
+ pitch: torch.Tensor = params["pitch"].to(input)
+ roll: torch.Tensor = params["roll"].to(input)
+
+ center: torch.Tensor = _compute_tensor_center3d(input)
+ rotation_mat: torch.Tensor = _compute_rotation_matrix3d(yaw, pitch, roll, center.expand(yaw.shape[0], -1))
+
+ # rotation_mat is B x 3 x 4 and we need a B x 4 x 4 matrix
+ trans_mat: torch.Tensor = torch.eye(4, device=input.device, dtype=input.dtype).repeat(input.shape[0], 1, 1)
+ trans_mat[:, 0] = rotation_mat[:, 0]
+ trans_mat[:, 1] = rotation_mat[:, 1]
+ trans_mat[:, 2] = rotation_mat[:, 2]
+
+ return trans_mat
+
+ def apply_transform(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ ) -> torch.Tensor:
+ transform = cast(torch.Tensor, transform)
+ return affine3d(
+ input, transform[..., :3, :4], self.flags["resample"].name.lower(), "zeros", self.flags["align_corners"]
+ )
diff --git a/kornia/augmentation/_3d/geometric/vertical_flip.py b/kornia/augmentation/_3d/geometric/vertical_flip.py
new file mode 100644
index 000000000..f5ba2d9aa
--- /dev/null
+++ b/kornia/augmentation/_3d/geometric/vertical_flip.py
@@ -0,0 +1,76 @@
+from typing import Dict, Optional
+
+import torch
+
+from kornia.augmentation._3d.base import AugmentationBase3D
+
+
+class RandomVerticalFlip3D(AugmentationBase3D):
+ r"""Apply random vertical flip to 3D volumes (5D tensor).
+
+ Input should be a tensor of shape :math:`(C, D, H, W)` or a batch of tensors :math:`(*, C, D, H, W)`.
+ If Input is a tuple it is assumed that the first element contains the aforementioned tensors and the second,
+ the corresponding transformation matrix that has been applied to them. In this case the module
+ will Vertically flip the tensors and concatenate the corresponding transformation matrix to the
+ previous one. This is especially useful when using this functionality as part of an ``nn.Sequential`` module.
+
+ Args:
+ p: probability of the image being flipped.
+ return_transform: if ``True`` return the matrix describing the transformation applied to each
+ input tensor. If ``False`` and the input is a tuple the applied transformation
+ won't be concatenated.
+ 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, D, H, W)` or :math:`(B, C, D, H, W)`, Optional: :math:`(B, 4, 4)`
+ - Output: :math:`(B, C, D, H, W)`
+
+ Note:
+ Input tensor must be float and normalized into [0, 1] for the best differentiability support.
+ Additionally, this function accepts another transformation tensor (:math:`(B, 4, 4)`), then the
+ applied transformation will be merged int to the input transformation tensor and returned.
+
+ Examples:
+ >>> x = torch.eye(3).repeat(3, 1, 1)
+ >>> seq = RandomVerticalFlip3D(p=1.0, return_transform=True)
+ >>> seq(x)
+ (tensor([[[[[0., 0., 1.],
+ [0., 1., 0.],
+ [1., 0., 0.]],
+ <BLANKLINE>
+ [[0., 0., 1.],
+ [0., 1., 0.],
+ [1., 0., 0.]],
+ <BLANKLINE>
+ [[0., 0., 1.],
+ [0., 1., 0.],
+ [1., 0., 0.]]]]]), tensor([[[ 1., 0., 0., 0.],
+ [ 0., -1., 0., 2.],
+ [ 0., 0., 1., 0.],
+ [ 0., 0., 0., 1.]]]))
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.rand(1, 3, 32, 32, 32)
+ >>> aug = RandomVerticalFlip3D(p=1.)
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
+ """
+
+ def __init__(
+ self, return_transform: bool = False, same_on_batch: bool = False, p: float = 0.5, keepdim: bool = False
+ ) -> None:
+ super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
+
+ def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
+ h: int = input.shape[-2]
+ flip_mat: torch.Tensor = torch.tensor(
+ [[1, 0, 0, 0], [0, -1, 0, h - 1], [0, 0, 1, 0], [0, 0, 0, 1]], device=input.device, dtype=input.dtype
+ )
+ return flip_mat.repeat(input.size(0), 1, 1)
+
+ def apply_transform(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ ) -> torch.Tensor:
+ return torch.flip(input, [-2])
diff --git a/kornia/augmentation/_3d/intensity/__init__.py b/kornia/augmentation/_3d/intensity/__init__.py
new file mode 100644
index 000000000..87b40c595
--- /dev/null
+++ b/kornia/augmentation/_3d/intensity/__init__.py
@@ -0,0 +1,2 @@
+from kornia.augmentation._3d.intensity.equalize import RandomEqualize3D
+from kornia.augmentation._3d.intensity.motion_blur import RandomMotionBlur3D
diff --git a/kornia/augmentation/_3d/intensity/equalize.py b/kornia/augmentation/_3d/intensity/equalize.py
new file mode 100644
index 000000000..d886b4dda
--- /dev/null
+++ b/kornia/augmentation/_3d/intensity/equalize.py
@@ -0,0 +1,64 @@
+from typing import Dict, Optional
+
+import torch
+
+from kornia.augmentation._3d.base import AugmentationBase3D
+from kornia.enhance import equalize3d
+
+
+class RandomEqualize3D(AugmentationBase3D):
+ r"""Apply random equalization to 3D volumes (5D tensor).
+
+ Args:
+ p: probability of the image being equalized.
+ return_transform: if ``True`` return the matrix describing the transformation applied to each
+ input tensor. If ``False`` and the input is a tuple the applied transformation won't be concatenated.
+ 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, D, H, W)` or :math:`(B, C, D, H, W)`, Optional: :math:`(B, 4, 4)`
+ - Output: :math:`(B, C, D, H, W)`
+
+ Note:
+ Input tensor must be float and normalized into [0, 1] for the best differentiability support.
+ Additionally, this function accepts another transformation tensor (:math:`(B, 4, 4)`), then the
+ applied transformation will be merged int to the input transformation tensor and returned.
+
+ Examples:
+ >>> rng = torch.manual_seed(0)
+ >>> input = torch.rand(1, 1, 3, 3, 3)
+ >>> aug = RandomEqualize3D(p=1.0)
+ >>> aug(input)
+ tensor([[[[[0.4963, 0.7682, 0.0885],
+ [0.1320, 0.3074, 0.6341],
+ [0.4901, 0.8964, 0.4556]],
+ <BLANKLINE>
+ [[0.6323, 0.3489, 0.4017],
+ [0.0223, 0.1689, 0.2939],
+ [0.5185, 0.6977, 0.8000]],
+ <BLANKLINE>
+ [[0.1610, 0.2823, 0.6816],
+ [0.9152, 0.3971, 0.8742],
+ [0.4194, 0.5529, 0.9527]]]]])
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.rand(1, 3, 32, 32, 32)
+ >>> aug = RandomEqualize3D(p=1.)
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
+ """
+
+ def __init__(
+ self, p: float = 0.5, return_transform: bool = False, same_on_batch: bool = False, keepdim: bool = False
+ ) -> None:
+ super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
+
+ def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
+ return self.identity_matrix(input)
+
+ def apply_transform(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ ) -> torch.Tensor:
+ return equalize3d(input)
diff --git a/kornia/augmentation/_3d/intensity/motion_blur.py b/kornia/augmentation/_3d/intensity/motion_blur.py
new file mode 100644
index 000000000..2c4c0bb6f
--- /dev/null
+++ b/kornia/augmentation/_3d/intensity/motion_blur.py
@@ -0,0 +1,116 @@
+from typing import Dict, Optional, Tuple, Union, cast
+
+import torch
+
+from kornia.augmentation import random_generator as rg
+from kornia.augmentation._3d.base import AugmentationBase3D
+from kornia.constants import BorderType, Resample
+from kornia.filters import motion_blur3d
+
+
+class RandomMotionBlur3D(AugmentationBase3D):
+ r"""Apply random motion blur on 3D volumes (5D tensor).
+
+ Args:
+ p: probability of applying the transformation.
+ kernel_size: motion kernel size (odd and positive).
+ If int, the kernel will have a fixed size.
+ If Tuple[int, int], it will randomly generate the value from the range batch-wisely.
+ angle: Range of degrees to select from.
+ If angle is a number, then yaw, pitch, roll will be generated from the range of (-angle, +angle).
+ If angle is a tuple of (min, max), then yaw, pitch, roll will be generated from the range of (min, max).
+ If angle is a list of floats [a, b, c], then yaw, pitch, roll will be generated from (-a, a), (-b, b)
+ and (-c, c).
+ If angle is a list of tuple ((a, b), (m, n), (x, y)), then yaw, pitch, roll will be generated from
+ (a, b), (m, n) and (x, y).
+ Set to 0 to deactivate rotations.
+ direction: forward/backward direction of the motion blur.
+ Lower values towards -1.0 will point the motion blur towards the back (with angle provided via angle),
+ while higher values towards 1.0 will point the motion blur forward. A value of 0.0 leads to a
+ uniformly (but still angled) motion blur.
+ If float, it will generate the value from (-direction, direction).
+ If Tuple[int, int], it will randomly generate the value from the range.
+ border_type: the padding mode to be applied before convolving.
+ CONSTANT = 0, REFLECT = 1, REPLICATE = 2, CIRCULAR = 3. Default: BorderType.CONSTANT.
+ resample: resample mode from "nearest" (0) or "bilinear" (1).
+ keepdim: whether to keep the output shape the same as input (True) or broadcast it to the batch form (False).
+
+ Shape:
+ - Input: :math:`(C, D, H, W)` or :math:`(B, C, D, H, W)`, Optional: :math:`(B, 4, 4)`
+ - Output: :math:`(B, C, D, H, W)`
+
+ Note:
+ Input tensor must be float and normalized into [0, 1] for the best differentiability support.
+ Additionally, this function accepts another transformation tensor (:math:`(B, 4, 4)`), then the
+ applied transformation will be merged int to the input transformation tensor and returned.
+
+ Examples:
+ >>> rng = torch.manual_seed(0)
+ >>> input = torch.rand(1, 1, 3, 5, 5)
+ >>> motion_blur = RandomMotionBlur3D(3, 35., 0.5, p=1.)
+ >>> motion_blur(input)
+ tensor([[[[[0.1654, 0.4772, 0.2004, 0.3566, 0.2613],
+ [0.4557, 0.3131, 0.4809, 0.2574, 0.2696],
+ [0.2721, 0.5998, 0.3956, 0.5363, 0.1541],
+ [0.3006, 0.4773, 0.6395, 0.2856, 0.3989],
+ [0.4491, 0.5595, 0.1836, 0.3811, 0.1398]],
+ <BLANKLINE>
+ [[0.1843, 0.4240, 0.3370, 0.1231, 0.2186],
+ [0.4047, 0.3332, 0.1901, 0.5329, 0.3023],
+ [0.3070, 0.3088, 0.4807, 0.4928, 0.2590],
+ [0.2416, 0.4614, 0.7091, 0.5237, 0.1433],
+ [0.1582, 0.4577, 0.2749, 0.1369, 0.1607]],
+ <BLANKLINE>
+ [[0.2733, 0.4040, 0.4396, 0.2284, 0.3319],
+ [0.3856, 0.6730, 0.4624, 0.3878, 0.3076],
+ [0.4307, 0.4217, 0.2977, 0.5086, 0.5406],
+ [0.3686, 0.2778, 0.5228, 0.7592, 0.6455],
+ [0.2033, 0.3014, 0.4898, 0.6164, 0.3117]]]]])
+
+ To apply the exact augmenation again, you may take the advantage of the previous parameter state:
+ >>> input = torch.rand(1, 3, 32, 32, 32)
+ >>> aug = RandomMotionBlur3D(3, 35., 0.5, p=1.)
+ >>> (aug(input) == aug(input, params=aug._params)).all()
+ tensor(True)
+ """
+
+ def __init__(
+ self,
+ kernel_size: Union[int, Tuple[int, int]],
+ angle: Union[
+ torch.Tensor,
+ float,
+ Tuple[float, float, float],
+ Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float]],
+ ],
+ direction: Union[torch.Tensor, float, Tuple[float, float]],
+ border_type: Union[int, str, BorderType] = BorderType.CONSTANT.name,
+ resample: Union[str, int, Resample] = Resample.NEAREST.name,
+ return_transform: bool = False,
+ same_on_batch: bool = False,
+ p: float = 0.5,
+ keepdim: bool = False,
+ ) -> None:
+ super().__init__(
+ p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim
+ )
+ self.flags = dict(border_type=BorderType.get(border_type), resample=Resample.get(resample))
+ self._param_generator = cast(rg.MotionBlurGenerator3D, rg.MotionBlurGenerator3D(kernel_size, angle, direction))
+
+ def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
+ return self.identity_matrix(input)
+
+ def apply_transform(
+ self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ ) -> torch.Tensor:
+ kernel_size: int = cast(int, params["ksize_factor"].unique().item())
+ angle = params["angle_factor"]
+ direction = params["direction_factor"]
+ return motion_blur3d(
+ input,
+ kernel_size,
+ angle,
+ direction,
+ self.flags["border_type"].name.lower(),
+ self.flags["resample"].name.lower(),
+ )
diff --git a/kornia/augmentation/__init__.py b/kornia/augmentation/__init__.py
index 36b7f81eb..842e51ab9 100644
--- a/kornia/augmentation/__init__.py
+++ b/kornia/augmentation/__init__.py
@@ -1,4 +1,4 @@
-from .augmentation import (
+from kornia.augmentation._2d import (
CenterCrop,
ColorJitter,
Denormalize,
@@ -8,6 +8,7 @@ from .augmentation import (
RandomBoxBlur,
RandomChannelShuffle,
RandomCrop,
+ RandomCutMix,
RandomElasticTransform,
RandomEqualize,
RandomErasing,
@@ -17,6 +18,7 @@ from .augmentation import (
RandomGrayscale,
RandomHorizontalFlip,
RandomInvert,
+ RandomMixUp,
RandomMotionBlur,
RandomPerspective,
RandomPosterize,
@@ -27,7 +29,11 @@ from .augmentation import (
RandomThinPlateSpline,
RandomVerticalFlip,
)
-from .augmentation3d import (
+from kornia.augmentation._2d.base import AugmentationBase2D
+from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
+from kornia.augmentation._2d.mix.base import MixAugmentationBase
+from kornia.augmentation._3d import (
CenterCrop3D,
RandomAffine3D,
RandomCrop3D,
@@ -39,12 +45,14 @@ from .augmentation3d import (
RandomRotation3D,
RandomVerticalFlip3D,
)
-from .base import AugmentationBase2D, AugmentationBase3D
-from .container import AugmentationSequential, ImageSequential, PatchSequential, VideoSequential
-from .mix_augmentation import RandomCutMix, RandomMixUp
+from kornia.augmentation._3d.base import AugmentationBase3D
+from kornia.augmentation.container import AugmentationSequential, ImageSequential, PatchSequential, VideoSequential
__all__ = [
"AugmentationBase2D",
+ "GeometricAugmentationBase2D",
+ "IntensityAugmentationBase2D",
+ "MixAugmentationBase",
"CenterCrop",
"ColorJitter",
"Normalize",
diff --git a/kornia/augmentation/augmentation.py b/kornia/augmentation/augmentation.py
deleted file mode 100644
index 4eaf1678e..000000000
--- a/kornia/augmentation/augmentation.py
+++ /dev/null
@@ -1,2306 +0,0 @@
-from typing import Any, cast, Dict, List, Optional, Tuple, Union
-
-import torch
-from torch.nn.functional import pad
-
-from kornia.augmentation.base import GeometricAugmentationBase2D, IntensityAugmentationBase2D, TensorWithTransformMat
-from kornia.color import rgb_to_grayscale
-from kornia.constants import BorderType, pi, Resample, SamplePadding
-from kornia.enhance import (
- adjust_brightness,
- adjust_contrast,
- adjust_hue,
- adjust_saturation,
- denormalize,
- equalize,
- invert,
- normalize,
- posterize,
- sharpness,
- solarize,
-)
-from kornia.filters import box_blur, gaussian_blur2d, motion_blur
-from kornia.geometry.bbox import bbox_generator, bbox_to_mask
-from kornia.geometry.conversions import deg2rad
-from kornia.geometry.transform import (
- affine,
- crop_by_transform_mat,
- elastic_transform2d,
- get_affine_matrix2d,
- get_perspective_transform,
- get_tps_transform,
- hflip,
- remap,
- resize,
- vflip,
- warp_affine,
- warp_image_tps,
- warp_perspective,
-)
-from kornia.geometry.transform.affwarp import _compute_rotation_matrix, _compute_tensor_center
-from kornia.utils import create_meshgrid
-
-from . import random_generator as rg
-from .utils import _transform_input
-
-
-class RandomHorizontalFlip(GeometricAugmentationBase2D):
- r"""Apply a random horizontal flip to a tensor image or a batch of tensor images with a given probability.
-
- .. image:: _static/img/RandomHorizontalFlip.png
-
- Input should be a tensor of shape (C, H, W) or a batch of tensors :math:`(B, C, H, W)`.
- If Input is a tuple it is assumed that the first element contains the aforementioned tensors and the second,
- the corresponding transformation matrix that has been applied to them. In this case the module
- will Horizontally flip the tensors and concatenate the corresponding transformation matrix to the
- previous one. This is especially useful when using this functionality as part of an ``nn.Sequential`` module.
-
- Args:
- p: probability of the image being flipped.
- return_transform: if ``True`` return the matrix describing the transformation applied to each
- input tensor. If ``False`` and the input is a tuple the applied transformation
- won't be concatenated.
- 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)`, Optional: :math:`(B, 3, 3)`
- - Output: :math:`(B, C, H, W)`
-
- .. note::
- This function internally uses :func:`kornia.geometry.transform.hflip`.
-
- Examples:
- >>> input = torch.tensor([[[[0., 0., 0.],
- ... [0., 0., 0.],
- ... [0., 1., 1.]]]])
- >>> seq = RandomHorizontalFlip(p=1.0, return_transform=True)
- >>> seq(input)
- (tensor([[[[0., 0., 0.],
- [0., 0., 0.],
- [1., 1., 0.]]]]), tensor([[[-1., 0., 2.],
- [ 0., 1., 0.],
- [ 0., 0., 1.]]]))
- >>> seq.inverse(seq(input)).equal(input)
- True
-
- To apply the exact augmenation again, you may take the advantage of the previous parameter state:
- >>> input = torch.randn(1, 3, 32, 32)
- >>> seq = RandomHorizontalFlip(p=1.0)
- >>> (seq(input) == seq(input, params=seq._params)).all()
- tensor(True)
- """
-
- def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
- w: int = int(params["forward_input_shape"][-1])
- flip_mat: torch.Tensor = torch.tensor(
- [[-1, 0, w - 1], [0, 1, 0], [0, 0, 1]], device=input.device, dtype=input.dtype
- )
-
- return flip_mat.repeat(input.size(0), 1, 1)
-
- def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
- ) -> torch.Tensor:
- return hflip(input)
-
- def inverse_transform(
- self,
- input: torch.Tensor,
- transform: Optional[torch.Tensor] = None,
- size: Optional[Tuple[int, int]] = None,
- **kwargs,
- ) -> torch.Tensor:
- return self.apply_transform(
- input, params=self._params, transform=torch.as_tensor(transform, device=input.device, dtype=input.dtype)
- )
-
-
-class RandomVerticalFlip(GeometricAugmentationBase2D):
- r"""Apply a random vertical flip to a tensor image or a batch of tensor images with a given probability.
-
- .. image:: _static/img/RandomVerticalFlip.png
-
- Args:
- p: probability of the image being flipped.
- return_transform: if ``True`` return the matrix describing the transformation applied to each
- input tensor. If ``False`` and the input is a tuple the applied transformation
- won't be concatenated.
- 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)`, Optional: :math:`(B, 3, 3)`
- - Output: :math:`(B, C, H, W)`
-
- .. note::
- This function internally uses :func:`kornia.geometry.transform.vflip`.
-
- Examples:
- >>> input = torch.tensor([[[[0., 0., 0.],
- ... [0., 0., 0.],
- ... [0., 1., 1.]]]])
- >>> seq = RandomVerticalFlip(p=1.0, return_transform=True)
- >>> seq(input)
- (tensor([[[[0., 1., 1.],
- [0., 0., 0.],
- [0., 0., 0.]]]]), tensor([[[ 1., 0., 0.],
- [ 0., -1., 2.],
- [ 0., 0., 1.]]]))
- >>> seq.inverse(seq(input)).equal(input)
- True
-
- To apply the exact augmenation again, you may take the advantage of the previous parameter state:
- >>> input = torch.randn(1, 3, 32, 32)
- >>> seq = RandomVerticalFlip(p=1.0)
- >>> (seq(input) == seq(input, params=seq._params)).all()
- tensor(True)
- """
-
- def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
- h: int = int(params["forward_input_shape"][-2])
- flip_mat: torch.Tensor = torch.tensor(
- [[1, 0, 0], [0, -1, h - 1], [0, 0, 1]], device=input.device, dtype=input.dtype
- )
-
- return flip_mat.repeat(input.size(0), 1, 1)
-
- def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
- ) -> torch.Tensor:
- return vflip(input)
-
- def inverse_transform(
- self,
- input: torch.Tensor,
- transform: Optional[torch.Tensor] = None,
- size: Optional[Tuple[int, int]] = None,
- **kwargs,
- ) -> torch.Tensor:
- return self.apply_transform(
- input, params=self._params, transform=torch.as_tensor(transform, device=input.device, dtype=input.dtype)
- )
-
-
-class ColorJitter(IntensityAugmentationBase2D):
- r"""Apply a random transformation to the brightness, contrast, saturation and hue of a tensor image.
-
- .. image:: _static/img/ColorJitter.png
-
- Args:
- p: probability of applying the transformation.
- brightness: The brightness factor to apply.
- contrast: The contrast factor to apply.
- saturation: The saturation factor to apply.
- hue: The hue factor to apply.
- return_transform: if ``True`` return the matrix describing the transformation applied to each
- input tensor. If ``False`` and the input is a tuple the applied transformation
- won't be concatenated.
- 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)`, Optional: :math:`(B, 3, 3)`
- - Output: :math:`(B, C, H, W)`
-
- .. note::
- This function internally uses :func:`kornia.enhance.adjust_brightness`,
- :func:`kornia.enhance.adjust_contrast`. :func:`kornia.enhance.adjust_saturation`,
- :func:`kornia.enhance.adjust_hue`.
-
- Examples:
- >>> rng = torch.manual_seed(0)
- >>> inputs = torch.ones(1, 3, 3, 3)
- >>> aug = ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.)
- >>> aug(inputs)
- tensor([[[[0.9993, 0.9993, 0.9993],
- [0.9993, 0.9993, 0.9993],
- [0.9993, 0.9993, 0.9993]],
- <BLANKLINE>
- [[0.9993, 0.9993, 0.9993],
- [0.9993, 0.9993, 0.9993],
- [0.9993, 0.9993, 0.9993]],
- <BLANKLINE>
- [[0.9993, 0.9993, 0.9993],
- [0.9993, 0.9993, 0.9993],
- [0.9993, 0.9993, 0.9993]]]])
-
- To apply the exact augmenation again, you may take the advantage of the previous parameter state:
- >>> input = torch.randn(1, 3, 32, 32)
- >>> aug = ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.)
- >>> (aug(input) == aug(input, params=aug._params)).all()
- tensor(True)
- """
-
- def __init__(
- self,
- brightness: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.0,
- contrast: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.0,
- saturation: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.0,
- hue: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.0,
- return_transform: bool = False,
- same_on_batch: bool = False,
- p: float = 1.0,
- keepdim: bool = False,
- ) -> None:
- super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
- self.brightness = brightness
- self.contrast = contrast
- self.saturation = saturation
- self.hue = hue
- self._param_generator = cast(
- rg.ColorJitterGenerator, rg.ColorJitterGenerator(brightness, contrast, saturation, hue)
- )
-
- def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
- ) -> torch.Tensor:
- transforms = [
- lambda img: adjust_brightness(img, params["brightness_factor"] - 1),
- lambda img: adjust_contrast(img, params["contrast_factor"]),
- lambda img: adjust_saturation(img, params["saturation_factor"]),
- lambda img: adjust_hue(img, params["hue_factor"] * 2 * pi),
- ]
-
- jittered = input
- for idx in params["order"].tolist():
- t = transforms[idx]
- jittered = t(jittered)
-
- return jittered
-
-
-class RandomGrayscale(IntensityAugmentationBase2D):
- r"""Apply random transformation to Grayscale according to a probability p value.
-
- .. image:: _static/img/RandomGrayscale.png
-
- Args:
- p: probability of the image to be transformed to grayscale.
- return_transform: if ``True`` return the matrix describing the transformation applied to each
- input tensor. If ``False`` and the input is a tuple the applied transformation
- won't be concatenated.
- 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)`, Optional: :math:`(B, 3, 3)`
- - Output: :math:`(B, C, H, W)`
-
- .. note::
- This function internally uses :func:`kornia.color.rgb_to_grayscale`.
-
- Examples:
- >>> rng = torch.manual_seed(0)
- >>> inputs = torch.randn((1, 3, 3, 3))
- >>> aug = RandomGrayscale(p=1.0)
- >>> aug(inputs)
- tensor([[[[-1.1344, -0.1330, 0.1517],
- [-0.0791, 0.6711, -0.1413],
- [-0.1717, -0.9023, 0.0819]],
- <BLANKLINE>
- [[-1.1344, -0.1330, 0.1517],
- [-0.0791, 0.6711, -0.1413],
- [-0.1717, -0.9023, 0.0819]],
- <BLANKLINE>
- [[-1.1344, -0.1330, 0.1517],
- [-0.0791, 0.6711, -0.1413],
- [-0.1717, -0.9023, 0.0819]]]])
-
- To apply the exact augmenation again, you may take the advantage of the previous parameter state:
- >>> input = torch.randn(1, 3, 32, 32)
- >>> aug = RandomGrayscale(p=1.0)
- >>> (aug(input) == aug(input, params=aug._params)).all()
- tensor(True)
- """
-
- def __init__(
- self, return_transform: bool = False, same_on_batch: bool = False, p: float = 0.1, keepdim: bool = False
- ) -> None:
- super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
-
- def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
- ) -> torch.Tensor:
- # Make sure it returns (*, 3, H, W)
- grayscale = torch.ones_like(input)
- grayscale[:] = rgb_to_grayscale(input)
- return grayscale
-
-
-class RandomErasing(IntensityAugmentationBase2D):
- r"""Erase a random rectangle of a tensor image according to a probability p value.
-
- .. image:: _static/img/RandomErasing.png
-
- The operator removes image parts and fills them with zero values at a selected rectangle
- for each of the images in the batch.
-
- The rectangle will have an area equal to the original image area multiplied by a value uniformly
- sampled between the range [scale[0], scale[1]) and an aspect ratio sampled
- between [ratio[0], ratio[1])
-
- Args:
- p: probability that the random erasing operation will be performed.
- scale: range of proportion of erased area against input image.
- ratio: range of aspect ratio of erased area.
- 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)`, Optional: :math:`(B, 3, 3)`
- - Output: :math:`(B, C, H, W)`
-
- Note:
- Input tensor must be float and normalized into [0, 1] for the best differentiability support.
- Additionally, this function accepts another transformation tensor (:math:`(B, 3, 3)`), then the
- applied transformation will be merged int to the input transformation tensor and returned.
-
- Examples:
- >>> rng = torch.manual_seed(0)
- >>> inputs = torch.ones(1, 1, 3, 3)
- >>> aug = RandomErasing((.4, .8), (.3, 1/.3), p=0.5)
- >>> aug(inputs)
- tensor([[[[1., 0., 0.],
- [1., 0., 0.],
- [1., 0., 0.]]]])
-
- To apply the exact augmenation again, you may take the advantage of the previous parameter state:
- >>> input = torch.randn(1, 3, 32, 32)
- >>> aug = RandomErasing((.4, .8), (.3, 1/.3), p=1.)
- >>> (aug(input) == aug(input, params=aug._params)).all()
- tensor(True)
- """
-
- # Note: Extra params, inplace=False in Torchvision.
- def __init__(
- self,
- scale: Union[torch.Tensor, Tuple[float, float]] = (0.02, 0.33),
- ratio: Union[torch.Tensor, Tuple[float, float]] = (0.3, 3.3),
- value: float = 0.0,
- return_transform: bool = False,
- same_on_batch: bool = False,
- p: float = 0.5,
- keepdim: bool = False,
- ) -> None:
- super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
- self.scale = scale
- self.ratio = ratio
- self.value: float = float(value)
- self._param_generator = cast(
- rg.RectangleEraseGenerator, rg.RectangleEraseGenerator(scale, ratio, float(value))
- )
-
- def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
- ) -> torch.Tensor:
- _, c, h, w = input.size()
- values = params["values"].unsqueeze(-1).unsqueeze(-1).unsqueeze(-1).repeat(1, *input.shape[1:]).to(input)
-
- bboxes = bbox_generator(params["xs"], params["ys"], params["widths"], params["heights"])
- mask = bbox_to_mask(bboxes, w, h) # Returns B, H, W
- mask = mask.unsqueeze(1).repeat(1, c, 1, 1).to(input) # Transform to B, c, H, W
- transformed = torch.where(mask == 1.0, values, input)
- return transformed
-
-
-class RandomPerspective(GeometricAugmentationBase2D):
- r"""Apply a random perspective transformation to an image tensor with a given probability.
-
- .. image:: _static/img/RandomPerspective.png
-
- Args:
- p: probability of the image being perspectively transformed.
- distortion_scale: the degree of distortion, ranged from 0 to 1.
- resample: the interpolation method to use.
- return_transform: if ``True`` return the matrix describing the transformation
- applied to each.
- same_on_batch: apply the same transformation across the batch. Default: False.
- align_corners: interpolation flag.
- 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)`, Optional: :math:`(B, 3, 3)`
- - Output: :math:`(B, C, H, W)`
-
- .. note::
- This function internally uses :func:`kornia.geometry.transform.warp_pespective`.
-
- Examples:
- >>> rng = torch.manual_seed(0)
- >>> inputs= torch.tensor([[[[1., 0., 0.],
- ... [0., 1., 0.],
- ... [0., 0., 1.]]]])
- >>> aug = RandomPerspective(0.5, p=0.5)
- >>> out = aug(inputs)
- >>> out
- tensor([[[[0.0000, 0.2289, 0.0000],
- [0.0000, 0.4800, 0.0000],
- [0.0000, 0.0000, 0.0000]]]])
- >>> aug.inverse(out)
- tensor([[[[0.0500, 0.0961, 0.0000],
- [0.2011, 0.3144, 0.0000],
- [0.0031, 0.0130, 0.0053]]]])
-
- To apply the exact augmenation again, you may take the advantage of the previous parameter state:
- >>> input = torch.randn(1, 3, 32, 32)
- >>> aug = RandomPerspective(0.5, p=1.)
- >>> (aug(input) == aug(input, params=aug._params)).all()
- tensor(True)
- """
-
- def __init__(
- self,
- distortion_scale: Union[torch.Tensor, float] = 0.5,
- resample: Union[str, int, Resample] = Resample.BILINEAR.name,
- return_transform: bool = False,
- same_on_batch: bool = False,
- align_corners: bool = False,
- p: float = 0.5,
- keepdim: bool = False,
- ) -> None:
- super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
- self._param_generator = cast(
- rg.PerspectiveGenerator, rg.PerspectiveGenerator(distortion_scale)
- )
- self.flags: Dict[str, Any] = dict(
- align_corners=align_corners,
- resample=Resample.get(resample)
- )
-
- def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
- return get_perspective_transform(params["start_points"].to(input), params["end_points"].to(input))
-
- def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
- ) -> torch.Tensor:
- _, _, height, width = input.shape
- transform = cast(torch.Tensor, transform)
- return warp_perspective(
- input, transform, (height, width), mode=self.flags["resample"].name.lower(),
- align_corners=self.flags["align_corners"]
- )
-
- def inverse_transform(
- self,
- input: torch.Tensor,
- transform: Optional[torch.Tensor] = None,
- size: Optional[Tuple[int, int]] = None,
- **kwargs,
- ) -> torch.Tensor:
- return self.apply_transform(
- input, params=self._params, transform=torch.as_tensor(transform, device=input.device, dtype=input.dtype)
- )
-
-
-class RandomAffine(GeometricAugmentationBase2D):
- r"""Apply a random 2D affine transformation to a tensor image.
-
- .. image:: _static/img/RandomAffine.png
-
- The transformation is computed so that the image center is kept invariant.
-
- Args:
- p: probability of applying the transformation.
- degrees: Range of degrees to select from.
- If degrees is a number instead of sequence like (min, max), the range of degrees
- will be (-degrees, +degrees). Set to 0 to deactivate rotations.
- 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.
- scale: scaling factor interval.
- If (a, b) represents isotropic scaling, the scale is randomly sampled from the range a <= scale <= b.
- If (a, b, c, d), the scale is randomly sampled from the range a <= scale_x <= b, c <= scale_y <= d.
- Will keep original scale by default.
- 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).
- return_transform: if ``True`` return the matrix describing the transformation applied to each.
- same_on_batch: apply the same transformation across the batch.
- align_corners: interpolation flag.
- 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)`, Optional: :math:`(B, 3, 3)`
- - Output: :math:`(B, C, H, W)`
-
- .. note::
- This function internally uses :func:`kornia.geometry.transform.warp_affine`.
-
- Examples:
- >>> rng = torch.manual_seed(0)
- >>> input = torch.rand(1, 1, 3, 3)
- >>> aug = RandomAffine((-15., 20.), return_transform=True, p=1.)
- >>> out = aug(input)
- >>> out
- (tensor([[[[0.3961, 0.7310, 0.1574],
- [0.1781, 0.3074, 0.5648],
- [0.4804, 0.8379, 0.4234]]]]), tensor([[[ 0.9923, -0.1241, 0.1319],
- [ 0.1241, 0.9923, -0.1164],
- [ 0.0000, 0.0000, 1.0000]]]))
- >>> aug.inverse(out)
- tensor([[[[0.3890, 0.6573, 0.1865],
- [0.2063, 0.3074, 0.5459],
- [0.3892, 0.7896, 0.4224]]]])
- >>> input
- tensor([[[[0.4963, 0.7682, 0.0885],
- [0.1320, 0.3074, 0.6341],
- [0.4901, 0.8964, 0.4556]]]])
-
- To apply the exact augmenation again, you may take the advantage of the previous parameter state:
- >>> input = torch.randn(1, 3, 32, 32)
- >>> aug = RandomAffine((-15., 20.), p=1.)
- >>> (aug(input) == aug(input, params=aug._params)).all()
- tensor(True)
- """
-
- def __init__(
- self,
- degrees: Union[torch.Tensor, float, Tuple[float, float]],
- translate: Optional[Union[torch.Tensor, Tuple[float, float]]] = None,
- scale: Optional[Union[torch.Tensor, Tuple[float, float], Tuple[float, float, float, float]]] = None,
- shear: Optional[Union[torch.Tensor, float, Tuple[float, float]]] = None,
- resample: Union[str, int, Resample] = Resample.BILINEAR.name,
- return_transform: bool = False,
- 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, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
- self._param_generator = cast(
- rg.AffineGenerator, rg.AffineGenerator(degrees, translate, scale, shear)
- )
- self.flags = dict(
- resample=Resample.get(resample),
- padding_mode=SamplePadding.get(padding_mode),
- align_corners=align_corners,
- )
-
- def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.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)),
- )
-
- def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
- ) -> torch.Tensor:
- _, _, height, width = input.shape
- transform = cast(torch.Tensor, transform)
- return warp_affine(
- input,
- transform[:, :2, :],
- (height, width),
- self.flags["resample"].name.lower(),
- align_corners=self.flags["align_corners"],
- padding_mode=self.flags["padding_mode"].name.lower(),
- )
-
- def inverse_transform(
- self,
- input: torch.Tensor,
- transform: Optional[torch.Tensor] = None,
- size: Optional[Tuple[int, int]] = None,
- **kwargs,
- ) -> torch.Tensor:
- return self.apply_transform(
- input, params=self._params, transform=torch.as_tensor(transform, device=input.device, dtype=input.dtype)
- )
-
-
-class CenterCrop(GeometricAugmentationBase2D):
- r"""Crop a given image tensor at the center.
-
- .. image:: _static/img/CenterCrop.png
-
- Args:
- size: Desired output size (out_h, out_w) of the crop.
- If integer, out_h = out_w = size.
- If Tuple[int, int], out_h = size[0], out_w = size[1].
- align_corners: interpolation flag.
- resample: The interpolation mode.
- return_transform: if ``True`` return the matrix describing the transformation
- applied to each.
- p: probability of applying the transformation for the whole batch.
- keepdim: whether to keep the output shape the same as input (True) or broadcast it
- to the batch form (False).
- cropping_mode: The used algorithm to crop. ``slice`` will use advanced slicing to extract the tensor based
- on the sampled indices. ``resample`` will use `warp_affine` using the affine transformation
- to extract and resize at once. Use `slice` for efficiency, or `resample` for proper
- differentiability.
-
- Shape:
- - Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
- - Output: :math:`(B, C, out_h, out_w)`
-
- .. note::
- This function internally uses :func:`kornia.geometry.transform.crop_by_boxes`.
-
- Examples:
- >>> rng = torch.manual_seed(0)
- >>> inputs = torch.randn(1, 1, 4, 4)
- >>> inputs
- tensor([[[[-1.1258, -1.1524, -0.2506, -0.4339],
- [ 0.8487, 0.6920, -0.3160, -2.1152],
- [ 0.3223, -1.2633, 0.3500, 0.3081],
- [ 0.1198, 1.2377, 1.1168, -0.2473]]]])
- >>> aug = CenterCrop(2, p=1., cropping_mode="resample")
- >>> out = aug(inputs)
- >>> out
- tensor([[[[ 0.6920, -0.3160],
- [-1.2633, 0.3500]]]])
- >>> aug.inverse(out, padding_mode="border")
- tensor([[[[ 0.6920, 0.6920, -0.3160, -0.3160],
- [ 0.6920, 0.6920, -0.3160, -0.3160],
- [-1.2633, -1.2633, 0.3500, 0.3500],
- [-1.2633, -1.2633, 0.3500, 0.3500]]]])
-
- To apply the exact augmenation again, you may take the advantage of the previous parameter state:
- >>> input = torch.randn(1, 3, 32, 32)
- >>> aug = CenterCrop(2, p=1., cropping_mode="resample")
- >>> (aug(input) == aug(input, params=aug._params)).all()
- tensor(True)
- """
-
- def __init__(
- self,
- size: Union[int, Tuple[int, int]],
- align_corners: bool = True,
- resample: Union[str, int, Resample] = Resample.BILINEAR.name,
- return_transform: bool = False,
- p: float = 1.0,
- keepdim: bool = False,
- cropping_mode: str = "slice",
- ) -> None:
- # same_on_batch is always True for CenterCrop
- # Since PyTorch does not support ragged tensor. So cropping function happens batch-wisely.
- super().__init__(p=1.0,
- return_transform=return_transform,
- same_on_batch=True,
- p_batch=p,
- keepdim=keepdim)
- if isinstance(size, tuple):
- self.size = (size[0], size[1])
- elif isinstance(size, int):
- self.size = (size, size)
- else:
- raise Exception(f"Invalid size type. Expected (int, tuple(int, int). " f"Got: {type(size)}.")
-
- self.flags = dict(
- resample=Resample.get(resample),
- cropping_mode=cropping_mode,
- align_corners=align_corners,
- size=self.size
- )
-
- def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
- return rg.center_crop_generator(batch_shape[0], batch_shape[-2], batch_shape[-1], self.size, self.device)
-
- def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
- transform: torch.Tensor = get_perspective_transform(params["src"].to(input), params["dst"].to(input))
- transform = transform.expand(input.shape[0], -1, -1)
- return transform
-
- def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
- ) -> torch.Tensor:
- if self.flags["cropping_mode"] == "resample": # uses bilinear interpolation to crop
- transform = cast(torch.Tensor, transform)
- return crop_by_transform_mat(
- input, transform[:, :2, :], self.size, self.flags["resample"].name.lower(),
- "zeros", self.flags["align_corners"]
- )
- if self.flags["cropping_mode"] == "slice": # uses advanced slicing to crop
- # TODO: implement as separated function `crop_and_resize_iterative`
- B, C, _, _ = input.shape
- H, W = self.size
- out = torch.empty(B, C, H, W, device=input.device, dtype=input.dtype)
- for i in range(B):
- x1 = int(params["src"][i, 0, 0])
- x2 = int(params["src"][i, 1, 0]) + 1
- y1 = int(params["src"][i, 0, 1])
- y2 = int(params["src"][i, 3, 1]) + 1
- out[i] = input[i : i + 1, :, y1:y2, x1:x2]
- return out
- raise NotImplementedError(f"Not supported type: {self.flags['cropping_mode']}.")
-
- def inverse_transform(
- self,
- input: torch.Tensor,
- transform: Optional[torch.Tensor] = None,
- size: Optional[Tuple[int, int]] = None,
- **kwargs,
- ) -> torch.Tensor:
- if self.flags["cropping_mode"] != "resample":
- raise NotImplementedError(
- f"`inverse` is only applicable for resample cropping mode. Got {self.flags['cropping_mode']}."
- )
- if size is None:
- size = self.size
- mode = self.flags["resample"].name.lower() if "mode" not in kwargs else kwargs["mode"]
- align_corners = self.flags["align_corners"] if "align_corners" not in kwargs else kwargs["align_corners"]
- padding_mode = "zeros" if "padding_mode" not in kwargs else kwargs["padding_mode"]
- transform = cast(torch.Tensor, transform)
- return crop_by_transform_mat(input, transform[:, :2, :], size, mode, padding_mode, align_corners)
-
-
-class RandomRotation(GeometricAugmentationBase2D):
- r"""Apply a random rotation to a tensor image or a batch of tensor images given an amount of degrees.
-
- .. image:: _static/img/RandomRotation.png
-
- Args:
- p: probability of applying the transformation.
- degrees: range of degrees to select from. If degrees is a number the
- range of degrees to select from will be (-degrees, +degrees).
- resample: Default: the interpolation mode.
- return_transform: if ``True`` return the matrix describing the transformation applied to each
- input tensor. If ``False`` and the input is a tuple the applied transformation
- won't be concatenated.
- same_on_batch: apply the same transformation across the batch.
- align_corners: interpolation flag.
- 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)`, Optional: :math:`(B, 3, 3)`
- - Output: :math:`(B, C, H, W)`
-
- .. note::
- This function internally uses :func:`kornia.geometry.transform.affine`.
-
- Examples:
- >>> rng = torch.manual_seed(0)
- >>> input = torch.tensor([[1., 0., 0., 2.],
- ... [0., 0., 0., 0.],
- ... [0., 1., 2., 0.],
- ... [0., 0., 1., 2.]])
- >>> aug = RandomRotation(degrees=45.0, return_transform=True, p=1.)
- >>> out = aug(input)
- >>> out[0]
- tensor([[[[0.9824, 0.0088, 0.0000, 1.9649],
- [0.0000, 0.0029, 0.0000, 0.0176],
- [0.0029, 1.0000, 1.9883, 0.0000],
- [0.0000, 0.0088, 1.0117, 1.9649]]]])
- >>> out[1]
- tensor([[[ 1.0000, -0.0059, 0.0088],
- [ 0.0059, 1.0000, -0.0088],
- [ 0.0000, 0.0000, 1.0000]]])
- >>> aug.inverse(out)
- tensor([[[[9.6526e-01, 8.6824e-03, 1.7263e-02, 1.9305e+00],
- [8.6398e-03, 2.9485e-03, 5.8971e-03, 1.7365e-02],
- [2.9054e-03, 9.9416e-01, 1.9825e+00, 2.3134e-02],
- [2.5777e-05, 1.1640e-02, 9.9992e-01, 1.9392e+00]]]])
-
- To apply the exact augmenation again, you may take the advantage of the previous parameter state:
- >>> input = torch.randn(1, 3, 32, 32)
- >>> aug = RandomRotation(degrees=45.0, p=1.)
- >>> (aug(input) == aug(input, params=aug._params)).all()
- tensor(True)
- """
-
- # Note: Extra params, center=None, fill=0 in TorchVision
-
- def __init__(
- self,
- degrees: Union[torch.Tensor, float, Tuple[float, float], List[float]],
- resample: Union[str, int, Resample] = Resample.BILINEAR.name,
- return_transform: bool = False,
- same_on_batch: bool = False,
- align_corners: bool = True,
- p: float = 0.5,
- keepdim: bool = False,
- ) -> None:
- super().__init__(p=p,
- return_transform=return_transform,
- same_on_batch=same_on_batch,
- keepdim=keepdim)
- self._param_generator = cast(
- rg.PlainUniformGenerator, rg.PlainUniformGenerator((degrees, "degrees", 0., (-360., 360.)))
- )
- self.flags = dict(
- resample=Resample.get(resample),
- align_corners=align_corners,
- )
-
- def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
- # TODO: Update to use `get_rotation_matrix2d`
- angles: torch.Tensor = params["degrees"].to(input)
-
- center: torch.Tensor = _compute_tensor_center(input)
- rotation_mat: torch.Tensor = _compute_rotation_matrix(angles, center.expand(angles.shape[0], -1))
-
- # rotation_mat is B x 2 x 3 and we need a B x 3 x 3 matrix
- trans_mat: torch.Tensor = torch.eye(3, device=input.device, dtype=input.dtype).repeat(input.shape[0], 1, 1)
- trans_mat[:, 0] = rotation_mat[:, 0]
- trans_mat[:, 1] = rotation_mat[:, 1]
-
- return trans_mat
-
- def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
- ) -> torch.Tensor:
- transform = cast(torch.Tensor, transform)
- return affine(
- input, transform[..., :2, :3], self.flags["resample"].name.lower(), "zeros", self.flags["align_corners"])
-
- def inverse_transform(
- self,
- input: torch.Tensor,
- transform: Optional[torch.Tensor] = None,
- size: Optional[Tuple[int, int]] = None,
- **kwargs,
- ) -> torch.Tensor:
- return self.apply_transform(
- input, params=self._params, transform=torch.as_tensor(transform, device=input.device, dtype=input.dtype)
- )
-
-
-class RandomCrop(GeometricAugmentationBase2D):
- r"""Crop random patches of a tensor image on a given size.
-
- .. image:: _static/img/RandomCrop.png
-
- Args:
- p: probability of applying the transformation for the whole batch.
- size: Desired output size (out_h, out_w) of the crop.
- Must be Tuple[int, int], then out_h = size[0], out_w = size[1].
- padding: Optional padding on each border
- of the image. Default is None, i.e no padding. If a sequence of length
- 4 is provided, it is used to pad left, top, right, bottom borders
- respectively. If a sequence of length 2 is provided, it is used to
- pad left/right, top/bottom borders, respectively.
- pad_if_needed: It will pad the image if smaller than the
- desired size to avoid raising an exception. Since cropping is done
- after padding, the padding seems to be done at a random offset.
- fill: Pixel fill value for constant fill. Default is 0. If a tuple of
- length 3, it is used to fill R, G, B channels respectively.
- This value is only used when the padding_mode is constant.
- padding_mode: Type of padding. Should be: constant, edge, reflect or symmetric.
- resample: the interpolation mode.
- return_transform: if ``True`` return the matrix describing the transformation applied to each
- input tensor. If ``False`` and the input is a tuple the applied transformation
- won't be concatenated.
- same_on_batch: apply the same transformation across the batch.
- align_corners: interpolation flag.
- keepdim: whether to keep the output shape the same as input (True) or broadcast it
- to the batch form (False).
- cropping_mode: The used algorithm to crop. ``slice`` will use advanced slicing to extract the tensor based
- on the sampled indices. ``resample`` will use `warp_affine` using the affine transformation
- to extract and resize at once. Use `slice` for efficiency, or `resample` for proper
- differentiability.
-
- Shape:
- - Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
- - Output: :math:`(B, C, out_h, out_w)`
-
- Note:
- Input tensor must be float and normalized into [0, 1] for the best differentiability support.
- Additionally, this function accepts another transformation tensor (:math:`(B, 3, 3)`), then the
- applied transformation will be merged int to the input transformation tensor and returned.
-
- Examples:
- >>> _ = torch.manual_seed(0)
- >>> inputs = torch.arange(1*1*3*3.).view(1, 1, 3, 3)
- >>> aug = RandomCrop((2, 2), p=1., cropping_mode="resample")
- >>> out = aug(inputs)
- >>> out
- tensor([[[[3., 4.],
- [6., 7.]]]])
- >>> aug.inverse(out, padding_mode="border")
- tensor([[[[3., 4., 4.],
- [3., 4., 4.],
- [6., 7., 7.]]]])
-
- To apply the exact augmenation again, you may take the advantage of the previous parameter state:
- >>> input = torch.randn(1, 3, 32, 32)
- >>> aug = RandomCrop((2, 2), p=1., cropping_mode="resample")
- >>> (aug(input) == aug(input, params=aug._params)).all()
- tensor(True)
- """
-
- def __init__(
- self,
- size: Tuple[int, int],
- padding: Optional[Union[int, Tuple[int, int], Tuple[int, int, int, int]]] = None,
- pad_if_needed: Optional[bool] = False,
- fill: int = 0,
- padding_mode: str = "constant",
- resample: Union[str, int, Resample] = Resample.BILINEAR.name,
- return_transform: bool = False,
- same_on_batch: bool = False,
- align_corners: bool = True,
- p: float = 1.0,
- keepdim: bool = False,
- cropping_mode: str = "slice",
- ) -> None:
- # Since PyTorch does not support ragged tensor. So cropping function happens batch-wisely.
- super().__init__(
- p=1.0, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=p, keepdim=keepdim
- )
- self._param_generator = cast(rg.CropGenerator, rg.CropGenerator(size))
- self.flags = dict(
- size=size,
- padding=padding,
- pad_if_needed=pad_if_needed,
- fill=fill,
- padding_mode=padding_mode,
- resample=Resample.get(resample),
- align_corners=align_corners,
- cropping_mode=cropping_mode,
- )
-
- def compute_padding(self, shape: torch.Size) -> List[int]:
- if len(shape) != 4:
- raise AssertionError(f"Expected BCHW. Got {shape}.")
- padding = [0, 0, 0, 0]
- if self.flags["padding"] is not None:
- if isinstance(self.flags["padding"], int):
- padding = [self.flags["padding"]] * 4
- elif isinstance(self.flags["padding"], tuple) and len(self.flags["padding"]) == 2:
- padding = [
- self.flags["padding"][1],
- self.flags["padding"][1],
- self.flags["padding"][0],
- self.flags["padding"][0]
- ]
- elif isinstance(self.flags["padding"], tuple) and len(self.flags["padding"]) == 4:
- padding = [
- self.flags["padding"][3],
- self.flags["padding"][2],
- self.flags["padding"][1],
- self.flags["padding"][0]
- ]
- else:
- raise RuntimeError(
- f"Expect `padding` to be a scalar, or length 2/4 list. Got {self.flags['padding']}.")
-
- if self.flags["pad_if_needed"] and shape[-2] < self.flags["size"][0]:
- padding = [0, 0, (self.flags["size"][0] - shape[-2]), self.flags["size"][0] - shape[-2]]
-
- if self.flags["pad_if_needed"] and shape[-1] < self.flags["size"][1]:
- padding = [self.flags["size"][1] - shape[-1], self.flags["size"][1] - shape[-1], 0, 0]
-
- return padding
-
- def precrop_padding(self, input: torch.Tensor, padding: List[int] = None) -> torch.Tensor:
- if padding is None:
- padding = self.compute_padding(input.shape)
-
- input = pad(input, padding, value=self.flags["fill"], mode=self.flags["padding_mode"])
-
- return input
-
- def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
- transform: torch.Tensor = get_perspective_transform(params["src"].to(input), params["dst"].to(input))
- return transform
-
- def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
- ) -> torch.Tensor:
- if self.flags["cropping_mode"] == "resample": # uses bilinear interpolation to crop
- transform = cast(torch.Tensor, transform)
- return crop_by_transform_mat(
- input,
- transform,
- self.flags["size"],
- mode=self.flags["resample"].name.lower(),
- padding_mode="zeros",
- align_corners=self.flags["align_corners"],
- )
- if self.flags["cropping_mode"] == "slice": # uses advanced slicing to crop
- B, C, _, _ = input.shape
- out = torch.empty(B, C, *self.flags["size"], device=input.device, dtype=input.dtype)
- for i in range(B):
- x1 = int(params["src"][i, 0, 0])
- x2 = int(params["src"][i, 1, 0]) + 1
- y1 = int(params["src"][i, 0, 1])
- y2 = int(params["src"][i, 3, 1]) + 1
- out[i] = input[i : i + 1, :, y1:y2, x1:x2]
- return out
- raise NotImplementedError(f"Not supported type: {self.flags['cropping_mode']}.")
-
- def inverse_transform(
- self,
- input: torch.Tensor,
- transform: Optional[torch.Tensor] = None,
- size: Optional[Tuple[int, int]] = None,
- **kwargs,
- ) -> torch.Tensor:
- if self.flags["cropping_mode"] != "resample":
- raise NotImplementedError(
- f"`inverse` is only applicable for resample cropping mode. Got {self.flags['cropping_mode']}."
- )
- size = cast(Tuple[int, int], size)
- mode = self.flags["resample"].name.lower() if "mode" not in kwargs else kwargs["mode"]
- align_corners = self.flags["align_corners"] if "align_corners" not in kwargs else kwargs["align_corners"]
- padding_mode = "zeros" if "padding_mode" not in kwargs else kwargs["padding_mode"]
- transform = cast(torch.Tensor, transform)
- return crop_by_transform_mat(input, transform[:, :2, :], size, mode, padding_mode, align_corners)
-
- def inverse(
- self,
- input: TensorWithTransformMat,
- params: Optional[Dict[str, torch.Tensor]] = None,
- size: Optional[Tuple[int, int]] = None,
- **kwargs,
- ) -> torch.Tensor:
- out = super().inverse(input, params, size, **kwargs)
- if params is None:
- params = self._params
- if "padding_size" in params:
- padding_size = params["padding_size"].unique(dim=0).cpu().squeeze().numpy().tolist()
- padding_size = [-padding_size[0], -padding_size[1], -padding_size[2], -padding_size[3]]
- else:
- padding_size = [0, 0, 0, 0]
- return self.precrop_padding(out, padding_size)
-
- def forward_parameters_precrop(self, batch_shape) -> Dict[str, torch.Tensor]:
- input_pad = self.compute_padding(batch_shape)
- batch_shape_new = (
- *batch_shape[:2],
- batch_shape[2] + input_pad[2] + input_pad[3], # original height + top + bottom padding
- batch_shape[3] + input_pad[0] + input_pad[1] # original width + left + right padding
- )
- padding_size = torch.tensor(tuple(input_pad), dtype=torch.long).expand(batch_shape[0], -1)
- _params = super().forward_parameters(batch_shape_new)
- _params.update({"padding_size": padding_size})
- return _params
-
- def forward(
- self,
- input: TensorWithTransformMat,
- params: Optional[Dict[str, torch.Tensor]] = None,
- return_transform: Optional[bool] = None,
- ) -> TensorWithTransformMat:
- padding_size = params.get("padding_size") if params else None
- if padding_size is not None:
- input_pad = padding_size.unique(dim=0).cpu().squeeze().numpy().tolist()
- else:
- input_pad = None
-
- if isinstance(input, (tuple, list)):
- input_temp = _transform_input(input[0])
- input_pad = self.compute_padding(input[0].shape) if input_pad is None else input_pad
- _input = (self.precrop_padding(input_temp, input_pad), input[1])
- else:
- input = cast(torch.Tensor, input) # TODO: weird that cast is not working under this context.
- input_temp = _transform_input(input)
- input_pad = self.compute_padding(input_temp.shape) if input_pad is None else input_pad
- _input = self.precrop_padding(input_temp, input_pad) # type: ignore
- out = super().forward(_input, params, return_transform)
-
- # Update the actual input size for inverse
- if "padding_size" not in self._params:
- _padding_size = torch.tensor(tuple(input_pad), device=input_temp.device, dtype=torch.long).expand(
- input_temp.size(0), -1
- )
- self._params.update({"padding_size": _padding_size})
-
- if not self._params["batch_prob"].all():
- # undo the pre-crop if nothing happened.
- if isinstance(out, tuple) and isinstance(input, tuple):
- return input[0], out[1]
- if isinstance(out, tuple) and not isinstance(input, tuple):
- return input, out[1]
- return input
- return out
-
-
-class RandomResizedCrop(GeometricAugmentationBase2D):
- r"""Crop random patches in an image tensor and resizes to a given size.
-
- .. image:: _static/img/RandomResizedCrop.png
-
- Args:
- size: Desired output size (out_h, out_w) of each edge.
- Must be Tuple[int, int], then out_h = size[0], out_w = size[1].
- scale: range of size of the origin size cropped.
- ratio: range of aspect ratio of the origin aspect ratio cropped.
- resample: the interpolation mode.
- return_transform: if ``True`` return the matrix describing the transformation applied to each
- input tensor. If ``False`` and the input is a tuple the applied transformation
- won't be concatenated.
- same_on_batch: apply the same transformation across the batch.
- align_corners: interpolation flag.
- keepdim: whether to keep the output shape the same as input (True) or broadcast it
- to the batch form (False).
- cropping_mode: The used algorithm to crop. ``slice`` will use advanced slicing to extract the tensor based
- on the sampled indices. ``resample`` will use `warp_affine` using the affine transformation
- to extract and resize at once. Use `slice` for efficiency, or `resample` for proper
- differentiability.
-
- Shape:
- - Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
- - Output: :math:`(B, C, out_h, out_w)`
-
- Note:
- Input tensor must be float and normalized into [0, 1] for the best differentiability support.
- Additionally, this function accepts another transformation tensor (:math:`(B, 3, 3)`), then the
- applied transformation will be merged int to the input transformation tensor and returned.
-
- Example:
- >>> rng = torch.manual_seed(0)
- >>> inputs = torch.tensor([[[0., 1., 2.],
- ... [3., 4., 5.],
- ... [6., 7., 8.]]])
- >>> aug = RandomResizedCrop(size=(3, 3), scale=(3., 3.), ratio=(2., 2.), p=1., cropping_mode="resample")
- >>> out = aug(inputs)
- >>> out
- tensor([[[[1.0000, 1.5000, 2.0000],
- [4.0000, 4.5000, 5.0000],
- [7.0000, 7.5000, 8.0000]]]])
- >>> aug.inverse(out, padding_mode="border")
- tensor([[[[1., 1., 2.],
- [4., 4., 5.],
- [7., 7., 8.]]]])
-
- To apply the exact augmenation again, you may take the advantage of the previous parameter state:
- >>> input = torch.randn(1, 3, 32, 32)
- >>> aug = RandomResizedCrop(size=(3, 3), scale=(3., 3.), ratio=(2., 2.), p=1., cropping_mode="resample")
- >>> (aug(input) == aug(input, params=aug._params)).all()
- tensor(True)
- """
-
- def __init__(
- self,
- size: Tuple[int, int],
- scale: Union[torch.Tensor, Tuple[float, float]] = (0.08, 1.0),
- ratio: Union[torch.Tensor, Tuple[float, float]] = (3.0 / 4.0, 4.0 / 3.0),
- resample: Union[str, int, Resample] = Resample.BILINEAR.name,
- return_transform: bool = False,
- same_on_batch: bool = False,
- align_corners: bool = True,
- p: float = 1.0,
- keepdim: bool = False,
- cropping_mode: str = "slice",
- ) -> None:
- # Since PyTorch does not support ragged tensor. So cropping function happens all the time.
- super().__init__(
- p=1.0, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=p, keepdim=keepdim
- )
- self._param_generator = cast(rg.ResizedCropGenerator, rg.ResizedCropGenerator(size, scale, ratio))
- self.flags = dict(
- size=size,
- resample=Resample.get(resample),
- align_corners=align_corners,
- cropping_mode=cropping_mode,
- )
-
- def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
- transform: torch.Tensor = get_perspective_transform(params["src"].to(input), params["dst"].to(input))
- transform = transform.expand(input.shape[0], -1, -1)
- return transform
-
- def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
- ) -> torch.Tensor:
- if self.flags["cropping_mode"] == "resample": # uses bilinear interpolation to crop
- transform = cast(torch.Tensor, transform)
- return crop_by_transform_mat(
- input,
- transform,
- self.flags["size"],
- mode=self.flags["resample"].name.lower(),
- padding_mode="zeros",
- align_corners=self.flags["align_corners"],
- )
- if self.flags["cropping_mode"] == "slice": # uses advanced slicing to crop
- B, C, _, _ = input.shape
- out = torch.empty(B, C, *self.flags["size"], device=input.device, dtype=input.dtype)
- for i in range(B):
- x1 = int(params["src"][i, 0, 0])
- x2 = int(params["src"][i, 1, 0]) + 1
- y1 = int(params["src"][i, 0, 1])
- y2 = int(params["src"][i, 3, 1]) + 1
- out[i] = resize(
- input[i : i + 1, :, y1:y2, x1:x2],
- self.flags["size"],
- interpolation=(self.flags["resample"].name).lower(),
- align_corners=self.flags["align_corners"],
- )
- return out
- raise NotImplementedError(f"Not supported type: {self.flags['cropping_mode']}.")
-
- def inverse_transform(
- self,
- input: torch.Tensor,
- transform: Optional[torch.Tensor] = None,
- size: Optional[Tuple[int, int]] = None,
- **kwargs,
- ) -> torch.Tensor:
- if self.flags["cropping_mode"] != "resample":
- raise NotImplementedError(
- f"`inverse` is only applicable for resample cropping mode. Got {self.flags['cropping_mode']}."
- )
- size = cast(Tuple[int, int], size)
- mode = self.flags["resample"].name.lower() if "mode" not in kwargs else kwargs["mode"]
- align_corners = self.flags["align_corners"] if "align_corners" not in kwargs else kwargs["align_corners"]
- padding_mode = "zeros" if "padding_mode" not in kwargs else kwargs["padding_mode"]
- transform = cast(torch.Tensor, transform)
- return crop_by_transform_mat(input, transform[:, :2, :], size, mode, padding_mode, align_corners)
-
-
-class Normalize(IntensityAugmentationBase2D):
- r"""Normalize tensor images with mean and standard deviation.
-
- .. math::
- \text{input[channel] = (input[channel] - mean[channel]) / std[channel]}
-
- Where `mean` is :math:`(M_1, ..., M_n)` and `std` :math:`(S_1, ..., S_n)` for `n` channels,
-
- Args:
- mean: Mean for each channel.
- std: Standard deviations for each channel.
- return_transform: if ``True`` return the matrix describing the transformation applied to each
- input tensor. If ``False`` and the input is a tuple the applied transformation
- won't be concatenated.
- 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).
-
- Return:
- Normalised tensor with same size as input :math:`(*, C, H, W)`.
-
- .. note::
- This function internally uses :func:`kornia.enhance.normalize`.
-
- Examples:
-
- >>> norm = Normalize(mean=torch.zeros(4), std=torch.ones(4))
- >>> x = torch.rand(1, 4, 3, 3)
- >>> out = norm(x)
- >>> out.shape
- torch.Size([1, 4, 3, 3])
- """
-
- def __init__(
- self,
- mean: Union[torch.Tensor, Tuple[float], List[float], float],
- std: Union[torch.Tensor, Tuple[float], List[float], float],
- return_transform: bool = False,
- p: float = 1.0,
- keepdim: bool = False,
- ) -> None:
- super().__init__(p=p, return_transform=return_transform, same_on_batch=True, keepdim=keepdim)
- if isinstance(mean, float):
- mean = torch.tensor([mean])
-
- if isinstance(std, float):
- std = torch.tensor([std])
-
- if isinstance(mean, (tuple, list)):
- mean = torch.tensor(mean)
-
- if isinstance(std, (tuple, list)):
- std = torch.tensor(std)
-
- self.flags = dict(mean=mean, std=std)
-
- def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
- ) -> torch.Tensor:
- return normalize(input, self.flags["mean"], self.flags["std"])
-
-
-class Denormalize(Normalize):
- r"""Denormalize tensor images with mean and standard deviation.
-
- .. math::
- \text{input[channel] = (input[channel] * std[channel]) + mean[channel]}
-
- Where `mean` is :math:`(M_1, ..., M_n)` and `std` :math:`(S_1, ..., S_n)` for `n` channels,
-
- Args:
- mean: Mean for each channel.
- std: Standard deviations for each channel.
-
- Return:
- Denormalised tensor with same size as input :math:`(*, C, H, W)`.
-
- .. note::
- This function internally uses :func:`kornia.enhance.denormalize`.
-
- Examples:
-
- >>> norm = Denormalize(mean=torch.zeros(1, 4), std=torch.ones(1, 4))
- >>> x = torch.rand(1, 4, 3, 3)
- >>> out = norm(x)
- >>> out.shape
- torch.Size([1, 4, 3, 3])
- """
-
- def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
- ) -> torch.Tensor:
- return denormalize(input, self.flags["mean"], self.flags["std"])
-
-
-class RandomMotionBlur(IntensityAugmentationBase2D):
- r"""Perform motion blur on 2D images (4D tensor).
-
- .. image:: _static/img/RandomMotionBlur.png
-
- Args:
- p: probability of applying the transformation.
- kernel_size: motion kernel size (odd and positive).
- If int, the kernel will have a fixed size.
- If Tuple[int, int], it will randomly generate the value from the range batch-wisely.
- angle: angle of the motion blur in degrees (anti-clockwise rotation).
- If float, it will generate the value from (-angle, angle).
- direction: forward/backward direction of the motion blur.
- Lower values towards -1.0 will point the motion blur towards the back (with angle provided via angle),
- while higher values towards 1.0 will point the motion blur forward. A value of 0.0 leads to a
- uniformly (but still angled) motion blur.
- If float, it will generate the value from (-direction, direction).
- If Tuple[int, int], it will randomly generate the value from the range.
- border_type: the padding mode to be applied before convolving.
- CONSTANT = 0, REFLECT = 1, REPLICATE = 2, CIRCULAR = 3.
- resample: the interpolation mode.
- 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)`, Optional: :math:`(B, 3, 3)`
- - Output: :math:`(B, C, H, W)`
-
- Note:
- Input tensor must be float and normalized into [0, 1] for the best differentiability support.
- Additionally, this function accepts another transformation tensor (:math:`(B, 3, 3)`), then the
- applied transformation will be merged int to the input transformation tensor and returned.
-
- Please set ``resample`` to ``'bilinear'`` if more meaningful gradients wanted.
-
- .. note::
- This function internally uses :func:`kornia.filters.motion_blur`.
-
- Examples:
- >>> rng = torch.manual_seed(0)
- >>> input = torch.ones(1, 1, 5, 5)
- >>> motion_blur = RandomMotionBlur(3, 35., 0.5, p=1.)
- >>> motion_blur(input)
- tensor([[[[0.5773, 1.0000, 1.0000, 1.0000, 0.7561],
- [0.5773, 1.0000, 1.0000, 1.0000, 0.7561],
- [0.5773, 1.0000, 1.0000, 1.0000, 0.7561],
- [0.5773, 1.0000, 1.0000, 1.0000, 0.7561],
- [0.5773, 1.0000, 1.0000, 1.0000, 0.7561]]]])
-
- To apply the exact augmenation again, you may take the advantage of the previous parameter state:
- >>> input = torch.randn(1, 3, 32, 32)
- >>> aug = RandomMotionBlur(3, 35., 0.5, p=1.)
- >>> (aug(input) == aug(input, params=aug._params)).all()
- tensor(True)
- """
-
- def __init__(
- self,
- kernel_size: Union[int, Tuple[int, int]],
- angle: Union[torch.Tensor, float, Tuple[float, float]],
- direction: Union[torch.Tensor, float, Tuple[float, float]],
- border_type: Union[int, str, BorderType] = BorderType.CONSTANT.name,
- resample: Union[str, int, Resample] = Resample.NEAREST.name,
- return_transform: bool = False,
- same_on_batch: bool = False,
- p: float = 0.5,
- keepdim: bool = False,
- ) -> None:
- super().__init__(p=p,
- return_transform=return_transform,
- same_on_batch=same_on_batch,
- keepdim=keepdim)
- self._param_generator = rg.MotionBlurGenerator(kernel_size, angle, direction)
- self.flags = dict(
- border_type=BorderType.get(border_type),
- resample=Resample.get(resample)
- )
-
- def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
- ) -> torch.Tensor:
- kernel_size: int = cast(int, params["ksize_factor"].unique().item())
- angle = params["angle_factor"]
- direction = params["direction_factor"]
- return motion_blur(
- input,
- kernel_size,
- angle,
- direction,
- border_type=self.flags["border_type"].name.lower(),
- mode=self.flags["resample"].name.lower(),
- )
-
-
-class RandomSolarize(IntensityAugmentationBase2D):
- r"""Solarize given tensor image or a batch of tensor images randomly.
-
- .. image:: _static/img/RandomSolarize.png
-
- Args:
- p: probability of applying the transformation.
- thresholds:
- If float x, threshold will be generated from (0.5 - x, 0.5 + x).
- If tuple (x, y), threshold will be generated from (x, y).
- additions:
- If float x, addition will be generated from (-x, x).
- If tuple (x, y), addition will be generated from (x, y).
- same_on_batch: apply the same transformation across the batch.
- return_transform: if ``True`` return the matrix describing the transformation applied to each
- input tensor. If ``False`` and the input is a tuple the applied transformation won't be concatenated.
- 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)`, Optional: :math:`(B, 3, 3)`
- - Output: :math:`(B, C, H, W)`
-
- .. note::
- This function internally uses :func:`kornia.enhance.solarize`.
-
- Examples:
- >>> rng = torch.manual_seed(0)
- >>> input = torch.rand(1, 1, 5, 5)
- >>> solarize = RandomSolarize(0.1, 0.1, p=1.)
- >>> solarize(input)
- tensor([[[[0.4132, 0.1412, 0.1790, 0.2226, 0.3980],
- [0.2754, 0.4194, 0.0130, 0.4538, 0.2771],
- [0.4394, 0.4923, 0.1129, 0.2594, 0.3844],
- [0.3909, 0.2118, 0.1094, 0.2516, 0.3728],
- [0.2278, 0.0000, 0.4876, 0.0353, 0.5100]]]])
-
- To apply the exact augmenation again, you may take the advantage of the previous parameter state:
- >>> input = torch.randn(1, 3, 32, 32)
- >>> aug = RandomSolarize(0.1, 0.1, p=1.)
- >>> (aug(input) == aug(input, params=aug._params)).all()
- tensor(True)
- """
-
- def __init__(
- self,
- thresholds: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.1,
- additions: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.1,
- same_on_batch: bool = False,
- return_transform: bool = False,
- p: float = 0.5,
- keepdim: bool = False,
- ) -> None:
- super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
- self._param_generator = cast(
- rg.PlainUniformGenerator, rg.PlainUniformGenerator(
- (thresholds, "thresholds", 0.5, (0.0, 1.0)),
- (additions, "additions", 0., (-0.5, 0.5)),
- )
- )
-
- def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
- ) -> torch.Tensor:
- thresholds = params["thresholds"]
- additions: Optional[torch.Tensor]
- if "additions" in params:
- additions = params["additions"]
- else:
- additions = None
- return solarize(input, thresholds, additions)
-
-
-class RandomPosterize(IntensityAugmentationBase2D):
- r"""Posterize given tensor image or a batch of tensor images randomly.
-
- .. image:: _static/img/RandomPosterize.png
-
- 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).
- same_on_batch: apply the same transformation across the batch.
- return_transform: if ``True`` return the matrix describing the transformation applied to each
- input tensor. If ``False`` and the input is a tuple the applied transformation won't be concatenated.
- 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)`, Optional: :math:`(B, 3, 3)`
- - Output: :math:`(B, C, H, W)`
-
- .. note::
- This function internally uses :func:`kornia.enhance.posterize`.
-
- Examples:
- >>> rng = torch.manual_seed(0)
- >>> input = torch.rand(1, 1, 5, 5)
- >>> 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]]]])
-
- 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(input) == aug(input, params=aug._params)).all()
- tensor(True)
- """
-
- def __init__(
- self,
- bits: Union[int, Tuple[int, int], torch.Tensor] = 3,
- same_on_batch: bool = False,
- return_transform: bool = False,
- p: float = 0.5,
- keepdim: bool = False,
- ) -> None:
- super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
- self._param_generator = cast(rg.PosterizeGenerator, rg.PosterizeGenerator(bits))
-
- def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
- ) -> torch.Tensor:
- return posterize(input, params["bits_factor"])
-
-
-class RandomSharpness(IntensityAugmentationBase2D):
- r"""Sharpen given tensor image or a batch of tensor images randomly.
-
- .. image:: _static/img/RandomSharpness.png
-
- Args:
- p: probability of applying the transformation.
- sharpness: factor of sharpness strength. Must be above 0.
- same_on_batch: apply the same transformation across the batch.
- return_transform: if ``True`` return the matrix describing the transformation applied to each
- input tensor. If ``False`` and the input is a tuple the applied transformation won't be concatenated.
- 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)`, Optional: :math:`(B, 3, 3)`
- - Output: :math:`(B, C, H, W)`
-
- .. note::
- This function internally uses :func:`kornia.enhance.sharpness`.
-
- Examples:
- >>> rng = torch.manual_seed(0)
- >>> input = torch.rand(1, 1, 5, 5)
- >>> sharpness = RandomSharpness(1., p=1.)
- >>> sharpness(input)
- tensor([[[[0.4963, 0.7682, 0.0885, 0.1320, 0.3074],
- [0.6341, 0.4810, 0.7367, 0.4177, 0.6323],
- [0.3489, 0.4428, 0.1562, 0.2443, 0.2939],
- [0.5185, 0.6462, 0.7050, 0.2288, 0.2823],
- [0.6816, 0.9152, 0.3971, 0.8742, 0.4194]]]])
-
- To apply the exact augmenation again, you may take the advantage of the previous parameter state:
- >>> input = torch.randn(1, 3, 32, 32)
- >>> aug = RandomSharpness(1., p=1.)
- >>> (aug(input) == aug(input, params=aug._params)).all()
- tensor(True)
- """
-
- def __init__(
- self,
- sharpness: Union[torch.Tensor, float, Tuple[float, float], torch.Tensor] = 0.5,
- same_on_batch: bool = False,
- return_transform: bool = False,
- p: float = 0.5,
- keepdim: bool = False,
- ) -> None:
- super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
- self._param_generator = cast(rg.PlainUniformGenerator, rg.PlainUniformGenerator(
- (sharpness, "sharpness", 0., (0, float("inf"))))
- )
-
- def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
- ) -> torch.Tensor:
- factor = params["sharpness"]
- return sharpness(input, factor)
-
-
-class RandomEqualize(IntensityAugmentationBase2D):
- r"""Equalize given tensor image or a batch of tensor images randomly.
-
- .. image:: _static/img/RandomEqualize.png
-
- Args:
- p: Probability to equalize an image.
- same_on_batch: apply the same transformation across the batch.
- return_transform: if ``True`` return the matrix describing the transformation applied to each
- input tensor. If ``False`` and the input is a tuple the applied transformation
- won't be concatenated.
- 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)`, Optional: :math:`(B, 3, 3)`
- - Output: :math:`(B, C, H, W)`
-
- .. note::
- This function internally uses :func:`kornia.enhance.equalize`.
-
- Examples:
- >>> rng = torch.manual_seed(0)
- >>> input = torch.rand(1, 1, 5, 5)
- >>> equalize = RandomEqualize(p=1.)
- >>> equalize(input)
- tensor([[[[0.4963, 0.7682, 0.0885, 0.1320, 0.3074],
- [0.6341, 0.4901, 0.8964, 0.4556, 0.6323],
- [0.3489, 0.4017, 0.0223, 0.1689, 0.2939],
- [0.5185, 0.6977, 0.8000, 0.1610, 0.2823],
- [0.6816, 0.9152, 0.3971, 0.8742, 0.4194]]]])
-
- To apply the exact augmenation again, you may take the advantage of the previous parameter state:
- >>> input = torch.rand(1, 3, 32, 32)
- >>> aug = RandomEqualize(p=1.)
- >>> (aug(input) == aug(input, params=aug._params)).all()
- tensor(True)
- """
-
- def __init__(
- self, same_on_batch: bool = False, return_transform: bool = False, p: float = 0.5, keepdim: bool = False
- ) -> None:
- super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
-
- def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
- ) -> torch.Tensor:
- return equalize(input)
-
-
-class RandomGaussianBlur(IntensityAugmentationBase2D):
- r"""Apply gaussian blur given tensor image or a batch of tensor images randomly.
-
- .. image:: _static/img/RandomGaussianBlur.png
-
- Args:
- kernel_size: the size of the kernel.
- sigma: the standard deviation of the kernel.
- border_type: the padding mode to be applied before convolving.
- The expected modes are: ``constant``, ``reflect``, ``replicate`` or ``circular``.
- return_transform: if ``True`` return the matrix describing the transformation applied to each
- input tensor. If ``False`` and the input is a tuple the applied transformation won't be concatenated.
- same_on_batch: apply the same transformation across the batch.
- p: probability of applying the transformation.
- keepdim: whether to keep the output shape the same as input (True) or broadcast it
- to the batch form (False).
-
- Shape:
- - Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
- - Output: :math:`(B, C, H, W)`
-
- .. note::
- This function internally uses :func:`kornia.filters.gaussian_blur2d`.
-
- Examples:
- >>> rng = torch.manual_seed(0)
- >>> input = torch.rand(1, 1, 5, 5)
- >>> blur = RandomGaussianBlur((3, 3), (0.1, 2.0), p=1.)
- >>> blur(input)
- tensor([[[[0.6699, 0.4645, 0.3193, 0.1741, 0.1955],
- [0.5422, 0.6657, 0.6261, 0.6527, 0.5195],
- [0.3826, 0.2638, 0.1902, 0.1620, 0.2141],
- [0.6329, 0.6732, 0.5634, 0.4037, 0.2049],
- [0.8307, 0.6753, 0.7147, 0.5768, 0.7097]]]])
-
- To apply the exact augmenation again, you may take the advantage of the previous parameter state:
- >>> input = torch.randn(1, 3, 32, 32)
- >>> aug = RandomGaussianBlur((3, 3), (0.1, 2.0), p=1.)
- >>> (aug(input) == aug(input, params=aug._params)).all()
- tensor(True)
- """
-
- def __init__(
- self,
- kernel_size: Tuple[int, int],
- sigma: Tuple[float, float],
- border_type: str = "reflect",
- return_transform: bool = False,
- same_on_batch: bool = False,
- p: float = 0.5,
- keepdim: bool = False
- ) -> None:
- super().__init__(p=p,
- return_transform=return_transform,
- same_on_batch=same_on_batch,
- p_batch=1.0,
- keepdim=keepdim)
- self.flags = dict(
- kernel_size=kernel_size,
- sigma=sigma,
- border_type=BorderType.get(border_type),
- )
-
- def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
- ) -> torch.Tensor:
- return gaussian_blur2d(
- input, self.flags["kernel_size"], self.flags["sigma"], self.flags["border_type"].name.lower())
-
-
-class RandomInvert(IntensityAugmentationBase2D):
- r"""Invert the tensor images values randomly.
-
- .. image:: _static/img/RandomInvert.png
-
- Args:
- max_val: The expected maximum value in the input tensor. The shape has to
- according to the input tensor shape, or at least has to work with broadcasting.
- return_transform: if ``True`` return the matrix describing the transformation applied to each
- input tensor. If ``False`` and the input is a tuple the applied transformation won't be concatenated.
- same_on_batch: apply the same transformation across the batch.
- p: probability of applying the transformation.
- keepdim: whether to keep the output shape the same as input (True) or broadcast it
- to the batch form (False).
- .. note::
- This function internally uses :func:`kornia.enhance.invert`.
-
- Examples:
- >>> rng = torch.manual_seed(0)
- >>> img = torch.rand(1, 1, 5, 5)
- >>> inv = RandomInvert()
- >>> inv(img)
- tensor([[[[0.4963, 0.7682, 0.0885, 0.1320, 0.3074],
- [0.6341, 0.4901, 0.8964, 0.4556, 0.6323],
- [0.3489, 0.4017, 0.0223, 0.1689, 0.2939],
- [0.5185, 0.6977, 0.8000, 0.1610, 0.2823],
- [0.6816, 0.9152, 0.3971, 0.8742, 0.4194]]]])
-
- To apply the exact augmenation again, you may take the advantage of the previous parameter state:
- >>> input = torch.randn(1, 3, 32, 32)
- >>> aug = RandomInvert(p=1.)
- >>> (aug(input) == aug(input, params=aug._params)).all()
- tensor(True)
- """
-
- def __init__(
- self,
- max_val: Union[float, torch.Tensor] = torch.tensor(1.0),
- return_transform: bool = False,
- same_on_batch: bool = False,
- p: float = 0.5,
- keepdim: bool = False
- ) -> None:
- super().__init__(p=p,
- return_transform=return_transform,
- same_on_batch=same_on_batch,
- p_batch=1.0,
- keepdim=keepdim)
- self.flags = dict(
- max_val=max_val,
- )
-
- def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
- ) -> torch.Tensor:
- return invert(input, torch.as_tensor(self.flags["max_val"], device=input.device, dtype=input.dtype))
-
-
-class RandomChannelShuffle(IntensityAugmentationBase2D):
- r"""Shuffle the channels of a batch of multi-dimensional images.
-
- .. image:: _static/img/RandomChannelShuffle.png
-
- Args:
- return_transform: if ``True`` return the matrix describing the transformation applied to each
- input tensor. If ``False`` and the input is a tuple the applied transformation won't be concatenated.
- same_on_batch: apply the same transformation across the batch.
- p: probability of applying the transformation.
-
- Examples:
- >>> rng = torch.manual_seed(0)
- >>> img = torch.arange(1*2*2*2.).view(1,2,2,2)
- >>> RandomChannelShuffle()(img)
- tensor([[[[4., 5.],
- [6., 7.]],
- <BLANKLINE>
- [[0., 1.],
- [2., 3.]]]])
-
- To apply the exact augmenation again, you may take the advantage of the previous parameter state:
- >>> input = torch.randn(1, 3, 32, 32)
- >>> aug = RandomChannelShuffle(p=1.)
- >>> (aug(input) == aug(input, params=aug._params)).all()
- tensor(True)
- """
-
- def __init__(self,
- return_transform: bool = False,
- same_on_batch: bool = False,
- p: float = 0.5,
- keepdim: bool = False) -> None:
- super().__init__(p=p,
- return_transform=return_transform,
- same_on_batch=same_on_batch,
- p_batch=1.0,
- keepdim=keepdim)
-
- def generate_parameters(self, shape: torch.Size) -> Dict[str, torch.Tensor]:
- B, C, _, _ = shape
- channels = torch.rand(B, C).argsort(dim=1)
- return dict(channels=channels)
-
- def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
- ) -> torch.Tensor:
- out = torch.empty_like(input)
- for i in range(out.shape[0]):
- out[i] = input[i, params["channels"][i]]
- return out
-
-
-class RandomGaussianNoise(IntensityAugmentationBase2D):
- r"""Add gaussian noise to a batch of multi-dimensional images.
-
- .. image:: _static/img/RandomGaussianNoise.png
-
- Args:
- mean: The mean of the gaussian distribution.
- std: The standard deviation of the gaussian distribution.
- return_transform: if ``True`` return the matrix describing the transformation applied to each
- input tensor. If ``False`` and the input is a tuple the applied transformation won't be concatenated.
- same_on_batch: apply the same transformation across the batch.
- p: probability of applying the transformation.
- keepdim: whether to keep the output shape the same as input (True) or broadcast it
- to the batch form (False).
- Examples:
- >>> rng = torch.manual_seed(0)
- >>> img = torch.ones(1, 1, 2, 2)
- >>> RandomGaussianNoise(mean=0., std=1., p=1.)(img)
- tensor([[[[ 2.5410, 0.7066],
- [-1.1788, 1.5684]]]])
-
- To apply the exact augmenation again, you may take the advantage of the previous parameter state:
- >>> input = torch.randn(1, 3, 32, 32)
- >>> aug = RandomGaussianNoise(mean=0., std=1., p=1.)
- >>> (aug(input) == aug(input, params=aug._params)).all()
- tensor(True)
- """
-
- def __init__(
- self,
- mean: float = 0.0,
- std: float = 1.0,
- return_transform: bool = False,
- same_on_batch: bool = False,
- p: float = 0.5,
- keepdim: bool = False
- ) -> None:
- super().__init__(p=p,
- return_transform=return_transform,
- same_on_batch=same_on_batch,
- p_batch=1.0,
- keepdim=keepdim)
- self.flags = dict(mean=mean, std=std)
-
- def generate_parameters(self, shape: torch.Size) -> Dict[str, torch.Tensor]:
- noise = torch.randn(shape)
- return dict(noise=noise)
-
- def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
- ) -> torch.Tensor:
- return input + params["noise"].to(input.device) * self.flags["std"] + self.flags["mean"]
-
-
-class RandomFisheye(GeometricAugmentationBase2D):
- r"""Add random camera radial distortion.
-
- .. image:: _static/img/RandomFisheye.png
-
- Args:
- center_x: Ranges to sample respect to x-coordinate center with shape (2,).
- center_y: Ranges to sample respect to y-coordinate center with shape (2,).
- gamma: Ranges to sample for the gamma values respect to optical center with shape (2,).
- return_transform: if ``True`` return the matrix describing the transformation applied to each
- input tensor. If ``False`` and the input is a tuple the applied transformation won't be concatenated.
- same_on_batch: apply the same transformation across the batch.
- p: probability of applying the transformation.
- keepdim: whether to keep the output shape the same as input (True) or broadcast it
- to the batch form (False).
- Examples:
- >>> img = torch.ones(1, 1, 2, 2)
- >>> center_x = torch.tensor([-.3, .3])
- >>> center_y = torch.tensor([-.3, .3])
- >>> gamma = torch.tensor([.9, 1.])
- >>> out = RandomFisheye(center_x, center_y, gamma)(img)
- >>> out.shape
- torch.Size([1, 1, 2, 2])
-
- To apply the exact augmenation again, you may take the advantage of the previous parameter state:
- >>> input = torch.randn(1, 3, 32, 32)
- >>> aug = RandomFisheye(center_x, center_y, gamma, p=1.)
- >>> (aug(input) == aug(input, params=aug._params)).all()
- tensor(True)
- """
-
- def __init__(
- self,
- center_x: torch.Tensor,
- center_y: torch.Tensor,
- gamma: torch.Tensor,
- return_transform: bool = False,
- same_on_batch: bool = False,
- p: float = 0.5,
- keepdim: bool = False
- ) -> None:
- super().__init__(p=p,
- return_transform=return_transform,
- same_on_batch=same_on_batch,
- p_batch=1.0,
- keepdim=keepdim)
- self._check_tensor(center_x)
- self._check_tensor(center_y)
- self._check_tensor(gamma)
- self._param_generator = cast(
- rg.PlainUniformGenerator, rg.PlainUniformGenerator(
- (center_x[:, None], "center_x", None, None),
- (center_y[:, None], "center_y", None, None),
- (gamma[:, None], "gamma", None, None),
- )
- )
-
- def _check_tensor(self, data: torch.Tensor) -> None:
- if not isinstance(data, torch.Tensor):
- raise TypeError(f"Invalid input type. Expected torch.Tensor - got: {type(data)}")
-
- if len(data.shape) != 1 and data.shape[0] != 2:
- raise ValueError(f"Tensor must be of shape (2,). Got: {data.shape}.")
-
- # TODO: It is incorrect to return identity
- def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
- return self.identity_matrix(input)
-
- def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
- ) -> torch.Tensor:
- # create the initial sampling fields
- B, _, H, W = input.shape
- grid = create_meshgrid(H, W, normalized_coordinates=True)
- field_x = grid[..., 0].to(input) # 1xHxW
- field_y = grid[..., 1].to(input) # 1xHxW
- # vectorize the random parameters
- center_x = params["center_x"].view(B, 1, 1).to(input)
- center_y = params["center_y"].view(B, 1, 1).to(input)
- gamma = params["gamma"].view(B, 1, 1).to(input)
- # compute and apply the distances respect to the camera optical center
- distance = ((center_x - field_x) ** 2 + (center_y - field_y) ** 2) ** 0.5
- field_x = field_x + field_x * distance ** gamma # BxHxw
- field_y = field_y + field_y * distance ** gamma # BxHxW
- return remap(input, field_x, field_y, normalized_coordinates=True, align_corners=True)
-
-
-class RandomElasticTransform(GeometricAugmentationBase2D):
- r"""Add random elastic transformation to a tensor image.
-
- .. image:: _static/img/RandomElasticTransform.png
-
- Args:
- kernel_size: the size of the Gaussian kernel.
- sigma: The standard deviation of the Gaussian in the y and x directions,
- respectively. Larger sigma results in smaller pixel displacements.
- alpha: The scaling factor that controls the intensity of the deformation
- in the y and x directions, respectively.
- align_corners: Interpolation flag used by `grid_sample`.
- mode: Interpolation mode used by `grid_sample`. Either 'bilinear' or 'nearest'.
- padding_mode: The padding used by ```grid_sample```. Either 'zeros', 'border' or 'refection'.
-
- return_transform: if ``True`` return the matrix describing the transformation applied to each
- input tensor. If ``False`` and the input is a tuple the applied transformation won't be concatenated.
- same_on_batch: apply the same transformation across the batch.
- p: probability of applying the transformation.
-
- .. note::
- This function internally uses :func:`kornia.geometry.transform.elastic_transform2d`.
-
- Examples:
- >>> img = torch.ones(1, 1, 2, 2)
- >>> out = RandomElasticTransform()(img)
- >>> out.shape
- torch.Size([1, 1, 2, 2])
-
- To apply the exact augmenation again, you may take the advantage of the previous parameter state:
- >>> input = torch.randn(1, 3, 32, 32)
- >>> aug = RandomElasticTransform(p=1.)
- >>> (aug(input) == aug(input, params=aug._params)).all()
- tensor(True)
- """
-
- def __init__(
- self,
- kernel_size: Tuple[int, int] = (63, 63),
- sigma: Tuple[float, float] = (32.0, 32.0),
- alpha: Tuple[float, float] = (1.0, 1.0),
- align_corners: bool = False,
- mode: str = "bilinear",
- padding_mode: str = "zeros",
- return_transform: bool = False,
- same_on_batch: bool = False,
- p: float = 0.5,
- keepdim: bool = False
- ) -> None:
- super().__init__(p=p,
- return_transform=return_transform,
- same_on_batch=same_on_batch,
- p_batch=1.0,
- keepdim=keepdim)
- self.flags = dict(
- kernel_size=kernel_size,
- sigma=sigma,
- alpha=alpha,
- align_corners=align_corners,
- mode=mode,
- padding_mode=padding_mode,
- )
-
- def generate_parameters(self, shape: torch.Size) -> Dict[str, torch.Tensor]:
- B, _, H, W = shape
- if self.same_on_batch:
- noise = torch.rand(1, 2, H, W, device=self.device, dtype=self.dtype).repeat(B, 1, 1, 1)
- else:
- noise = torch.rand(B, 2, H, W, device=self.device, dtype=self.dtype)
- return dict(noise=noise * 2 - 1)
-
- # TODO: It is incorrect to return identity
- def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
- return self.identity_matrix(input)
-
- def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
- ) -> torch.Tensor:
- return elastic_transform2d(
- input, params["noise"].to(input), self.flags["kernel_size"], self.flags["sigma"],
- self.flags["alpha"], self.flags["align_corners"], self.flags["mode"], self.flags["padding_mode"]
- )
-
-
-class RandomThinPlateSpline(GeometricAugmentationBase2D):
- r"""Add random noise to the Thin Plate Spline algorithm.
-
- .. image:: _static/img/RandomThinPlateSpline.png
-
- Args:
- scale: the scale factor to apply to the destination points.
- align_corners: Interpolation flag used by ``grid_sample``.
- mode: Interpolation mode used by `grid_sample`. Either 'bilinear' or 'nearest'.
- return_transform: if ``True`` return the matrix describing the transformation applied to each
- input tensor. If ``False`` and the input is a tuple the applied transformation won't be concatenated.
- same_on_batch: apply the same transformation across the batch.
- p: probability of applying the transformation.
- keepdim: whether to keep the output shape the same as input (True) or broadcast it
- to the batch form (False).
- .. note::
- This function internally uses :func:`kornia.geometry.transform.warp_image_tps`.
-
- Examples:
- >>> img = torch.ones(1, 1, 2, 2)
- >>> out = RandomThinPlateSpline()(img)
- >>> out.shape
- torch.Size([1, 1, 2, 2])
-
- To apply the exact augmenation again, you may take the advantage of the previous parameter state:
- >>> input = torch.randn(1, 3, 32, 32)
- >>> aug = RandomThinPlateSpline(p=1.)
- >>> (aug(input) == aug(input, params=aug._params)).all()
- tensor(True)
- """
-
- def __init__(
- self,
- scale: float = 0.2,
- align_corners: bool = False,
- return_transform: bool = False,
- same_on_batch: bool = False,
- p: float = 0.5,
- keepdim: bool = False
- ) -> None:
- super().__init__(p=p,
- return_transform=return_transform,
- same_on_batch=same_on_batch,
- p_batch=1.0,
- keepdim=keepdim)
- self.flags = dict(align_corners=align_corners)
- self.dist = torch.distributions.Uniform(-scale, scale)
-
- def generate_parameters(self, shape: torch.Size) -> Dict[str, torch.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]]]).repeat(B, 1, 1) # Bx5x2
- dst = src + self.dist.rsample(src.shape)
- return dict(src=src, dst=dst)
-
- # TODO: It is incorrect to return identity
- def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
- return self.identity_matrix(input)
-
- def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
- ) -> torch.Tensor:
- src = params["src"].to(input)
- dst = params["dst"].to(input)
- # NOTE: warp_image_tps need to use inverse parameters
- kernel, affine = get_tps_transform(dst, src)
- return warp_image_tps(input, src, kernel, affine, self.flags["align_corners"])
-
-
-class RandomBoxBlur(IntensityAugmentationBase2D):
- """Add random blur with a box filter to an image tensor.
-
- .. image:: _static/img/RandomBoxBlur.png
-
- Args:
- kernel_size: the blurring kernel size.
- border_type: the padding mode to be applied before convolving.
- The expected modes are: ``constant``, ``reflect``, ``replicate`` or ``circular``.
- normalized: if True, L1 norm of the kernel is set to 1.
- return_transform: if ``True`` return the matrix describing the transformation applied to each
- input tensor. If ``False`` and the input is a tuple the applied transformation won't be concatenated.
- same_on_batch (bool): apply the same transformation across the batch.
- p: probability of applying the transformation.
- keepdim: whether to keep the output shape the same as input (True) or broadcast it
- to the batch form (False).
- .. note::
- This function internally uses :func:`kornia.filters.box_blur`.
-
- Examples:
- >>> img = torch.ones(1, 1, 24, 24)
- >>> out = RandomBoxBlur((7, 7))(img)
- >>> out.shape
- torch.Size([1, 1, 24, 24])
-
- To apply the exact augmenation again, you may take the advantage of the previous parameter state:
- >>> input = torch.randn(1, 3, 32, 32)
- >>> aug = RandomBoxBlur((7, 7), p=1.)
- >>> (aug(input) == aug(input, params=aug._params)).all()
- tensor(True)
- """
-
- def __init__(
- self,
- kernel_size: Tuple[int, int] = (3, 3),
- border_type: str = "reflect",
- normalized: bool = True,
- return_transform: bool = False,
- same_on_batch: bool = False,
- p: float = 0.5,
- keepdim: bool = False
- ) -> None:
- super().__init__(p=p,
- return_transform=return_transform,
- same_on_batch=same_on_batch, p_batch=1.0,
- keepdim=keepdim)
- self.flags = dict(
- kernel_size=kernel_size,
- border_type=border_type,
- normalized=normalized,
- )
-
- def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
- return self.identity_matrix(input)
-
- def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
- ) -> torch.Tensor:
- return box_blur(input, self.flags["kernel_size"], self.flags["border_type"], self.flags["normalized"])
-
-
-class PadTo(GeometricAugmentationBase2D):
- r"""Pad the given sample to a specific size.
-
- Args:
- size: a tuple of ints in the format (height, width) that give the spatial
- dimensions to pad inputs to.
- pad_mode: the type of padding to perform on the image (valid values
- are those accepted by torch.nn.functional.pad)
- pad_value: fill value for 'constant' padding applied to the image
- p: probability of the image being flipped.
- return_transform: if ``True`` return the matrix describing the transformation applied to each
- input tensor. If ``False`` and the input is a tuple the applied transformation
- won't be concatenated.
- 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)`, Optional: :math:`(B, 3, 3)`
- - Output: :math:`(B, C, H, W)`
-
- .. note::
- This function internally uses :func:`torch.nn.functional.pad`.
-
- Examples:
- >>> img = torch.tensor([[[[0., 0., 0.],
- ... [0., 0., 0.],
- ... [0., 0., 0.]]]])
- >>> pad = PadTo((4, 5), pad_value=1.)
- >>> out = pad(img)
- >>> out
- tensor([[[[0., 0., 0., 1., 1.],
- [0., 0., 0., 1., 1.],
- [0., 0., 0., 1., 1.],
- [1., 1., 1., 1., 1.]]]])
- >>> pad.inverse(out)
- tensor([[[[0., 0., 0.],
- [0., 0., 0.],
- [0., 0., 0.]]]])
- """
- def __init__(
- self,
- size: Tuple[int, int],
- pad_mode: str = "constant",
- pad_value: Union[int, float] = 0,
- return_transform: bool = False,
- keepdim: bool = False
- ) -> None:
- super().__init__(p=1.,
- return_transform=return_transform,
- same_on_batch=True,
- p_batch=1.,
- keepdim=keepdim)
- self.flags = dict(
- size=size,
- pad_mode=pad_mode,
- pad_value=pad_value,
- )
-
- # TODO: It is incorrect to return identity
- # TODO: Having a resampled version with ``warp_affine``
- def compute_transformation(self, image: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
- return self.identity_matrix(image)
-
- def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
- ) -> torch.Tensor:
- _, _, height, width = input.shape
- height_pad: int = self.flags["size"][0] - height
- width_pad: int = self.flags["size"][1] - width
- return torch.nn.functional.pad(
- input, [0, width_pad, 0, height_pad], mode=self.flags["pad_mode"], value=self.flags["pad_value"])
-
- def inverse_transform(
- self,
- input: torch.Tensor,
- transform: Optional[torch.Tensor] = None,
- size: Optional[Tuple[int, int]] = None,
- **kwargs
- ) -> torch.Tensor:
- size = cast(Tuple[int, int], size)
- return input[..., :size[0], :size[1]]
diff --git a/kornia/augmentation/augmentation3d.py b/kornia/augmentation/augmentation3d.py
deleted file mode 100644
index bad2d007e..000000000
--- a/kornia/augmentation/augmentation3d.py
+++ /dev/null
@@ -1,978 +0,0 @@
-from typing import cast, Dict, Optional, Tuple, Union
-
-import torch
-from torch.nn.functional import pad
-
-from kornia.constants import BorderType, Resample
-from kornia.enhance import equalize3d
-from kornia.filters import motion_blur3d
-from kornia.geometry import (
- affine3d,
- crop_by_transform_mat3d,
- deg2rad,
- get_affine_matrix3d,
- get_perspective_transform3d,
- warp_affine3d,
- warp_perspective3d,
-)
-from kornia.geometry.transform.affwarp import _compute_rotation_matrix3d, _compute_tensor_center3d
-
-from . import random_generator as rg
-from .base import AugmentationBase3D, TensorWithTransformMat
-
-
-class RandomHorizontalFlip3D(AugmentationBase3D):
- r"""Apply random horizontal flip to 3D volumes (5D tensor).
-
- Args:
- p: probability of the image being flipped.
- return_transform: if ``True`` return the matrix describing the transformation applied to each
- input tensor. If ``False`` and the input is a tuple the applied transformation
- won't be concatenated.
- 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, D, H, W)` or :math:`(B, C, D, H, W)`, Optional: :math:`(B, 4, 4)`
- - Output: :math:`(B, C, D, H, W)`
-
- Note:
- Input tensor must be float and normalized into [0, 1] for the best differentiability support.
- Additionally, this function accepts another transformation tensor (:math:`(B, 4, 4)`), then the
- applied transformation will be merged int to the input transformation tensor and returned.
-
- Examples:
- >>> x = torch.eye(3).repeat(3, 1, 1)
- >>> seq = RandomHorizontalFlip3D(p=1.0, return_transform=True)
- >>> seq(x)
- (tensor([[[[[0., 0., 1.],
- [0., 1., 0.],
- [1., 0., 0.]],
- <BLANKLINE>
- [[0., 0., 1.],
- [0., 1., 0.],
- [1., 0., 0.]],
- <BLANKLINE>
- [[0., 0., 1.],
- [0., 1., 0.],
- [1., 0., 0.]]]]]), tensor([[[-1., 0., 0., 2.],
- [ 0., 1., 0., 0.],
- [ 0., 0., 1., 0.],
- [ 0., 0., 0., 1.]]]))
-
- To apply the exact augmenation again, you may take the advantage of the previous parameter state:
- >>> input = torch.rand(1, 3, 32, 32, 32)
- >>> aug = RandomHorizontalFlip3D(p=1.)
- >>> (aug(input) == aug(input, params=aug._params)).all()
- tensor(True)
- """
-
- def __init__(
- self, return_transform: bool = False, same_on_batch: bool = False, p: float = 0.5, keepdim: bool = False
- ) -> None:
- super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
-
- def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
- w: int = input.shape[-1]
- flip_mat: torch.Tensor = torch.tensor(
- [[-1, 0, 0, w - 1], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]], device=input.device, dtype=input.dtype
- )
- return flip_mat.repeat(input.size(0), 1, 1)
-
- def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
- ) -> torch.Tensor:
- return torch.flip(input, [-1])
-
-
-class RandomVerticalFlip3D(AugmentationBase3D):
- r"""Apply random vertical flip to 3D volumes (5D tensor).
-
- Input should be a tensor of shape :math:`(C, D, H, W)` or a batch of tensors :math:`(*, C, D, H, W)`.
- If Input is a tuple it is assumed that the first element contains the aforementioned tensors and the second,
- the corresponding transformation matrix that has been applied to them. In this case the module
- will Vertically flip the tensors and concatenate the corresponding transformation matrix to the
- previous one. This is especially useful when using this functionality as part of an ``nn.Sequential`` module.
-
- Args:
- p: probability of the image being flipped.
- return_transform: if ``True`` return the matrix describing the transformation applied to each
- input tensor. If ``False`` and the input is a tuple the applied transformation
- won't be concatenated.
- 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, D, H, W)` or :math:`(B, C, D, H, W)`, Optional: :math:`(B, 4, 4)`
- - Output: :math:`(B, C, D, H, W)`
-
- Note:
- Input tensor must be float and normalized into [0, 1] for the best differentiability support.
- Additionally, this function accepts another transformation tensor (:math:`(B, 4, 4)`), then the
- applied transformation will be merged int to the input transformation tensor and returned.
-
- Examples:
- >>> x = torch.eye(3).repeat(3, 1, 1)
- >>> seq = RandomVerticalFlip3D(p=1.0, return_transform=True)
- >>> seq(x)
- (tensor([[[[[0., 0., 1.],
- [0., 1., 0.],
- [1., 0., 0.]],
- <BLANKLINE>
- [[0., 0., 1.],
- [0., 1., 0.],
- [1., 0., 0.]],
- <BLANKLINE>
- [[0., 0., 1.],
- [0., 1., 0.],
- [1., 0., 0.]]]]]), tensor([[[ 1., 0., 0., 0.],
- [ 0., -1., 0., 2.],
- [ 0., 0., 1., 0.],
- [ 0., 0., 0., 1.]]]))
-
- To apply the exact augmenation again, you may take the advantage of the previous parameter state:
- >>> input = torch.rand(1, 3, 32, 32, 32)
- >>> aug = RandomVerticalFlip3D(p=1.)
- >>> (aug(input) == aug(input, params=aug._params)).all()
- tensor(True)
- """
-
- def __init__(
- self, return_transform: bool = False, same_on_batch: bool = False, p: float = 0.5, keepdim: bool = False
- ) -> None:
- super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
-
- def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
- h: int = input.shape[-2]
- flip_mat: torch.Tensor = torch.tensor(
- [[1, 0, 0, 0], [0, -1, 0, h - 1], [0, 0, 1, 0], [0, 0, 0, 1]], device=input.device, dtype=input.dtype
- )
- return flip_mat.repeat(input.size(0), 1, 1)
-
- def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
- ) -> torch.Tensor:
- return torch.flip(input, [-2])
-
-
-class RandomDepthicalFlip3D(AugmentationBase3D):
- r"""Apply random flip along the depth axis of 3D volumes (5D tensor).
-
- Input should be a tensor of shape :math:`(C, D, H, W)` or a batch of tensors :math:`(*, C, D, H, W)`.
- If Input is a tuple it is assumed that the first element contains the aforementioned tensors and the second,
- the corresponding transformation matrix that has been applied to them. In this case the module
- will Depthically flip the tensors and concatenate the corresponding transformation matrix to the
- previous one. This is especially useful when using this functionality as part of an ``nn.Sequential`` module.
-
- Args:
- p: probability of the image being flipped.
- return_transform: if ``True`` return the matrix describing the transformation applied to each
- input tensor. If ``False`` and the input is a tuple the applied transformation
- won't be concatenated.
- 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, D, H, W)` or :math:`(B, C, D, H, W)`, Optional: :math:`(B, 4, 4)`
- - Output: :math:`(B, C, D, H, W)`
-
- Note:
- Input tensor must be float and normalized into [0, 1] for the best differentiability support.
- Additionally, this function accepts another transformation tensor (:math:`(B, 4, 4)`), then the
- applied transformation will be merged int to the input transformation tensor and returned.
-
- Examples:
- >>> x = torch.eye(3).repeat(3, 1, 1)
- >>> seq = RandomDepthicalFlip3D(p=1.0, return_transform=True)
- >>> seq(x)
- (tensor([[[[[1., 0., 0.],
- [0., 1., 0.],
- [0., 0., 1.]],
- <BLANKLINE>
- [[1., 0., 0.],
- [0., 1., 0.],
- [0., 0., 1.]],
- <BLANKLINE>
- [[1., 0., 0.],
- [0., 1., 0.],
- [0., 0., 1.]]]]]), tensor([[[ 1., 0., 0., 0.],
- [ 0., 1., 0., 0.],
- [ 0., 0., -1., 2.],
- [ 0., 0., 0., 1.]]]))
-
- To apply the exact augmenation again, you may take the advantage of the previous parameter state:
- >>> input = torch.rand(1, 3, 32, 32, 32)
- >>> aug = RandomDepthicalFlip3D(p=1.)
- >>> (aug(input) == aug(input, params=aug._params)).all()
- tensor(True)
-
- """
-
- def __init__(
- self, return_transform: bool = False, same_on_batch: bool = False, p: float = 0.5, keepdim: bool = False
- ) -> None:
- super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
-
- def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
- d: int = input.shape[-3]
- flip_mat: torch.Tensor = torch.tensor(
- [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, -1, d - 1], [0, 0, 0, 1]], device=input.device, dtype=input.dtype
- )
- return flip_mat.repeat(input.size(0), 1, 1)
-
- def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
- ) -> torch.Tensor:
- return torch.flip(input, [-3])
-
-
-class RandomAffine3D(AugmentationBase3D):
- r"""Apply affine transformation 3D volumes (5D tensor).
-
- The transformation is computed so that the center is kept invariant.
-
- Args:
- degrees: Range of yaw (x-axis), pitch (y-axis), roll (z-axis) to select from.
- If degrees is a number, then yaw, pitch, roll will be generated from the range of (-degrees, +degrees).
- If degrees is a tuple of (min, max), then yaw, pitch, roll will be generated from the range of (min, max).
- If degrees is a list of floats [a, b, c], then yaw, pitch, roll will be generated from (-a, a), (-b, b)
- and (-c, c).
- If degrees is a list of tuple ((a, b), (m, n), (x, y)), then yaw, pitch, roll will be generated from
- (a, b), (m, n) and (x, y).
- Set to 0 to deactivate rotations.
- translate: tuple of maximum absolute fraction for horizontal, vertical and
- depthical translations (dx,dy,dz). For example translate=(a, b, c), then
- horizontal shift will be randomly sampled in the range -img_width * a < dx < img_width * a
- vertical shift will be randomly sampled in the range -img_height * b < dy < img_height * b.
- depthical shift will be randomly sampled in the range -img_depth * c < dz < img_depth * c.
- Will not translate by default.
- scale: scaling factor interval.
- If (a, b) represents isotropic scaling, the scale is randomly sampled from the range a <= scale <= b.
- If ((a, b), (c, d), (e, f)), the scale is randomly sampled from the range a <= scale_x <= b,
- c <= scale_y <= d, e <= scale_z <= f. Will keep original scale by default.
- shears: Range of degrees to select from.
- If shear is a number, a shear to the 6 facets in the range (-shear, +shear) will be applied.
- If shear is a tuple of 2 values, a shear to the 6 facets in the range (shear[0], shear[1]) will be applied.
- If shear is a tuple of 6 values, a shear to the i-th facet in the range (-shear[i], shear[i])
- will be applied.
- If shear is a tuple of 6 tuples, a shear to the i-th facet in the range (-shear[i, 0], shear[i, 1])
- will be applied.
- resample:
- return_transform: if ``True`` return the matrix describing the transformation
- applied to each.
- same_on_batch: apply the same transformation across the batch.
- align_corners: interpolation flag.
- keepdim: whether to keep the output shape the same as input (True) or broadcast it
- to the batch form (False). Default: False.
-
- Shape:
- - Input: :math:`(C, D, H, W)` or :math:`(B, C, D, H, W)`, Optional: :math:`(B, 4, 4)`
- - Output: :math:`(B, C, D, H, W)`
-
- Note:
- Input tensor must be float and normalized into [0, 1] for the best differentiability support.
- Additionally, this function accepts another transformation tensor (:math:`(B, 4, 4)`), then the
- applied transformation will be merged int to the input transformation tensor and returned.
-
- Examples:
- >>> rng = torch.manual_seed(0)
- >>> input = torch.rand(1, 1, 3, 3, 3)
- >>> aug = RandomAffine3D((15., 20., 20.), p=1., return_transform=True)
- >>> aug(input)
- (tensor([[[[[0.4503, 0.4763, 0.1680],
- [0.2029, 0.4267, 0.3515],
- [0.3195, 0.5436, 0.3706]],
- <BLANKLINE>
- [[0.5255, 0.3508, 0.4858],
- [0.0795, 0.1689, 0.4220],
- [0.5306, 0.7234, 0.6879]],
- <BLANKLINE>
- [[0.2971, 0.2746, 0.3471],
- [0.4924, 0.4960, 0.6460],
- [0.3187, 0.4556, 0.7596]]]]]), tensor([[[ 0.9722, -0.0603, 0.2262, -0.1381],
- [ 0.1131, 0.9669, -0.2286, 0.1486],
- [-0.2049, 0.2478, 0.9469, 0.0102],
- [ 0.0000, 0.0000, 0.0000, 1.0000]]]))
-
- To apply the exact augmenation again, you may take the advantage of the previous parameter state:
- >>> input = torch.rand(1, 3, 32, 32, 32)
- >>> aug = RandomAffine3D((15., 20., 20.), p=1.)
- >>> (aug(input) == aug(input, params=aug._params)).all()
- tensor(True)
- """
-
- def __init__(
- self,
- degrees: Union[
- torch.Tensor,
- float,
- Tuple[float, float],
- Tuple[float, float, float],
- Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float]],
- ],
- translate: Optional[Union[torch.Tensor, Tuple[float, float, float]]] = None,
- scale: Optional[
- Union[
- torch.Tensor, Tuple[float, float], Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float]]
- ]
- ] = None,
- shears: Union[
- torch.Tensor,
- float,
- Tuple[float, float],
- Tuple[float, float, float, float, float, float],
- Tuple[
- Tuple[float, float],
- Tuple[float, float],
- Tuple[float, float],
- Tuple[float, float],
- Tuple[float, float],
- Tuple[float, float],
- ],
- ] = None,
- resample: Union[str, int, Resample] = Resample.BILINEAR.name,
- return_transform: bool = False,
- same_on_batch: bool = False,
- align_corners: bool = False,
- p: float = 0.5,
- keepdim: bool = False,
- ) -> None:
- super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
- self.degrees = degrees
- self.shears = shears
- self.translate = translate
- self.scale = scale
-
- self.flags = dict(
- resample=Resample.get(resample),
- align_corners=align_corners
- )
- self._param_generator = cast(rg.AffineGenerator3D, rg.AffineGenerator3D(degrees, translate, scale, shears))
-
- def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
- transform: torch.Tensor = get_affine_matrix3d(
- params["translations"],
- params["center"],
- params["scale"],
- params["angles"],
- deg2rad(params["sxy"]),
- deg2rad(params["sxz"]),
- deg2rad(params["syx"]),
- deg2rad(params["syz"]),
- deg2rad(params["szx"]),
- deg2rad(params["szy"]),
- ).to(input)
- return transform
-
- def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
- ) -> torch.Tensor:
- transform = cast(torch.Tensor, transform)
- return warp_affine3d(
- input,
- transform[:, :3, :],
- (input.shape[-3], input.shape[-2], input.shape[-1]),
- self.flags["resample"].name.lower(),
- align_corners=self.flags["align_corners"],
- )
-
-
-class RandomRotation3D(AugmentationBase3D):
- r"""Apply random rotations to 3D volumes (5D tensor).
-
- Input should be a tensor of shape (C, D, H, W) or a batch of tensors :math:`(B, C, D, H, W)`.
- If Input is a tuple it is assumed that the first element contains the aforementioned tensors and the second,
- the corresponding transformation matrix that has been applied to them. In this case the module
- will rotate the tensors and concatenate the corresponding transformation matrix to the
- previous one. This is especially useful when using this functionality as part of an ``nn.Sequential`` module.
-
- Args:
- degrees: Range of degrees to select from.
- If degrees is a number, then yaw, pitch, roll will be generated from the range of (-degrees, +degrees).
- If degrees is a tuple of (min, max), then yaw, pitch, roll will be generated from the range of (min, max).
- If degrees is a list of floats [a, b, c], then yaw, pitch, roll will be generated from (-a, a), (-b, b)
- and (-c, c).
- If degrees is a list of tuple ((a, b), (m, n), (x, y)), then yaw, pitch, roll will be generated from
- (a, b), (m, n) and (x, y).
- Set to 0 to deactivate rotations.
- resample:
- return_transform: if ``True`` return the matrix describing the transformation applied to each
- input tensor. If ``False`` and the input is a tuple the applied transformation won't be concatenated.
- same_on_batch: apply the same transformation across the batch.
- align_corners: interpolation flag.
- keepdim: whether to keep the output shape the same as input (True) or broadcast it
- to the batch form (False).
-
- Shape:
- - Input: :math:`(C, D, H, W)` or :math:`(B, C, D, H, W)`, Optional: :math:`(B, 4, 4)`
- - Output: :math:`(B, C, D, H, W)`
-
- Note:
- Input tensor must be float and normalized into [0, 1] for the best differentiability support.
- Additionally, this function accepts another transformation tensor (:math:`(B, 4, 4)`), then the
- applied transformation will be merged int to the input transformation tensor and returned.
-
- Examples:
- >>> rng = torch.manual_seed(0)
- >>> input = torch.rand(1, 1, 3, 3, 3)
- >>> aug = RandomRotation3D((15., 20., 20.), p=1.0, return_transform=True)
- >>> aug(input)
- (tensor([[[[[0.3819, 0.4886, 0.2111],
- [0.1196, 0.3833, 0.4722],
- [0.3432, 0.5951, 0.4223]],
- <BLANKLINE>
- [[0.5553, 0.4374, 0.2780],
- [0.2423, 0.1689, 0.4009],
- [0.4516, 0.6376, 0.7327]],
- <BLANKLINE>
- [[0.1605, 0.3112, 0.3673],
- [0.4931, 0.4620, 0.5700],
- [0.3505, 0.4685, 0.8092]]]]]), tensor([[[ 0.9722, 0.1131, -0.2049, 0.1196],
- [-0.0603, 0.9669, 0.2478, -0.1545],
- [ 0.2262, -0.2286, 0.9469, 0.0556],
- [ 0.0000, 0.0000, 0.0000, 1.0000]]]))
-
- To apply the exact augmenation again, you may take the advantage of the previous parameter state:
- >>> input = torch.rand(1, 3, 32, 32, 32)
- >>> aug = RandomRotation3D((15., 20., 20.), p=1.)
- >>> (aug(input) == aug(input, params=aug._params)).all()
- tensor(True)
- """
-
- def __init__(
- self,
- degrees: Union[
- torch.Tensor,
- float,
- Tuple[float, float, float],
- Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float]],
- ],
- resample: Union[str, int, Resample] = Resample.BILINEAR.name,
- return_transform: bool = False,
- same_on_batch: bool = False,
- align_corners: bool = False,
- p: float = 0.5,
- keepdim: bool = False,
- ) -> None:
- super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
- self.flags = dict(
- resample=Resample.get(resample),
- align_corners=align_corners
- )
- self._param_generator = cast(rg.RotationGenerator3D, rg.RotationGenerator3D(degrees))
-
- def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
- yaw: torch.Tensor = params["yaw"].to(input)
- pitch: torch.Tensor = params["pitch"].to(input)
- roll: torch.Tensor = params["roll"].to(input)
-
- center: torch.Tensor = _compute_tensor_center3d(input)
- rotation_mat: torch.Tensor = _compute_rotation_matrix3d(yaw, pitch, roll, center.expand(yaw.shape[0], -1))
-
- # rotation_mat is B x 3 x 4 and we need a B x 4 x 4 matrix
- trans_mat: torch.Tensor = torch.eye(4, device=input.device, dtype=input.dtype).repeat(input.shape[0], 1, 1)
- trans_mat[:, 0] = rotation_mat[:, 0]
- trans_mat[:, 1] = rotation_mat[:, 1]
- trans_mat[:, 2] = rotation_mat[:, 2]
-
- return trans_mat
-
- def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
- ) -> torch.Tensor:
- transform = cast(torch.Tensor, transform)
- return affine3d(
- input, transform[..., :3, :4], self.flags["resample"].name.lower(), "zeros", self.flags["align_corners"]
- )
-
-
-class RandomMotionBlur3D(AugmentationBase3D):
- r"""Apply random motion blur on 3D volumes (5D tensor).
-
- Args:
- p: probability of applying the transformation.
- kernel_size: motion kernel size (odd and positive).
- If int, the kernel will have a fixed size.
- If Tuple[int, int], it will randomly generate the value from the range batch-wisely.
- angle: Range of degrees to select from.
- If angle is a number, then yaw, pitch, roll will be generated from the range of (-angle, +angle).
- If angle is a tuple of (min, max), then yaw, pitch, roll will be generated from the range of (min, max).
- If angle is a list of floats [a, b, c], then yaw, pitch, roll will be generated from (-a, a), (-b, b)
- and (-c, c).
- If angle is a list of tuple ((a, b), (m, n), (x, y)), then yaw, pitch, roll will be generated from
- (a, b), (m, n) and (x, y).
- Set to 0 to deactivate rotations.
- direction: forward/backward direction of the motion blur.
- Lower values towards -1.0 will point the motion blur towards the back (with angle provided via angle),
- while higher values towards 1.0 will point the motion blur forward. A value of 0.0 leads to a
- uniformly (but still angled) motion blur.
- If float, it will generate the value from (-direction, direction).
- If Tuple[int, int], it will randomly generate the value from the range.
- border_type: the padding mode to be applied before convolving.
- CONSTANT = 0, REFLECT = 1, REPLICATE = 2, CIRCULAR = 3. Default: BorderType.CONSTANT.
- resample: resample mode from "nearest" (0) or "bilinear" (1).
- keepdim: whether to keep the output shape the same as input (True) or broadcast it to the batch form (False).
-
- Shape:
- - Input: :math:`(C, D, H, W)` or :math:`(B, C, D, H, W)`, Optional: :math:`(B, 4, 4)`
- - Output: :math:`(B, C, D, H, W)`
-
- Note:
- Input tensor must be float and normalized into [0, 1] for the best differentiability support.
- Additionally, this function accepts another transformation tensor (:math:`(B, 4, 4)`), then the
- applied transformation will be merged int to the input transformation tensor and returned.
-
- Examples:
- >>> rng = torch.manual_seed(0)
- >>> input = torch.rand(1, 1, 3, 5, 5)
- >>> motion_blur = RandomMotionBlur3D(3, 35., 0.5, p=1.)
- >>> motion_blur(input)
- tensor([[[[[0.1654, 0.4772, 0.2004, 0.3566, 0.2613],
- [0.4557, 0.3131, 0.4809, 0.2574, 0.2696],
- [0.2721, 0.5998, 0.3956, 0.5363, 0.1541],
- [0.3006, 0.4773, 0.6395, 0.2856, 0.3989],
- [0.4491, 0.5595, 0.1836, 0.3811, 0.1398]],
- <BLANKLINE>
- [[0.1843, 0.4240, 0.3370, 0.1231, 0.2186],
- [0.4047, 0.3332, 0.1901, 0.5329, 0.3023],
- [0.3070, 0.3088, 0.4807, 0.4928, 0.2590],
- [0.2416, 0.4614, 0.7091, 0.5237, 0.1433],
- [0.1582, 0.4577, 0.2749, 0.1369, 0.1607]],
- <BLANKLINE>
- [[0.2733, 0.4040, 0.4396, 0.2284, 0.3319],
- [0.3856, 0.6730, 0.4624, 0.3878, 0.3076],
- [0.4307, 0.4217, 0.2977, 0.5086, 0.5406],
- [0.3686, 0.2778, 0.5228, 0.7592, 0.6455],
- [0.2033, 0.3014, 0.4898, 0.6164, 0.3117]]]]])
-
- To apply the exact augmenation again, you may take the advantage of the previous parameter state:
- >>> input = torch.rand(1, 3, 32, 32, 32)
- >>> aug = RandomMotionBlur3D(3, 35., 0.5, p=1.)
- >>> (aug(input) == aug(input, params=aug._params)).all()
- tensor(True)
- """
-
- def __init__(
- self,
- kernel_size: Union[int, Tuple[int, int]],
- angle: Union[
- torch.Tensor,
- float,
- Tuple[float, float, float],
- Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float]],
- ],
- direction: Union[torch.Tensor, float, Tuple[float, float]],
- border_type: Union[int, str, BorderType] = BorderType.CONSTANT.name,
- resample: Union[str, int, Resample] = Resample.NEAREST.name,
- return_transform: bool = False,
- same_on_batch: bool = False,
- p: float = 0.5,
- keepdim: bool = False,
- ) -> None:
- super().__init__(
- p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim
- )
- self.flags = dict(
- border_type=BorderType.get(border_type),
- resample=Resample.get(resample),
- )
- self._param_generator = cast(rg.MotionBlurGenerator3D, rg.MotionBlurGenerator3D(kernel_size, angle, direction))
-
- def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
- return self.identity_matrix(input)
-
- def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
- ) -> torch.Tensor:
- kernel_size: int = cast(int, params["ksize_factor"].unique().item())
- angle = params["angle_factor"]
- direction = params["direction_factor"]
- return motion_blur3d(
- input, kernel_size, angle, direction, self.flags["border_type"].name.lower(),
- self.flags["resample"].name.lower()
- )
-
-
-class CenterCrop3D(AugmentationBase3D):
- r"""Apply center crop on 3D volumes (5D tensor).
-
- Args:
- p: probability of applying the transformation for the whole batch.
- size (Tuple[int, int, int] or int): Desired output size (out_d, out_h, out_w) of the crop.
- If integer, out_d = out_h = out_w = size.
- If Tuple[int, int, int], out_d = size[0], out_h = size[1], out_w = size[2].
- resample:
- return_transform: if ``True`` return the matrix describing the transformation applied to each
- input tensor. If ``False`` and the input is a tuple the applied transformation won't be concatenated.
- align_corners: interpolation flag.
- keepdim: whether to keep the output shape the same as input (True) or broadcast it
- to the batch form (False).
-
- Shape:
- - Input: :math:`(C, D, H, W)` or :math:`(B, C, D, H, W)`, Optional: :math:`(B, 4, 4)`
- - Output: :math:`(B, C, out_d, out_h, out_w)`
-
- Note:
- Input tensor must be float and normalized into [0, 1] for the best differentiability support.
- Additionally, this function accepts another transformation tensor (:math:`(B, 4, 4)`), then the
- applied transformation will be merged int to the input transformation tensor and returned.
-
- Examples:
- >>> rng = torch.manual_seed(0)
- >>> inputs = torch.randn(1, 1, 2, 4, 6)
- >>> inputs
- tensor([[[[[-1.1258, -1.1524, -0.2506, -0.4339, 0.8487, 0.6920],
- [-0.3160, -2.1152, 0.3223, -1.2633, 0.3500, 0.3081],
- [ 0.1198, 1.2377, 1.1168, -0.2473, -1.3527, -1.6959],
- [ 0.5667, 0.7935, 0.5988, -1.5551, -0.3414, 1.8530]],
- <BLANKLINE>
- [[ 0.7502, -0.5855, -0.1734, 0.1835, 1.3894, 1.5863],
- [ 0.9463, -0.8437, -0.6136, 0.0316, -0.4927, 0.2484],
- [ 0.4397, 0.1124, 0.6408, 0.4412, -0.1023, 0.7924],
- [-0.2897, 0.0525, 0.5229, 2.3022, -1.4689, -1.5867]]]]])
- >>> aug = CenterCrop3D(2, p=1.)
- >>> aug(inputs)
- tensor([[[[[ 0.3223, -1.2633],
- [ 1.1168, -0.2473]],
- <BLANKLINE>
- [[-0.6136, 0.0316],
- [ 0.6408, 0.4412]]]]])
-
- To apply the exact augmenation again, you may take the advantage of the previous parameter state:
- >>> input = torch.rand(1, 3, 32, 32, 32)
- >>> aug = CenterCrop3D(24, p=1.)
- >>> (aug(input) == aug(input, params=aug._params)).all()
- tensor(True)
- """
-
- def __init__(
- self,
- size: Union[int, Tuple[int, int, int]],
- align_corners: bool = True,
- resample: Union[str, int, Resample] = Resample.BILINEAR.name,
- return_transform: bool = False,
- p: float = 1.0,
- keepdim: bool = False,
- ) -> None:
- # same_on_batch is always True for CenterCrop
- # Since PyTorch does not support ragged tensor. So cropping function happens batch-wisely.
- super().__init__(p=1.0, return_transform=return_transform, same_on_batch=True, p_batch=p, keepdim=keepdim)
- if isinstance(size, tuple):
- size = (size[0], size[1], size[2])
- elif isinstance(size, int):
- size = (size, size, size)
- else:
- raise Exception(f"Invalid size type. Expected (int, tuple(int, int int). Got: {size}.")
- self.flags = dict(
- size=size,
- align_corners=align_corners,
- resample=Resample.get(resample),
- )
-
- def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
- return rg.center_crop_generator3d(
- batch_shape[0], batch_shape[-3], batch_shape[-2], batch_shape[-1], self.flags["size"], device=self.device
- )
-
- def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
- transform: torch.Tensor = get_perspective_transform3d(params["src"].to(input), params["dst"].to(input))
- transform = transform.expand(input.shape[0], -1, -1)
- return transform
-
- def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
- ) -> torch.Tensor:
- transform = cast(torch.Tensor, transform)
- return crop_by_transform_mat3d(
- input, transform, self.flags["size"], mode=self.flags["resample"].name.lower(),
- align_corners=self.flags["align_corners"]
- )
-
-
-class RandomCrop3D(AugmentationBase3D):
- r"""Apply random crop on 3D volumes (5D tensor).
-
- Crops random sub-volumes on a given size.
-
- Args:
- p: probability of applying the transformation for the whole batch.
- size: Desired output size (out_d, out_h, out_w) of the crop.
- Must be Tuple[int, int, int], then out_d = size[0], out_h = size[1], out_w = size[2].
- padding: Optional padding on each border of the image.
- Default is None, i.e no padding. If a sequence of length 6 is provided, it is used to pad
- left, top, right, bottom, front, back borders respectively.
- If a sequence of length 3 is provided, it is used to pad left/right,
- top/bottom, front/back borders, respectively.
- pad_if_needed: It will pad the image if smaller than the
- desired size to avoid raising an exception. Since cropping is done
- after padding, the padding seems to be done at a random offset.
- fill: Pixel fill value for constant fill. Default is 0. If a tuple of
- length 3, it is used to fill R, G, B channels respectively.
- This value is only used when the padding_mode is constant.
- padding_mode: Type of padding. Should be: constant, edge, reflect or symmetric. Default is constant.
- resample:
- return_transform: if ``True`` return the matrix describing the transformation applied to each
- input tensor. If ``False`` and the input is a tuple the applied transformation won't be concatenated
- same_on_batch: apply the same transformation across the batch.
- align_corners: interpolation flag.
- keepdim: whether to keep the output shape the same as input (True) or broadcast it
- to the batch form (False).
-
- Shape:
- - Input: :math:`(C, D, H, W)` or :math:`(B, C, D, H, W)`, Optional: :math:`(B, 4, 4)`
- - Output: :math:`(B, C, , out_d, out_h, out_w)`
-
- Note:
- Input tensor must be float and normalized into [0, 1] for the best differentiability support.
- Additionally, this function accepts another transformation tensor (:math:`(B, 4, 4)`), then the
- applied transformation will be merged int to the input transformation tensor and returned.
-
- Examples:
- >>> rng = torch.manual_seed(0)
- >>> inputs = torch.randn(1, 1, 3, 3, 3)
- >>> aug = RandomCrop3D((2, 2, 2), p=1.)
- >>> aug(inputs)
- tensor([[[[[-1.1258, -1.1524],
- [-0.4339, 0.8487]],
- <BLANKLINE>
- [[-1.2633, 0.3500],
- [ 0.1665, 0.8744]]]]])
-
- To apply the exact augmenation again, you may take the advantage of the previous parameter state:
- >>> input = torch.rand(1, 3, 32, 32, 32)
- >>> aug = RandomCrop3D((24, 24, 24), p=1.)
- >>> (aug(input) == aug(input, params=aug._params)).all()
- tensor(True)
- """
-
- def __init__(
- self,
- size: Tuple[int, int, int],
- padding: Optional[Union[int, Tuple[int, int, int], Tuple[int, int, int, int, int, int]]] = None,
- pad_if_needed: Optional[bool] = False,
- fill: int = 0,
- padding_mode: str = "constant",
- resample: Union[str, int, Resample] = Resample.BILINEAR.name,
- return_transform: bool = False,
- same_on_batch: bool = False,
- align_corners: bool = True,
- p: float = 1.0,
- keepdim: bool = False,
- ) -> None:
- # Since PyTorch does not support ragged tensor. So cropping function happens batch-wisely.
- super().__init__(
- p=1.0, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=p, keepdim=keepdim
- )
- self.flags = dict(
- size=size,
- padding=padding,
- pad_if_needed=pad_if_needed,
- padding_mode=padding_mode,
- fill=fill,
- resample=Resample.get(resample),
- align_corners=align_corners,
- )
- self._param_generator = cast(rg.CropGenerator3D, rg.CropGenerator3D(size, None))
-
- def precrop_padding(self, input: torch.Tensor) -> torch.Tensor:
- padding = self.flags["padding"]
- if padding is not None:
- if isinstance(padding, int):
- padding = [padding, padding, padding, padding, padding, padding]
- elif isinstance(padding, (tuple, list)) and len(padding) == 3:
- padding = [padding[0], padding[0], padding[1], padding[1], padding[2], padding[2]]
- elif isinstance(padding, (tuple, list)) and len(padding) == 6:
- padding = [padding[0], padding[1], padding[2], padding[3], padding[4], padding[5]] # type: ignore
- else:
- raise ValueError(f"`padding` must be an integer, 3-element-list or 6-element-list. Got {padding}.")
- input = pad(input, padding, value=self.flags["fill"], mode=self.flags["padding_mode"])
-
- if self.flags["pad_if_needed"] and input.shape[-3] < self.flags["size"][0]:
- padding = [0, 0, 0, 0, self.flags["size"][0] - input.shape[-3], self.flags["size"][0] - input.shape[-3]]
- input = pad(input, padding, value=self.flags["fill"], mode=self.flags["padding_mode"])
-
- if self.flags["pad_if_needed"] and input.shape[-2] < self.flags["size"][1]:
- padding = [0, 0, (self.flags["size"][1] - input.shape[-2]), self.flags["size"][1] - input.shape[-2], 0, 0]
- input = pad(input, padding, value=self.flags["fill"], mode=self.flags["padding_mode"])
-
- if self.flags["pad_if_needed"] and input.shape[-1] < self.flags["size"][2]:
- padding = [self.flags["size"][2] - input.shape[-1], self.flags["size"][2] - input.shape[-1], 0, 0, 0, 0]
- input = pad(input, padding, value=self.flags["fill"], mode=self.flags["padding_mode"])
-
- return input
-
- def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
- transform: torch.Tensor = get_perspective_transform3d(params["src"].to(input), params["dst"].to(input))
- transform = transform.expand(input.shape[0], -1, -1)
- return transform
-
- def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
- ) -> torch.Tensor:
- transform = cast(torch.Tensor, transform)
- return crop_by_transform_mat3d(
- input, transform, self.flags["size"], mode=self.flags["resample"].name.lower(),
- align_corners=self.flags["align_corners"]
- )
-
- def forward( # type: ignore
- self,
- input: TensorWithTransformMat,
- params: Optional[Dict[str, torch.Tensor]] = None,
- return_transform: Optional[bool] = None,
- ) -> TensorWithTransformMat:
- if type(input) is tuple:
- input = (self.precrop_padding(input[0]), input[1])
- else:
- input = self.precrop_padding(input) # type:ignore
- return super().forward(input, params, return_transform)
-
-
-class RandomPerspective3D(AugmentationBase3D):
- r"""Apply andom perspective transformation to 3D volumes (5D tensor).
-
- Args:
- p: probability of the image being perspectively transformed.
- distortion_scale: it controls the degree of distortion and ranges from 0 to 1.
- resample:
- return_transform: if ``True`` return the matrix describing the transformation applied to each.
- same_on_batch: apply the same transformation across the batch.
- align_corners: interpolation flag.
- keepdim: whether to keep the output shape the same as input (True) or broadcast it
- to the batch form (False).
-
- Shape:
- - Input: :math:`(C, D, H, W)` or :math:`(B, C, D, H, W)`, Optional: :math:`(B, 4, 4)`
- - Output: :math:`(B, C, D, H, W)`
-
- Note:
- Input tensor must be float and normalized into [0, 1] for the best differentiability support.
- Additionally, this function accepts another transformation tensor (:math:`(B, 4, 4)`), then the
- applied transformation will be merged int to the input transformation tensor and returned.
-
- Examples:
- >>> rng = torch.manual_seed(0)
- >>> inputs= torch.tensor([[[
- ... [[1., 0., 0.],
- ... [0., 1., 0.],
- ... [0., 0., 1.]],
- ... [[1., 0., 0.],
- ... [0., 1., 0.],
- ... [0., 0., 1.]],
- ... [[1., 0., 0.],
- ... [0., 1., 0.],
- ... [0., 0., 1.]]
- ... ]]])
- >>> aug = RandomPerspective3D(0.5, p=1., align_corners=True)
- >>> aug(inputs)
- tensor([[[[[0.3976, 0.5507, 0.0000],
- [0.0901, 0.3668, 0.0000],
- [0.0000, 0.0000, 0.0000]],
- <BLANKLINE>
- [[0.2651, 0.4657, 0.0000],
- [0.1390, 0.5174, 0.0000],
- [0.0000, 0.0000, 0.0000]],
- <BLANKLINE>
- [[0.0000, 0.1153, 0.0000],
- [0.0000, 0.0000, 0.0000],
- [0.0000, 0.0000, 0.0000]]]]])
-
- To apply the exact augmenation again, you may take the advantage of the previous parameter state:
- >>> input = torch.rand(1, 3, 32, 32, 32)
- >>> aug = RandomPerspective3D(0.5, p=1.)
- >>> (aug(input) == aug(input, params=aug._params)).all()
- tensor(True)
- """
-
- def __init__(
- self,
- distortion_scale: Union[torch.Tensor, float] = 0.5,
- resample: Union[str, int, Resample] = Resample.BILINEAR.name,
- return_transform: bool = False,
- same_on_batch: bool = False,
- align_corners: bool = False,
- p: float = 0.5,
- keepdim: bool = False,
- ) -> None:
- super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
- self.flags = dict(
- resample=Resample.get(resample),
- align_corners=align_corners,
- )
- self._param_generator = cast(rg.PerspectiveGenerator3D, rg.PerspectiveGenerator3D(distortion_scale))
-
- def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
- return get_perspective_transform3d(params["start_points"], params["end_points"]).to(input)
-
- def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
- ) -> torch.Tensor:
- transform = cast(torch.Tensor, transform)
- return warp_perspective3d(
- input,
- transform,
- (input.shape[-3], input.shape[-2], input.shape[-1]),
- flags=self.flags["resample"].name.lower(),
- align_corners=self.flags["align_corners"],
- )
-
-
-class RandomEqualize3D(AugmentationBase3D):
- r"""Apply random equalization to 3D volumes (5D tensor).
-
- Args:
- p: probability of the image being equalized.
- return_transform: if ``True`` return the matrix describing the transformation applied to each
- input tensor. If ``False`` and the input is a tuple the applied transformation won't be concatenated.
- 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, D, H, W)` or :math:`(B, C, D, H, W)`, Optional: :math:`(B, 4, 4)`
- - Output: :math:`(B, C, D, H, W)`
-
- Note:
- Input tensor must be float and normalized into [0, 1] for the best differentiability support.
- Additionally, this function accepts another transformation tensor (:math:`(B, 4, 4)`), then the
- applied transformation will be merged int to the input transformation tensor and returned.
-
- Examples:
- >>> rng = torch.manual_seed(0)
- >>> input = torch.rand(1, 1, 3, 3, 3)
- >>> aug = RandomEqualize3D(p=1.0)
- >>> aug(input)
- tensor([[[[[0.4963, 0.7682, 0.0885],
- [0.1320, 0.3074, 0.6341],
- [0.4901, 0.8964, 0.4556]],
- <BLANKLINE>
- [[0.6323, 0.3489, 0.4017],
- [0.0223, 0.1689, 0.2939],
- [0.5185, 0.6977, 0.8000]],
- <BLANKLINE>
- [[0.1610, 0.2823, 0.6816],
- [0.9152, 0.3971, 0.8742],
- [0.4194, 0.5529, 0.9527]]]]])
-
- To apply the exact augmenation again, you may take the advantage of the previous parameter state:
- >>> input = torch.rand(1, 3, 32, 32, 32)
- >>> aug = RandomEqualize3D(p=1.)
- >>> (aug(input) == aug(input, params=aug._params)).all()
- tensor(True)
- """
-
- def __init__(
- self, p: float = 0.5, return_transform: bool = False, same_on_batch: bool = False, keepdim: bool = False
- ) -> None:
- super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
-
- def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
- return self.identity_matrix(input)
-
- def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
- ) -> torch.Tensor:
- return equalize3d(input)
diff --git a/kornia/augmentation/base.py b/kornia/augmentation/base.py
index 9d3497c83..124aeeb35 100644
--- a/kornia/augmentation/base.py
+++ b/kornia/augmentation/base.py
@@ -1,22 +1,12 @@
-import warnings
from enum import Enum
-from typing import Any, cast, Dict, Optional, Tuple, Union
+from typing import Any, Dict, Optional, Tuple, Union, cast
import torch
import torch.nn as nn
from torch.distributions import Bernoulli
-import kornia
-from kornia.utils.helpers import _torch_inverse_cast
-
-from .random_generator import RandomGeneratorBase
-from .utils import (
- _adapted_sampling,
- _transform_input,
- _transform_input3d,
- _transform_output_shape,
- _validate_input_dtype,
-)
+from kornia.augmentation.random_generator import RandomGeneratorBase
+from kornia.augmentation.utils import _adapted_sampling, _transform_output_shape
TensorWithTransformMat = Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]
@@ -269,298 +259,3 @@ class _AugmentationBase(_BasicAugmentationBase):
self._params = params
output = self.apply_func(in_tensor, in_transform, self._params, return_transform)
return _transform_output_shape(output, ori_shape) if self.keepdim else output
-
-
-class AugmentationBase2D(_AugmentationBase):
- r"""AugmentationBase2D base class for customized augmentation implementations.
-
- For any augmentation, the implementation of "generate_parameters" and "apply_transform" are required while the
- "compute_transformation" is only required when passing "return_transform" as True.
-
- Args:
- p: probability for applying an augmentation. This param controls the augmentation probabilities
- element-wise for a batch.
- p_batch: probability for applying an augmentation to a batch. This param controls the augmentation
- probabilities batch-wise.
- return_transform: if ``True`` return the matrix describing the geometric transformation applied to each
- input tensor. If ``False`` and the input is a tuple the applied transformation won't be concatenated.
- 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``.
- """
-
- def __check_batching__(self, input: TensorWithTransformMat):
- if isinstance(input, tuple):
- inp, mat = input
- if len(inp.shape) == 4:
- if len(mat.shape) != 3:
- raise AssertionError('Input tensor is in batch mode ' 'but transformation matrix is not')
- if mat.shape[0] != inp.shape[0]:
- raise AssertionError(
- f"In batch dimension, input has {inp.shape[0]} but transformation matrix has {mat.shape[0]}"
- )
- elif len(inp.shape) in (2, 3):
- if len(mat.shape) != 2:
- raise AssertionError("Input tensor is in non-batch mode but transformation matrix is not")
- else:
- raise ValueError(f'Unrecognized output shape. Expected 2, 3, or 4, got {len(inp.shape)}')
-
- def transform_tensor(self, input: torch.Tensor) -> torch.Tensor:
- """Convert any incoming (H, W), (C, H, W) and (B, C, H, W) into (B, C, H, W)."""
- _validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])
- return _transform_input(input)
-
- def identity_matrix(self, input) -> torch.Tensor:
- """Return 3x3 identity matrix."""
- return kornia.eye_like(3, input)
-
-
-class IntensityAugmentationBase2D(AugmentationBase2D):
- r"""IntensityAugmentationBase2D base class for customized intensity augmentation implementations.
-
- For any augmentation, the implementation of "generate_parameters" and "apply_transform" are required while the
- "compute_transformation" is only required when passing "return_transform" as True.
-
- Args:
- p: probability for applying an augmentation. This param controls the augmentation probabilities
- element-wise for a batch.
- p_batch: probability for applying an augmentation to a batch. This param controls the augmentation
- probabilities batch-wise.
- return_transform: if ``True`` return the matrix describing the geometric transformation applied to each
- input tensor. If ``False`` and the input is a tuple the applied transformation won't be concatenated.
- 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``.
- """
-
- def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
- return self.identity_matrix(input)
-
-
-class GeometricAugmentationBase2D(AugmentationBase2D):
- r"""GeometricAugmentationBase2D base class for customized geometric augmentation implementations.
-
- For any augmentation, the implementation of "generate_parameters" and "apply_transform" are required while the
- "compute_transformation" is only required when passing "return_transform" as True.
-
- Args:
- p: probability for applying an augmentation. This param controls the augmentation probabilities
- element-wise for a batch.
- p_batch: probability for applying an augmentation to a batch. This param controls the augmentation
- probabilities batch-wise.
- return_transform: if ``True`` return the matrix describing the geometric transformation applied to each
- input tensor. If ``False`` and the input is a tuple the applied transformation won't be concatenated.
- 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``.
- """
-
- def inverse_transform(
- self,
- input: torch.Tensor,
- transform: Optional[torch.Tensor] = None,
- size: Optional[Tuple[int, int]] = None,
- **kwargs,
- ) -> torch.Tensor:
- """By default, the exact transformation as ``apply_transform`` will be used."""
- raise NotImplementedError
-
- def compute_inverse_transformation(self, transform: torch.Tensor):
- """Compute the inverse transform of given transformation matrices."""
- return _torch_inverse_cast(transform)
-
- def get_transformation_matrix(
- self, input: torch.Tensor, params: Optional[Dict[str, torch.Tensor]] = None
- ) -> torch.Tensor:
- if params is not None:
- transform = self.compute_transformation(input[params['batch_prob']], params)
- elif not hasattr(self, "_transform_matrix"):
- params = self.forward_parameters(input.shape)
- transform = self.identity_matrix(input)
- transform[params['batch_prob']] = self.compute_transformation(input[params['batch_prob']], params)
- else:
- transform = self._transform_matrix
- return torch.as_tensor(transform, device=input.device, dtype=input.dtype)
-
- def inverse(
- self,
- input: TensorWithTransformMat,
- params: Optional[Dict[str, torch.Tensor]] = None,
- size: Optional[Tuple[int, int]] = None,
- **kwargs,
- ) -> torch.Tensor:
- if isinstance(input, (list, tuple)):
- input, transform = input
- else:
- transform = self.get_transformation_matrix(input, params)
- if params is not None:
- transform = self.identity_matrix(input)
- transform[params['batch_prob']] = self.compute_transformation(input[params['batch_prob']], params)
-
- ori_shape = input.shape
- in_tensor = self.transform_tensor(input)
- batch_shape = input.shape
- if params is None:
- params = self._params
- if size is None and "forward_input_shape" in params:
- # Majorly for cropping functions
- size = params['forward_input_shape'].numpy().tolist()
- size = (size[-2], size[-1])
- if 'batch_prob' not in params:
- params['batch_prob'] = torch.tensor([True] * batch_shape[0])
- warnings.warn("`batch_prob` is not found in params. Will assume applying on all data.")
- output = input.clone()
- to_apply = params['batch_prob']
- # if no augmentation needed
- if torch.sum(to_apply) == 0:
- output = in_tensor
- # if all data needs to be augmented
- elif torch.sum(to_apply) == len(to_apply):
- transform = self.compute_inverse_transformation(transform)
- output = self.inverse_transform(in_tensor, transform, size, **kwargs)
- else:
- transform[to_apply] = self.compute_inverse_transformation(transform[to_apply])
- output[to_apply] = self.inverse_transform(in_tensor[to_apply], transform[to_apply], size, **kwargs)
- return cast(torch.Tensor, _transform_output_shape(output, ori_shape)) if self.keepdim else output
-
-
-class AugmentationBase3D(_AugmentationBase):
- r"""AugmentationBase3D base class for customized augmentation implementations.
-
- For any augmentation, the implementation of "generate_parameters" and "apply_transform" are required while the
- "compute_transformation" is only required when passing "return_transform" as True.
-
- Args:
- p: probability for applying an augmentation. This param controls the augmentation probabilities
- element-wise for a batch.
- p_batch: probability for applying an augmentation to a batch. This param controls the augmentation
- probabilities batch-wise.
- return_transform: if ``True`` return the matrix describing the geometric transformation applied to each
- input tensor. If ``False`` and the input is a tuple the applied transformation won't be concatenated.
- same_on_batch: apply the same transformation across the batch.
- """
-
- def __check_batching__(self, input: TensorWithTransformMat):
- if isinstance(input, tuple):
- inp, mat = input
- if len(inp.shape) == 5:
- if len(mat.shape) != 3:
- raise AssertionError('Input tensor is in batch mode ' 'but transformation matrix is not')
- if mat.shape[0] != inp.shape[0]:
- raise AssertionError(
- f"In batch dimension, input has {inp.shape[0]} but transformation matrix has {mat.shape[0]}"
- )
- elif len(inp.shape) in (3, 4):
- if len(mat.shape) != 2:
- raise AssertionError("Input tensor is in non-batch mode but transformation matrix is not")
- else:
- raise ValueError(f'Unrecognized output shape. Expected 3, 4 or 5, got {len(inp.shape)}')
-
- def transform_tensor(self, input: torch.Tensor) -> torch.Tensor:
- """Convert any incoming (D, H, W), (C, D, H, W) and (B, C, D, H, W) into (B, C, D, H, W)."""
- _validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])
- return _transform_input3d(input)
-
- def identity_matrix(self, input) -> torch.Tensor:
- """Return 4x4 identity matrix."""
- return kornia.eye_like(4, input)
-
-
-class MixAugmentationBase(_BasicAugmentationBase):
- r"""MixAugmentationBase base class for customized mix augmentation implementations.
-
- For any augmentation, the implementation of "generate_parameters" and "apply_transform" are required.
- "apply_transform" will need to handle the probabilities internally.
-
- Args:
- p: probability for applying an augmentation. This param controls if to apply the augmentation for the batch.
- p_batch: probability for applying an augmentation to a batch. This param controls the augmentation
- probabilities batch-wise.
- 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``.
- """
-
- def __init__(self, p: float, p_batch: float, same_on_batch: bool = False, keepdim: bool = False) -> None:
- super().__init__(p, p_batch=p_batch, same_on_batch=same_on_batch, keepdim=keepdim)
-
- def __check_batching__(self, input: TensorWithTransformMat):
- if isinstance(input, tuple):
- inp, mat = input
- if len(inp.shape) == 4:
- if len(mat.shape) != 3:
- raise AssertionError('Input tensor is in batch mode ' 'but transformation matrix is not')
- if mat.shape[0] != inp.shape[0]:
- raise AssertionError(
- f"In batch dimension, input has {inp.shape[0]} but transformation matrix has {mat.shape[0]}"
- )
- elif len(inp.shape) in (2, 3):
- if len(mat.shape) != 2:
- raise AssertionError("Input tensor is in non-batch mode but transformation matrix is not")
- else:
- raise ValueError(f'Unrecognized output shape. Expected 2, 3, or 4, got {len(inp.shape)}')
-
- def __unpack_input__( # type: ignore
- self, input: TensorWithTransformMat
- ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
- if isinstance(input, tuple):
- in_tensor = input[0]
- in_transformation = input[1]
- return in_tensor, in_transformation
- in_tensor = input
- return in_tensor, None
-
- def transform_tensor(self, input: torch.Tensor) -> torch.Tensor:
- """Convert any incoming (H, W), (C, H, W) and (B, C, H, W) into (B, C, H, W)."""
- _validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])
- return _transform_input(input)
-
- def apply_transform( # type: ignore
- self, input: torch.Tensor, label: torch.Tensor, params: Dict[str, torch.Tensor]
- ) -> Tuple[torch.Tensor, torch.Tensor]:
- raise NotImplementedError
-
- def apply_func( # type: ignore
- self, in_tensor: torch.Tensor, label: torch.Tensor, params: Dict[str, torch.Tensor]
- ) -> Tuple[torch.Tensor, torch.Tensor]:
- to_apply = params['batch_prob']
-
- # if no augmentation needed
- if torch.sum(to_apply) == 0:
- output = in_tensor
- # if all data needs to be augmented
- elif torch.sum(to_apply) == len(to_apply):
- output, label = self.apply_transform(in_tensor, label, params)
- else:
- raise ValueError(
- "Mix augmentations must be performed batch-wisely. Element-wise augmentation is not supported."
- )
-
- return output, label
-
- def forward( # type: ignore
- self,
- input: TensorWithTransformMat,
- label: Optional[torch.Tensor] = None,
- params: Optional[Dict[str, torch.Tensor]] = None,
- ) -> Tuple[TensorWithTransformMat, torch.Tensor]:
- in_tensor, in_trans = self.__unpack_input__(input)
- ori_shape = in_tensor.shape
- in_tensor = self.transform_tensor(in_tensor)
- # If label is not provided, it would output the indices instead.
- if label is None:
- if isinstance(input, (tuple, list)):
- device = input[0].device
- else:
- device = input.device
- label = torch.arange(0, in_tensor.size(0), device=device, dtype=torch.long)
- if params is None:
- batch_shape = in_tensor.shape
- params = self.forward_parameters(batch_shape)
- self._params = params
-
- output, lab = self.apply_func(in_tensor, label, self._params)
- output = _transform_output_shape(output, ori_shape) if self.keepdim else output # type: ignore
- if in_trans is not None:
- return (output, in_trans), lab
- return output, lab
diff --git a/kornia/augmentation/container/__init__.py b/kornia/augmentation/container/__init__.py
index e2da07e75..cc31c01c7 100644
--- a/kornia/augmentation/container/__init__.py
+++ b/kornia/augmentation/container/__init__.py
@@ -1,4 +1,4 @@
-from .augment import AugmentationSequential
-from .image import ImageSequential
-from .patch import PatchSequential
-from .video import VideoSequential
+from kornia.augmentation.container.augment import AugmentationSequential
+from kornia.augmentation.container.image import ImageSequential
+from kornia.augmentation.container.patch import PatchSequential
+from kornia.augmentation.container.video import VideoSequential
diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.py
index d0957ab93..ef5f9c80e 100644
--- a/kornia/augmentation/container/augment.py
+++ b/kornia/augmentation/container/augment.py
@@ -1,23 +1,24 @@
import warnings
from itertools import zip_longest
-from typing import Any, cast, List, Optional, Tuple, Union
+from typing import Any, List, Optional, Tuple, Union, cast
import torch
-from kornia.augmentation.base import _AugmentationBase, GeometricAugmentationBase2D, IntensityAugmentationBase2D
+from kornia.augmentation import GeometricAugmentationBase2D, IntensityAugmentationBase2D
+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.patch import PatchSequential
+from kornia.augmentation.container.utils import ApplyInverse
+from kornia.augmentation.container.video import VideoSequential
from kornia.constants import DataKey
from kornia.geometry.boxes import Boxes
-from .base import SequentialBase
-from .image import ImageSequential, ParamItem
-from .patch import PatchSequential
-from .utils import ApplyInverse
-from .video import VideoSequential
-
__all__ = ["AugmentationSequential"]
AugmentationSequentialInput = Union[
- torch.Tensor, List[torch.Tensor], Tuple[torch.Tensor, torch.Tensor], Tuple[List[torch.Tensor], torch.Tensor]]
+ torch.Tensor, List[torch.Tensor], Tuple[torch.Tensor, torch.Tensor], Tuple[List[torch.Tensor], torch.Tensor]
+]
class AugmentationSequential(ImageSequential):
@@ -298,7 +299,7 @@ class AugmentationSequential(ImageSequential):
inp = _input[0]
else:
inp = _input
- if isinstance(inp, (tuple, list,)):
+ if isinstance(inp, (tuple, list)):
raise ValueError(f"`INPUT` should be a tensor but `{type(inp)}` received.")
# A video input shall be BCDHW while an image input shall be BCHW
if self.contains_video_sequential:
@@ -347,7 +348,7 @@ class AugmentationSequential(ImageSequential):
input = input.view(batch_size, -1, *input.shape[1:])
elif isinstance(module, PatchSequential):
raise NotImplementedError("Geometric involved PatchSequential is not supported.")
- elif isinstance(module, (GeometricAugmentationBase2D, ImageSequential,)) and dcate in DataKey:
+ elif isinstance(module, (GeometricAugmentationBase2D, ImageSequential)) and dcate in DataKey:
input, label = ApplyInverse.apply_by_key(input, label, module, param, dcate)
elif isinstance(module, (SequentialBase,)):
raise ValueError(f"Unsupported Sequential {module}.")
diff --git a/kornia/augmentation/container/base.py b/kornia/augmentation/container/base.py
index 8c5c9e32d..c3d9f08d3 100644
--- a/kornia/augmentation/container/base.py
+++ b/kornia/augmentation/container/base.py
@@ -4,7 +4,8 @@ from typing import Any, Iterator, List, NamedTuple, Optional, Tuple, Union
import torch
import torch.nn as nn
-from kornia.augmentation.base import _AugmentationBase, MixAugmentationBase
+from kornia.augmentation import MixAugmentationBase
+from kornia.augmentation.base import _AugmentationBase
__all__ = ["SequentialBase", "ParamItem"]
diff --git a/kornia/augmentation/container/image.py b/kornia/augmentation/container/image.py
index c664d72f5..7a3167c33 100644
--- a/kornia/augmentation/container/image.py
+++ b/kornia/augmentation/container/image.py
@@ -5,17 +5,15 @@ import torch
import torch.nn as nn
import kornia
-from kornia.augmentation import RandomCrop
-from kornia.augmentation.base import (
- _AugmentationBase,
+from kornia.augmentation import (
GeometricAugmentationBase2D,
IntensityAugmentationBase2D,
MixAugmentationBase,
- TensorWithTransformMat,
+ RandomCrop,
)
-
-from .base import ParamItem, SequentialBase
-from .utils import ApplyInverseInterface, InputApplyInverse
+from kornia.augmentation.base import TensorWithTransformMat, _AugmentationBase
+from kornia.augmentation.container.base import ParamItem, SequentialBase
+from kornia.augmentation.container.utils import ApplyInverseInterface, InputApplyInverse
__all__ = ["ImageSequential"]
@@ -97,7 +95,7 @@ class ImageSequential(SequentialBase):
keepdim: Optional[bool] = None,
random_apply: Union[int, bool, Tuple[int, int]] = False,
random_apply_weights: Optional[List[float]] = None,
- if_unsupported_ops: str = "raise"
+ if_unsupported_ops: str = "raise",
) -> None:
super().__init__(*args, same_on_batch=same_on_batch, return_transform=return_transform, keepdim=keepdim)
@@ -246,9 +244,7 @@ class ImageSequential(SequentialBase):
# Implicitly indicating the label cannot be optional since there is a mix aug
return output
- def get_transformation_matrix(
- self, input: torch.Tensor, params: Optional[List[ParamItem]] = None,
- ) -> torch.Tensor:
+ def get_transformation_matrix(self, input: torch.Tensor, params: Optional[List[ParamItem]] = None) -> torch.Tensor:
"""Compute the transformation matrix according to the provided parameters."""
if params is None:
raise NotImplementedError("requires params to be provided.")
@@ -289,11 +285,7 @@ class ImageSequential(SequentialBase):
return False
return True
- def inverse(
- self,
- input: torch.Tensor,
- params: Optional[List[ParamItem]] = None,
- ) -> torch.Tensor:
+ def inverse(self, input: torch.Tensor, params: Optional[List[ParamItem]] = None) -> torch.Tensor:
"""Inverse transformation.
Used to inverse a tensor according to the performed transformation by a forward pass, or with respect to
diff --git a/kornia/augmentation/container/patch.py b/kornia/augmentation/container/patch.py
index bf0c2b0b8..b2c226573 100644
--- a/kornia/augmentation/container/patch.py
+++ b/kornia/augmentation/container/patch.py
@@ -4,12 +4,12 @@ from typing import Iterator, List, NamedTuple, Optional, Tuple, Union
import torch
import torch.nn as nn
-from kornia.augmentation.base import _AugmentationBase, MixAugmentationBase, TensorWithTransformMat
+from kornia.augmentation import MixAugmentationBase
+from kornia.augmentation.base import TensorWithTransformMat, _AugmentationBase
from kornia.augmentation.container.base import SequentialBase
+from kornia.augmentation.container.image import ImageSequential, ParamItem
from kornia.contrib.extract_patches import extract_tensor_patches
-from .image import ImageSequential, ParamItem
-
__all__ = ["PatchSequential"]
@@ -138,8 +138,12 @@ class PatchSequential(ImageSequential):
else:
_random_apply = random_apply
super().__init__(
- *args, same_on_batch=same_on_batch, return_transform=False, keepdim=keepdim, random_apply=_random_apply,
- random_apply_weights=random_apply_weights
+ *args,
+ same_on_batch=same_on_batch,
+ return_transform=False,
+ keepdim=keepdim,
+ random_apply=_random_apply,
+ random_apply_weights=random_apply_weights,
)
if padding not in ("same", "valid"):
raise ValueError(f"`padding` must be either `same` or `valid`. Got {padding}.")
@@ -382,11 +386,7 @@ class PatchSequential(ImageSequential):
_input = _input.reshape(in_shape)
return _input, label
- def inverse( # type: ignore
- self,
- input: torch.Tensor,
- params: List[ParamItem],
- ) -> torch.Tensor:
+ def inverse(self, input: torch.Tensor, params: List[ParamItem]) -> torch.Tensor: # type: ignore
"""Inverse transformation.
Used to inverse a tensor according to the performed transformation by a forward pass, or with respect to
diff --git a/kornia/augmentation/container/utils.py b/kornia/augmentation/container/utils.py
index 1378d7607..ebe62af50 100644
--- a/kornia/augmentation/container/utils.py
+++ b/kornia/augmentation/container/utils.py
@@ -1,24 +1,20 @@
from abc import ABCMeta, abstractmethod
from functools import partial
-from typing import Callable, cast, Dict, Iterator, List, Optional, Tuple, Type, Union
+from typing import Callable, Dict, Iterator, List, Optional, Tuple, Type, Union, cast
import torch
import torch.nn as nn
import kornia # lazy loading for circular dependencies
-from kornia.augmentation.base import (
- _AugmentationBase,
- GeometricAugmentationBase2D,
- MixAugmentationBase,
- TensorWithTransformMat,
-)
+from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
+from kornia.augmentation._2d.mix.base import MixAugmentationBase
+from kornia.augmentation.base import TensorWithTransformMat, _AugmentationBase
+from kornia.augmentation.container.base import ParamItem
from kornia.constants import DataKey
from kornia.geometry.bbox import transform_bbox
from kornia.geometry.linalg import transform_points
from kornia.utils.helpers import _torch_inverse_cast
-from .base import ParamItem
-
def _get_geometric_only_param(
module: "kornia.augmentation.container.ImageSequential", param: List[ParamItem]
@@ -38,11 +34,7 @@ class ApplyInverseInterface(metaclass=ABCMeta):
@classmethod
@abstractmethod
def apply_trans(
- cls,
- input: torch.Tensor,
- label: Optional[torch.Tensor],
- module: nn.Module,
- param: ParamItem,
+ cls, input: torch.Tensor, label: Optional[torch.Tensor], module: nn.Module, param: ParamItem
) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
"""Apply a transformation with respect to the parameters.
@@ -57,12 +49,7 @@ class ApplyInverseInterface(metaclass=ABCMeta):
@classmethod
@abstractmethod
- def inverse(
- cls,
- input: torch.Tensor,
- module: nn.Module,
- param: Optional[ParamItem] = None
- ) -> torch.Tensor:
+ def inverse(cls, input: torch.Tensor, module: nn.Module, param: Optional[ParamItem] = None) -> torch.Tensor:
"""Inverse a transformation with respect to the parameters.
Args:
@@ -105,9 +92,7 @@ class ApplyInverseImpl(ApplyInverseInterface):
return input, label
@classmethod
- def inverse(
- cls, input: torch.Tensor, module: nn.Module, param: Optional[ParamItem] = None
- ) -> torch.Tensor:
+ def inverse(cls, input: torch.Tensor, module: nn.Module, param: Optional[ParamItem] = None) -> torch.Tensor:
"""Inverse a transformation with respect to the parameters.
Args:
@@ -128,10 +113,10 @@ class ApplyInverseImpl(ApplyInverseInterface):
cls, input: torch.Tensor, module: nn.Module, param: Optional[ParamItem] = None
) -> Optional[torch.Tensor]:
- if isinstance(module, (
- GeometricAugmentationBase2D,
- kornia.augmentation.container.ImageSequential,
- )) and param is None:
+ if (
+ isinstance(module, (GeometricAugmentationBase2D, kornia.augmentation.container.ImageSequential))
+ and param is None
+ ):
raise ValueError(f"Parameters of transformation matrix for {module} has not been computed.")
if isinstance(module, GeometricAugmentationBase2D):
@@ -154,11 +139,7 @@ class InputApplyInverse(ApplyInverseImpl):
@classmethod
def apply_trans( # type: ignore
- cls,
- input: TensorWithTransformMat,
- label: Optional[torch.Tensor],
- module: nn.Module,
- param: ParamItem,
+ cls, input: TensorWithTransformMat, label: Optional[torch.Tensor], module: nn.Module, param: ParamItem
) -> Tuple[TensorWithTransformMat, Optional[torch.Tensor]]:
"""Apply a transformation with respect to the parameters.
@@ -217,6 +198,7 @@ class MaskApplyInverse(ApplyInverseImpl):
@classmethod
def make_input_only_sequential(cls, module: "kornia.augmentation.container.ImageSequential") -> Callable:
"""Disable all other additional inputs (e.g. ) for ImageSequential."""
+
def f(*args, **kwargs):
if_return_trans = module.return_transform
if_return_label = module.return_label
@@ -226,6 +208,7 @@ class MaskApplyInverse(ApplyInverseImpl):
module.return_transform = if_return_trans
module.return_label = if_return_label
return out
+
return f
@classmethod
@@ -261,9 +244,7 @@ class MaskApplyInverse(ApplyInverseImpl):
return input, label
@classmethod
- def inverse(
- cls, input: torch.Tensor, module: nn.Module, param: Optional[ParamItem] = None
- ) -> torch.Tensor:
+ def inverse(cls, input: torch.Tensor, module: nn.Module, param: Optional[ParamItem] = None) -> torch.Tensor:
"""Inverse a transformation with respect to the parameters.
Args:
@@ -347,9 +328,7 @@ class BBoxXYXYApplyInverse(ApplyInverseImpl):
return _input, label
@classmethod
- def inverse(
- cls, input: torch.Tensor, module: nn.Module, param: Optional[ParamItem] = None
- ) -> torch.Tensor:
+ def inverse(cls, input: torch.Tensor, module: nn.Module, param: Optional[ParamItem] = None) -> torch.Tensor:
"""Inverse a transformation with respect to the parameters.
Args:
diff --git a/kornia/augmentation/container/video.py b/kornia/augmentation/container/video.py
index d3d89cc0d..cc8762353 100644
--- a/kornia/augmentation/container/video.py
+++ b/kornia/augmentation/container/video.py
@@ -1,16 +1,16 @@
-from typing import cast, List, Optional, Tuple, Union
+from typing import List, Optional, Tuple, Union, cast
import torch
import torch.nn as nn
import kornia
from kornia.augmentation import RandomCrop
-from kornia.augmentation.base import _AugmentationBase, MixAugmentationBase, TensorWithTransformMat
+from kornia.augmentation._2d.mix.base import MixAugmentationBase
+from kornia.augmentation.base import TensorWithTransformMat, _AugmentationBase
from kornia.augmentation.container.base import SequentialBase
+from kornia.augmentation.container.image import ImageSequential, ParamItem
from kornia.augmentation.container.utils import InputApplyInverse, MaskApplyInverse
-from .image import ImageSequential, ParamItem
-
__all__ = ["VideoSequential"]
@@ -103,8 +103,12 @@ class VideoSequential(ImageSequential):
random_apply_weights: Optional[List[float]] = None,
) -> None:
super().__init__(
- *args, same_on_batch=None, return_transform=None, keepdim=None, random_apply=random_apply,
- random_apply_weights=random_apply_weights
+ *args,
+ same_on_batch=None,
+ return_transform=None,
+ keepdim=None,
+ random_apply=random_apply,
+ random_apply_weights=random_apply_weights,
)
self.same_on_frame = same_on_frame
self.data_format = data_format.upper()
@@ -118,7 +122,7 @@ class VideoSequential(ImageSequential):
def __infer_channel_exclusive_batch_shape__(self, batch_shape: torch.Size, chennel_index: int) -> torch.Size:
# Fix mypy complains: error: Incompatible return value type (got "Tuple[int, ...]", expected "Size")
- return cast(torch.Size, batch_shape[:chennel_index] + batch_shape[chennel_index + 1:])
+ return cast(torch.Size, batch_shape[:chennel_index] + batch_shape[chennel_index + 1 :])
def __repeat_param_across_channels__(self, param: torch.Tensor, frame_num: int) -> torch.Tensor:
"""Repeat parameters across channels.
diff --git a/kornia/augmentation/random_generator/_2d/__init__.py b/kornia/augmentation/random_generator/_2d/__init__.py
new file mode 100644
index 000000000..5794a6c46
--- /dev/null
+++ b/kornia/augmentation/random_generator/_2d/__init__.py
@@ -0,0 +1,12 @@
+from kornia.augmentation.random_generator._2d.affine import *
+from kornia.augmentation.random_generator._2d.color_jitter import *
+from kornia.augmentation.random_generator._2d.crop import *
+from kornia.augmentation.random_generator._2d.cutmix import *
+from kornia.augmentation.random_generator._2d.func import *
+from kornia.augmentation.random_generator._2d.mixup import *
+from kornia.augmentation.random_generator._2d.motion_blur import *
+from kornia.augmentation.random_generator._2d.perspective import *
+from kornia.augmentation.random_generator._2d.plain_uniform import *
+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 *
diff --git a/kornia/augmentation/random_generator/_2d/affine.py b/kornia/augmentation/random_generator/_2d/affine.py
new file mode 100644
index 000000000..1cede6ab4
--- /dev/null
+++ b/kornia/augmentation/random_generator/_2d/affine.py
@@ -0,0 +1,288 @@
+from typing import Dict, Optional, Tuple, Union, cast
+
+import torch
+from torch.distributions import Uniform
+
+from kornia.augmentation.random_generator.base import RandomGeneratorBase
+from kornia.augmentation.utils import (
+ _adapted_rsampling,
+ _adapted_uniform,
+ _common_param_check,
+ _joint_range_check,
+ _range_bound,
+)
+from kornia.utils.helpers import _deprecated, _extract_device_dtype
+
+
+class AffineGenerator(RandomGeneratorBase):
+ r"""Get parameters for ``affine`` for a random affine transform.
+
+ Args:
+ degrees: Range of degrees to select from like (min, max).
+ 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.
+ scale: scaling factor interval, e.g (a, b), then scale is
+ randomly sampled from the range a <= scale <= b. Will keep original scale by default.
+ 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.
+ - translations (torch.Tensor): element-wise translations with a shape of (B, 2).
+ - center (torch.Tensor): element-wise center with a shape of (B, 2).
+ - scale (torch.Tensor): element-wise scales with a shape of (B, 2).
+ - angle (torch.Tensor): element-wise rotation angles with a shape of (B,).
+ - sx (torch.Tensor): element-wise x-axis shears with a shape of (B,).
+ - sy (torch.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,
+ degrees: Union[torch.Tensor, float, Tuple[float, float]],
+ translate: Optional[Union[torch.Tensor, Tuple[float, float]]] = None,
+ scale: Optional[Union[torch.Tensor, Tuple[float, float], Tuple[float, float, float, float]]] = None,
+ shear: Optional[Union[torch.Tensor, float, Tuple[float, float]]] = None,
+ ) -> None:
+ super().__init__()
+ self.degrees = degrees
+ self.translate = translate
+ self.scale = scale
+ self.shear = shear
+
+ def __repr__(self) -> str:
+ repr = f"degrees={self.degrees}, translate={self.translate}, scale={self.scale}, shear={self.shear}"
+ return repr
+
+ def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
+ _degrees = _range_bound(self.degrees, 'degrees', 0, (-360, 360)).to(device=device, dtype=dtype)
+ _translate = (
+ self.translate
+ if self.translate is None
+ else _range_bound(self.translate, 'translate', bounds=(0, 1), check='singular').to(
+ device=device, dtype=dtype
+ )
+ )
+ _scale: Optional[torch.Tensor] = None
+ if self.scale is not None:
+ if len(self.scale) == 2:
+ _scale = _range_bound(self.scale[:2], 'scale', bounds=(0, float('inf')), check='singular').to(
+ device=device, dtype=dtype
+ )
+ elif len(self.scale) == 4:
+ _scale = torch.cat(
+ [
+ _range_bound(self.scale[:2], 'scale_x', bounds=(0, float('inf')), check='singular'),
+ _range_bound(
+ self.scale[2:], 'scale_y', bounds=(0, float('inf')), check='singular' # type:ignore
+ ),
+ ]
+ ).to(device=device, dtype=dtype)
+ else:
+ raise ValueError(f"'scale' expected to be either 2 or 4 elements. Got {self.scale}")
+ _shear: Optional[torch.Tensor] = None
+ if self.shear is not None:
+ shear = torch.as_tensor(self.shear, device=device, dtype=dtype)
+ if shear.shape == torch.Size([2, 2]):
+ _shear = shear
+ else:
+ _shear = torch.stack(
+ [
+ _range_bound(shear if shear.dim() == 0 else shear[:2], 'shear-x', 0, (-360, 360)),
+ torch.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)),
+ ]
+ )
+
+ translate_x_sampler: Optional[Uniform] = None
+ translate_y_sampler: Optional[Uniform] = None
+ scale_2_sampler: Optional[Uniform] = None
+ scale_4_sampler: Optional[Uniform] = None
+ shear_x_sampler: Optional[Uniform] = None
+ shear_y_sampler: Optional[Uniform] = None
+
+ if _translate is not None:
+ translate_x_sampler = Uniform(-_translate[0], _translate[0], validate_args=False)
+ translate_y_sampler = Uniform(-_translate[1], _translate[1], validate_args=False)
+ if _scale is not None:
+ if len(_scale) == 2:
+ scale_2_sampler = Uniform(_scale[0], _scale[1], validate_args=False)
+ elif len(_scale) == 4:
+ scale_2_sampler = Uniform(_scale[0], _scale[1], validate_args=False)
+ scale_4_sampler = Uniform(_scale[2], _scale[3], validate_args=False)
+ else:
+ raise ValueError(f"'scale' expected to be either 2 or 4 elements. Got {self.scale}")
+ if _shear is not None:
+ _joint_range_check(cast(torch.Tensor, _shear)[0], "shear")
+ _joint_range_check(cast(torch.Tensor, _shear)[1], "shear")
+ 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.degree_sampler = Uniform(_degrees[0], _degrees[1], validate_args=False)
+ self.translate_x_sampler = translate_x_sampler
+ self.translate_y_sampler = translate_y_sampler
+ self.scale_2_sampler = scale_2_sampler
+ self.scale_4_sampler = scale_4_sampler
+ 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, torch.Tensor]: # type: ignore
+ batch_size = batch_shape[0]
+ height = batch_shape[-2]
+ width = batch_shape[-1]
+
+ _device, _dtype = _extract_device_dtype([self.degrees, self.translate, self.scale, 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}.")
+
+ angle = _adapted_rsampling((batch_size,), self.degree_sampler, same_on_batch).to(device=_device, dtype=_dtype)
+
+ # compute tensor ranges
+ if self.scale_2_sampler is not None:
+ _scale = _adapted_rsampling((batch_size,), self.scale_2_sampler, same_on_batch).unsqueeze(1).repeat(1, 2)
+ if self.scale_4_sampler is not None:
+ _scale[:, 1] = _adapted_rsampling((batch_size,), self.scale_4_sampler, same_on_batch)
+ _scale = _scale.to(device=_device, dtype=_dtype)
+ else:
+ _scale = torch.ones((batch_size, 2), device=_device, dtype=_dtype)
+
+ if self.translate_x_sampler is not None and self.translate_y_sampler is not None:
+ translations = torch.stack(
+ [
+ _adapted_rsampling((batch_size,), self.translate_x_sampler, same_on_batch) * width,
+ _adapted_rsampling((batch_size,), self.translate_y_sampler, same_on_batch) * height,
+ ],
+ dim=-1,
+ )
+ translations = translations.to(device=_device, dtype=_dtype)
+ else:
+ translations = torch.zeros((batch_size, 2), device=_device, dtype=_dtype)
+
+ center: torch.Tensor = torch.tensor([width, height], device=_device, dtype=_dtype).view(1, 2) / 2.0 - 0.5
+ center = center.expand(batch_size, -1)
+
+ if self.shear_x_sampler is not None and self.shear_y_sampler is not None:
+ 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)
+ else:
+ sx = sy = torch.tensor([0] * batch_size, device=_device, dtype=_dtype)
+
+ return dict(translations=translations, center=center, scale=_scale, angle=angle, sx=sx, sy=sy)
+
+
+@_deprecated(replace_with=AffineGenerator.__name__)
+def random_affine_generator(
+ batch_size: int,
+ height: int,
+ width: int,
+ degrees: torch.Tensor,
+ translate: Optional[torch.Tensor] = None,
+ scale: Optional[torch.Tensor] = None,
+ shear: 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"""Get parameters for ``affine`` for a random affine transform.
+
+ Args:
+ batch_size (int): the tensor batch size.
+ height (int) : height of the image.
+ width (int): width of the image.
+ degrees (torch.Tensor): Range of degrees to select from like (min, max).
+ translate (tensor, optional): 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.
+ scale (tensor, optional): scaling factor interval, e.g (a, b), then scale is
+ randomly sampled from the range a <= scale <= b. Will keep original scale by default.
+ shear (tensor, optional): Range of degrees to select from.
+ 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.
+ 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.
+ - translations (torch.Tensor): element-wise translations with a shape of (B, 2).
+ - center (torch.Tensor): element-wise center with a shape of (B, 2).
+ - scale (torch.Tensor): element-wise scales with a shape of (B, 2).
+ - angle (torch.Tensor): element-wise rotation angles with a shape of (B,).
+ - sx (torch.Tensor): element-wise x-axis shears with a shape of (B,).
+ - sy (torch.Tensor): element-wise y-axis shears with a shape of (B,).
+
+ Note:
+ The generated random numbers are not reproducible across different devices and dtypes.
+ """
+ _common_param_check(batch_size, same_on_batch)
+ _joint_range_check(degrees, "degrees")
+ 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}.")
+
+ _device, _dtype = _extract_device_dtype([degrees, translate, scale, shear])
+ degrees = degrees.to(device=device, dtype=dtype)
+ angle = _adapted_uniform((batch_size,), degrees[0], degrees[1], same_on_batch)
+ angle = angle.to(device=_device, dtype=_dtype)
+
+ # compute tensor ranges
+ if scale is not None:
+ scale = scale.to(device=device, dtype=dtype)
+ if not (len(scale.shape) == 1 and len(scale) in (2, 4)):
+ raise AssertionError(f"`scale` shall have 2 or 4 elements. Got {scale}.")
+ _joint_range_check(cast(torch.Tensor, scale[:2]), "scale")
+ _scale = _adapted_uniform((batch_size,), scale[0], scale[1], same_on_batch).unsqueeze(1).repeat(1, 2)
+ if len(scale) == 4:
+ _joint_range_check(cast(torch.Tensor, scale[2:]), "scale_y")
+ _scale[:, 1] = _adapted_uniform((batch_size,), scale[2], scale[3], same_on_batch)
+ _scale = _scale.to(device=_device, dtype=_dtype)
+ else:
+ _scale = torch.ones((batch_size, 2), device=_device, dtype=_dtype)
+
+ if translate is not None:
+ translate = translate.to(device=device, dtype=dtype)
+ if not (0.0 <= translate[0] <= 1.0 and 0.0 <= translate[1] <= 1.0 and translate.shape == torch.Size([2])):
+ raise AssertionError(f"Expect translate contains two elements and ranges are in [0, 1]. Got {translate}.")
+ max_dx: torch.Tensor = translate[0] * width
+ max_dy: torch.Tensor = translate[1] * height
+ translations = torch.stack(
+ [
+ _adapted_uniform((batch_size,), -max_dx, max_dx, same_on_batch),
+ _adapted_uniform((batch_size,), -max_dy, max_dy, same_on_batch),
+ ],
+ dim=-1,
+ )
+ translations = translations.to(device=_device, dtype=_dtype)
+ else:
+ translations = torch.zeros((batch_size, 2), device=_device, dtype=_dtype)
+
+ center: torch.Tensor = torch.tensor([width, height], device=_device, dtype=_dtype).view(1, 2) / 2.0 - 0.5
+ center = center.expand(batch_size, -1)
+
+ if shear is not None:
+ shear = shear.to(device=device, dtype=dtype)
+ _joint_range_check(cast(torch.Tensor, shear)[0], "shear")
+ _joint_range_check(cast(torch.Tensor, shear)[1], "shear")
+ sx = _adapted_uniform((batch_size,), shear[0][0], shear[0][1], same_on_batch)
+ sy = _adapted_uniform((batch_size,), shear[1][0], shear[1][1], same_on_batch)
+ sx = sx.to(device=_device, dtype=_dtype)
+ sy = sy.to(device=_device, dtype=_dtype)
+ else:
+ sx = sy = torch.tensor([0] * batch_size, device=_device, dtype=_dtype)
+
+ return dict(translations=translations, center=center, scale=_scale, angle=angle, sx=sx, sy=sy)
diff --git a/kornia/augmentation/random_generator/_2d/color_jitter.py b/kornia/augmentation/random_generator/_2d/color_jitter.py
new file mode 100644
index 000000000..fc588fa42
--- /dev/null
+++ b/kornia/augmentation/random_generator/_2d/color_jitter.py
@@ -0,0 +1,159 @@
+from functools import partial
+from typing import Dict, List, 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,
+ _adapted_uniform,
+ _common_param_check,
+ _joint_range_check,
+ _range_bound,
+)
+from kornia.utils.helpers import _deprecated, _extract_device_dtype
+
+
+class ColorJitterGenerator(RandomGeneratorBase):
+ r"""Generate random color jiter parameters for a batch of images.
+
+ Args:
+ brightness: The brightness factor to apply.
+ contrast: The contrast factor to apply.
+ saturation: The saturation factor to apply.
+ hue: The hue factor to apply.
+
+ Returns:
+ A dict of parameters to be passed for transformation.
+ - brightness_factor: element-wise brightness factors with a shape of (B,).
+ - contrast_factor: element-wise contrast factors with a shape of (B,).
+ - hue_factor: element-wise hue factors with a shape of (B,).
+ - saturation_factor: element-wise saturation factors with a shape of (B,).
+ - order: applying orders of the color adjustments with a shape of (4). In which,
+ 0 is brightness adjustment; 1 is contrast adjustment;
+ 2 is saturation adjustment; 3 is hue adjustment.
+
+ 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,
+ brightness: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.0,
+ contrast: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.0,
+ saturation: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.0,
+ hue: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.0,
+ ) -> None:
+ super().__init__()
+ self.brightness = brightness
+ self.contrast = contrast
+ self.saturation = saturation
+ self.hue = hue
+
+ def __repr__(self) -> str:
+ repr = f"brightness={self.brightness}, contrast={self.contrast}, saturation={self.saturation}, hue={self.hue}"
+ return repr
+
+ def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
+ brightness: torch.Tensor = _range_bound(
+ self.brightness, 'brightness', center=1.0, bounds=(0, 2), device=device, dtype=dtype
+ )
+ contrast: torch.Tensor = _range_bound(self.contrast, 'contrast', center=1.0, device=device, dtype=dtype)
+ saturation: torch.Tensor = _range_bound(self.saturation, 'saturation', center=1.0, device=device, dtype=dtype)
+ hue: torch.Tensor = _range_bound(self.hue, 'hue', bounds=(-0.5, 0.5), device=device, dtype=dtype)
+
+ _joint_range_check(brightness, "brightness", (0, 2))
+ _joint_range_check(contrast, "contrast", (0, float('inf')))
+ _joint_range_check(hue, "hue", (-0.5, 0.5))
+ _joint_range_check(saturation, "saturation", (0, float('inf')))
+
+ self.brightness_sampler = Uniform(brightness[0], brightness[1], validate_args=False)
+ self.contrast_sampler = Uniform(contrast[0], contrast[1], validate_args=False)
+ self.hue_sampler = Uniform(hue[0], hue[1], validate_args=False)
+ self.saturation_sampler = Uniform(saturation[0], saturation[1], validate_args=False)
+ self.randperm = partial(torch.randperm, device=device, dtype=dtype)
+
+ def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, torch.Tensor]: # type:ignore
+ batch_size = batch_shape[0]
+ _common_param_check(batch_size, same_on_batch)
+ _device, _dtype = _extract_device_dtype([self.brightness, self.contrast, self.hue, self.saturation])
+ brightness_factor = _adapted_rsampling((batch_size,), self.brightness_sampler, same_on_batch)
+ contrast_factor = _adapted_rsampling((batch_size,), self.contrast_sampler, same_on_batch)
+ hue_factor = _adapted_rsampling((batch_size,), self.hue_sampler, same_on_batch)
+ saturation_factor = _adapted_rsampling((batch_size,), self.saturation_sampler, same_on_batch)
+ return dict(
+ brightness_factor=brightness_factor.to(device=_device, dtype=_dtype),
+ contrast_factor=contrast_factor.to(device=_device, dtype=_dtype),
+ hue_factor=hue_factor.to(device=_device, dtype=_dtype),
+ saturation_factor=saturation_factor.to(device=_device, dtype=_dtype),
+ order=self.randperm(4).to(device=_device, dtype=_dtype).long(),
+ )
+
+
+@_deprecated(replace_with=ColorJitterGenerator.__name__)
+def random_color_jitter_generator(
+ batch_size: int,
+ brightness: Optional[torch.Tensor] = None,
+ contrast: Optional[torch.Tensor] = None,
+ saturation: Optional[torch.Tensor] = None,
+ hue: 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 random color jiter parameters for a batch of images.
+
+ Args:
+ batch_size (int): the number of images.
+ brightness (torch.Tensor, optional): Brightness factor tensor of range (a, b).
+ The provided range must follow 0 <= a <= b <= 2. Default value is [0., 0.].
+ contrast (torch.Tensor, optional): Contrast factor tensor of range (a, b).
+ The provided range must follow 0 <= a <= b. Default value is [0., 0.].
+ saturation (torch.Tensor, optional): Saturation factor tensor of range (a, b).
+ The provided range must follow 0 <= a <= b. Default value is [0., 0.].
+ hue (torch.Tensor, optional): Saturation factor tensor of range (a, b).
+ The provided range must follow -0.5 <= a <= b < 0.5. Default value is [0., 0.].
+ 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.
+ - brightness_factor (torch.Tensor): element-wise brightness factors with a shape of (B,).
+ - contrast_factor (torch.Tensor): element-wise contrast factors with a shape of (B,).
+ - hue_factor (torch.Tensor): element-wise hue factors with a shape of (B,).
+ - saturation_factor (torch.Tensor): element-wise saturation factors with a shape of (B,).
+ - order (torch.Tensor): applying orders of the color adjustments with a shape of (4). In which,
+ 0 is brightness adjustment; 1 is contrast adjustment;
+ 2 is saturation adjustment; 3 is hue adjustment.
+
+ Note:
+ The generated random numbers are not reproducible across different devices and dtypes.
+ """
+ _common_param_check(batch_size, same_on_batch)
+ _device, _dtype = _extract_device_dtype([brightness, contrast, hue, saturation])
+ brightness = torch.as_tensor([0.0, 0.0] if brightness is None else brightness, device=device, dtype=dtype)
+ contrast = torch.as_tensor([0.0, 0.0] if contrast is None else contrast, device=device, dtype=dtype)
+ hue = torch.as_tensor([0.0, 0.0] if hue is None else hue, device=device, dtype=dtype)
+ saturation = torch.as_tensor([0.0, 0.0] if saturation is None else saturation, device=device, dtype=dtype)
+
+ _joint_range_check(brightness, "brightness", (0, 2))
+ _joint_range_check(contrast, "contrast", (0, float('inf')))
+ _joint_range_check(hue, "hue", (-0.5, 0.5))
+ _joint_range_check(saturation, "saturation", (0, float('inf')))
+
+ brightness_factor = _adapted_uniform((batch_size,), brightness[0], brightness[1], same_on_batch)
+ contrast_factor = _adapted_uniform((batch_size,), contrast[0], contrast[1], same_on_batch)
+ hue_factor = _adapted_uniform((batch_size,), hue[0], hue[1], same_on_batch)
+ saturation_factor = _adapted_uniform((batch_size,), saturation[0], saturation[1], same_on_batch)
+
+ return dict(
+ brightness_factor=brightness_factor.to(device=_device, dtype=_dtype),
+ contrast_factor=contrast_factor.to(device=_device, dtype=_dtype),
+ hue_factor=hue_factor.to(device=_device, dtype=_dtype),
+ saturation_factor=saturation_factor.to(device=_device, dtype=_dtype),
+ order=torch.randperm(4, device=_device, dtype=_dtype).long(),
+ )
diff --git a/kornia/augmentation/random_generator/_2d/crop.py b/kornia/augmentation/random_generator/_2d/crop.py
new file mode 100644
index 000000000..e10ec2006
--- /dev/null
+++ b/kornia/augmentation/random_generator/_2d/crop.py
@@ -0,0 +1,519 @@
+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, _adapted_uniform, _common_param_check, _joint_range_check
+from kornia.geometry.bbox import bbox_generator
+from kornia.utils.helpers import _deprecated, _extract_device_dtype
+
+
+class CropGenerator(RandomGeneratorBase):
+ r"""Get parameters for ```crop``` transformation for crop transform.
+
+ Args:
+ size (tuple): Desired size of the crop operation, like (h, w).
+ If tensor, it must be (B, 2).
+ resize_to (tuple): Desired output size of the crop, like (h, w). If None, no resize will be performed.
+
+ Returns:
+ params Dict[str, torch.Tensor]: parameters to be passed for transformation.
+ - src (torch.Tensor): cropping bounding boxes with a shape of (B, 4, 2).
+ - dst (torch.Tensor): output bounding boxes with a shape (B, 4, 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, size: Union[Tuple[int, int], torch.Tensor], resize_to: Optional[Tuple[int, int]] = None) -> None:
+ super().__init__()
+ self.size = size
+ self.resize_to = resize_to
+
+ def __repr__(self) -> str:
+ repr = f"crop_size={self.size}"
+ if self.resize_to is not None:
+ repr += f", resize_to={self.resize_to}"
+ return repr
+
+ def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
+ self.rand_sampler = Uniform(
+ torch.tensor(0.0, device=device, dtype=dtype), torch.tensor(1.0, device=device, dtype=dtype)
+ )
+
+ def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, torch.Tensor]: # type:ignore
+ batch_size = batch_shape[0]
+ _common_param_check(batch_size, same_on_batch)
+ _device, _dtype = _extract_device_dtype([self.size if isinstance(self.size, torch.Tensor) else None])
+
+ if batch_size == 0:
+ return dict(
+ src=torch.zeros([0, 4, 2], device=_device, dtype=_dtype),
+ dst=torch.zeros([0, 4, 2], device=_device, dtype=_dtype),
+ )
+
+ input_size = (batch_shape[-2], batch_shape[-1])
+ if not isinstance(self.size, torch.Tensor):
+ size = torch.tensor(self.size, device=_device, dtype=_dtype).repeat(batch_size, 1)
+ else:
+ size = self.size.to(device=_device, dtype=_dtype)
+ if size.shape != torch.Size([batch_size, 2]):
+ raise AssertionError(
+ "If `size` is a tensor, it must be shaped as (B, 2). "
+ f"Got {size.shape} while expecting {torch.Size([batch_size, 2])}."
+ )
+ if not (input_size[0] > 0 and input_size[1] > 0 and (size > 0).all()):
+ raise AssertionError(f"Got non-positive input size or size. {input_size}, {size}.")
+ size = size.floor()
+
+ x_diff = input_size[1] - size[:, 1] + 1
+ y_diff = input_size[0] - size[:, 0] + 1
+
+ # Start point will be 0 if diff < 0
+ x_diff = x_diff.clamp(0)
+ y_diff = y_diff.clamp(0)
+
+ if same_on_batch:
+ # If same_on_batch, select the first then repeat.
+ x_start = (
+ _adapted_rsampling((batch_size,), self.rand_sampler, same_on_batch).to(x_diff) * x_diff[0]
+ ).floor()
+ y_start = (
+ _adapted_rsampling((batch_size,), self.rand_sampler, same_on_batch).to(y_diff) * y_diff[0]
+ ).floor()
+ else:
+ x_start = (_adapted_rsampling((batch_size,), self.rand_sampler, same_on_batch).to(x_diff) * x_diff).floor()
+ y_start = (_adapted_rsampling((batch_size,), self.rand_sampler, same_on_batch).to(y_diff) * y_diff).floor()
+ crop_src = bbox_generator(
+ x_start.view(-1).to(device=_device, dtype=_dtype),
+ y_start.view(-1).to(device=_device, dtype=_dtype),
+ torch.where(size[:, 1] == 0, torch.tensor(input_size[1], device=_device, dtype=_dtype), size[:, 1]),
+ torch.where(size[:, 0] == 0, torch.tensor(input_size[0], device=_device, dtype=_dtype), size[:, 0]),
+ )
+
+ if self.resize_to is None:
+ crop_dst = bbox_generator(
+ torch.tensor([0] * batch_size, device=_device, dtype=_dtype),
+ torch.tensor([0] * batch_size, device=_device, dtype=_dtype),
+ size[:, 1],
+ size[:, 0],
+ )
+ else:
+ if not (
+ len(self.resize_to) == 2
+ and isinstance(self.resize_to[0], (int,))
+ and isinstance(self.resize_to[1], (int,))
+ and self.resize_to[0] > 0
+ and self.resize_to[1] > 0
+ ):
+ raise AssertionError(f"`resize_to` must be a tuple of 2 positive integers. Got {self.resize_to}.")
+ crop_dst = torch.tensor(
+ [
+ [
+ [0, 0],
+ [self.resize_to[1] - 1, 0],
+ [self.resize_to[1] - 1, self.resize_to[0] - 1],
+ [0, self.resize_to[0] - 1],
+ ]
+ ],
+ device=_device,
+ dtype=_dtype,
+ ).repeat(batch_size, 1, 1)
+
+ _input_size = torch.tensor(input_size, device=_device, dtype=torch.long).expand(batch_size, -1)
+
+ return dict(src=crop_src, dst=crop_dst, input_size=_input_size)
+
+
+class ResizedCropGenerator(CropGenerator):
+ r"""Get cropping heights and widths for ```crop``` transformation for resized crop transform.
+
+ Args:
+ output_size (Tuple[int, int]): expected output size of each edge.
+ scale (torch.Tensor): range of size of the origin size cropped with (2,) shape.
+ ratio (torch.Tensor): range of aspect ratio of the origin aspect ratio cropped with (2,) shape.
+
+ Returns:
+ params Dict[str, torch.Tensor]: parameters to be passed for transformation.
+ - size (torch.Tensor): element-wise cropping sizes with a shape of (B, 2).
+
+ Note:
+ The generated random numbers are not reproducible across different devices and dtypes.
+
+ Examples:
+ >>> _ = torch.manual_seed(42)
+ >>> random_crop_size_generator(3, (30, 30), scale=torch.tensor([.7, 1.3]), ratio=torch.tensor([.9, 1.]))
+ {'size': tensor([[29., 29.],
+ [27., 28.],
+ [26., 29.]])}
+ """
+
+ def __init__(
+ self,
+ output_size: Tuple[int, int],
+ scale: Union[torch.Tensor, Tuple[float, float]],
+ ratio: Union[torch.Tensor, Tuple[float, float]],
+ ) -> None:
+ self.scale = scale
+ self.ratio = ratio
+ self.output_size = output_size
+ if not (
+ len(output_size) == 2
+ and isinstance(output_size[0], (int,))
+ and isinstance(output_size[1], (int,))
+ and output_size[0] > 0
+ and output_size[1] > 0
+ ):
+ raise AssertionError(f"`output_size` must be a tuple of 2 positive integers. Got {output_size}.")
+ super().__init__(size=output_size, resize_to=self.output_size) # fake an intermedia crop size
+
+ def __repr__(self) -> str:
+ repr = f"scale={self.scale}, resize_to={self.ratio}, output_size={self.output_size}"
+ return repr
+
+ def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
+ scale = torch.as_tensor(self.scale, device=device, dtype=dtype)
+ ratio = torch.as_tensor(self.ratio, device=device, dtype=dtype)
+ _joint_range_check(scale, "scale")
+ _joint_range_check(ratio, "ratio")
+ self.rand_sampler = Uniform(
+ torch.tensor(0.0, device=device, dtype=dtype), torch.tensor(1.0, device=device, dtype=dtype)
+ )
+ self.log_ratio_sampler = Uniform(torch.log(ratio[0]), torch.log(ratio[1]), validate_args=False)
+
+ def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, torch.Tensor]: # type:ignore
+ batch_size = batch_shape[0]
+ size = (batch_shape[-2], batch_shape[-1])
+ _device, _dtype = _extract_device_dtype([self.scale, self.ratio])
+
+ if batch_size == 0:
+ return dict(
+ src=torch.zeros([0, 4, 2], device=_device, dtype=_dtype),
+ dst=torch.zeros([0, 4, 2], device=_device, dtype=_dtype),
+ size=torch.zeros([0, 2], device=_device, dtype=_dtype),
+ )
+
+ rand = _adapted_rsampling((batch_size, 10), self.rand_sampler, same_on_batch).to(device=_device, dtype=_dtype)
+ area = (rand * (self.scale[1] - self.scale[0]) + self.scale[0]) * size[0] * size[1]
+ log_ratio = _adapted_rsampling((batch_size, 10), self.log_ratio_sampler, same_on_batch).to(
+ device=_device, dtype=_dtype
+ )
+ aspect_ratio = torch.exp(log_ratio)
+
+ w = torch.sqrt(area * aspect_ratio).round().floor()
+ h = torch.sqrt(area / aspect_ratio).round().floor()
+ # Element-wise w, h condition
+ cond = ((0 < w) * (w < size[0]) * (0 < h) * (h < size[1])).int()
+
+ # torch.argmax is not reproducible across devices: https://github.com/pytorch/pytorch/issues/17738
+ # Here, we will select the first occurrence of the duplicated elements.
+ cond_bool, argmax_dim1 = ((cond.cumsum(1) == 1) & cond.bool()).max(1)
+ h_out = w[torch.arange(0, batch_size, device=_device, dtype=torch.long), argmax_dim1]
+ w_out = h[torch.arange(0, batch_size, device=_device, dtype=torch.long), argmax_dim1]
+
+ if not cond_bool.all():
+ # Fallback to center crop
+ in_ratio = float(size[0]) / float(size[1])
+ _min = self.ratio.min() if isinstance(self.ratio, torch.Tensor) else min(self.ratio)
+ if in_ratio < _min: # type:ignore
+ h_ct = torch.tensor(size[0], device=_device, dtype=_dtype)
+ w_ct = torch.round(h_ct / _min)
+ elif in_ratio > _min: # type:ignore
+ w_ct = torch.tensor(size[1], device=_device, dtype=_dtype)
+ h_ct = torch.round(w_ct * _min)
+ else: # whole image
+ h_ct = torch.tensor(size[0], device=_device, dtype=_dtype)
+ w_ct = torch.tensor(size[1], device=_device, dtype=_dtype)
+ h_ct = h_ct.floor()
+ w_ct = w_ct.floor()
+
+ h_out = h_out.where(cond_bool, h_ct)
+ w_out = w_out.where(cond_bool, w_ct)
+
+ # Update the crop size.
+ self.size = torch.stack([h_out, w_out], dim=1)
+ return super().forward(batch_shape, same_on_batch)
+
+
+@_deprecated(replace_with=CropGenerator.__name__)
+def random_crop_generator(
+ batch_size: int,
+ input_size: Tuple[int, int],
+ size: Union[Tuple[int, int], torch.Tensor],
+ resize_to: Optional[Tuple[int, int]] = None,
+ same_on_batch: bool = False,
+ device: torch.device = torch.device('cpu'),
+ dtype: torch.dtype = torch.float32,
+) -> Dict[str, torch.Tensor]:
+ r"""Get parameters for ```crop``` transformation for crop transform.
+
+ Args:
+ batch_size (int): the tensor batch size.
+ input_size (tuple): Input image shape, like (h, w).
+ size (tuple): Desired size of the crop operation, like (h, w).
+ If tensor, it must be (B, 2).
+ resize_to (tuple): Desired output size of the crop, like (h, w). If None, no resize will be performed.
+ 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.
+ - src (torch.Tensor): cropping bounding boxes with a shape of (B, 4, 2).
+ - dst (torch.Tensor): output bounding boxes with a shape (B, 4, 2).
+
+ Note:
+ The generated random numbers are not reproducible across different devices and dtypes.
+
+ Example:
+ >>> _ = torch.manual_seed(0)
+ >>> crop_size = torch.tensor([[25, 28], [27, 29], [26, 28]])
+ >>> random_crop_generator(3, (30, 30), size=crop_size, same_on_batch=False)
+ {'src': tensor([[[ 1., 0.],
+ [28., 0.],
+ [28., 24.],
+ [ 1., 24.]],
+ <BLANKLINE>
+ [[ 1., 1.],
+ [29., 1.],
+ [29., 27.],
+ [ 1., 27.]],
+ <BLANKLINE>
+ [[ 0., 3.],
+ [27., 3.],
+ [27., 28.],
+ [ 0., 28.]]]), 'dst': tensor([[[ 0., 0.],
+ [27., 0.],
+ [27., 24.],
+ [ 0., 24.]],
+ <BLANKLINE>
+ [[ 0., 0.],
+ [28., 0.],
+ [28., 26.],
+ [ 0., 26.]],
+ <BLANKLINE>
+ [[ 0., 0.],
+ [27., 0.],
+ [27., 25.],
+ [ 0., 25.]]]), 'input_size': tensor([[30, 30],
+ [30, 30],
+ [30, 30]])}
+ """
+ _common_param_check(batch_size, same_on_batch)
+ _device, _dtype = _extract_device_dtype([size if isinstance(size, torch.Tensor) else None])
+ # Use float point instead
+ _dtype = _dtype if _dtype in [torch.float16, torch.float32, torch.float64] else dtype
+ if not isinstance(size, torch.Tensor):
+ size = torch.tensor(size, device=_device, dtype=_dtype).repeat(batch_size, 1)
+ else:
+ size = size.to(device=_device, dtype=_dtype)
+ if size.shape != torch.Size([batch_size, 2]):
+ raise AssertionError(
+ "If `size` is a tensor, it must be shaped as (B, 2). "
+ f"Got {size.shape} while expecting {torch.Size([batch_size, 2])}."
+ )
+ if not (input_size[0] > 0 and input_size[1] > 0 and (size > 0).all()):
+ raise AssertionError(f"Got non-positive input size or size. {input_size}, {size}.")
+ size = size.floor()
+
+ x_diff = input_size[1] - size[:, 1] + 1
+ y_diff = input_size[0] - size[:, 0] + 1
+
+ # Start point will be 0 if diff < 0
+ x_diff = x_diff.clamp(0)
+ y_diff = y_diff.clamp(0)
+
+ if batch_size == 0:
+ return dict(
+ src=torch.zeros([0, 4, 2], device=_device, dtype=_dtype),
+ dst=torch.zeros([0, 4, 2], device=_device, dtype=_dtype),
+ )
+
+ if same_on_batch:
+ # If same_on_batch, select the first then repeat.
+ x_start = _adapted_uniform((batch_size,), 0, x_diff[0].to(device=device, dtype=dtype), same_on_batch).floor()
+ y_start = _adapted_uniform((batch_size,), 0, y_diff[0].to(device=device, dtype=dtype), same_on_batch).floor()
+ else:
+ x_start = _adapted_uniform((1,), 0, x_diff.to(device=device, dtype=dtype), same_on_batch).floor()
+ y_start = _adapted_uniform((1,), 0, y_diff.to(device=device, dtype=dtype), same_on_batch).floor()
+ crop_src = bbox_generator(
+ x_start.view(-1).to(device=_device, dtype=_dtype),
+ y_start.view(-1).to(device=_device, dtype=_dtype),
+ torch.where(size[:, 1] == 0, torch.tensor(input_size[1], device=_device, dtype=_dtype), size[:, 1]),
+ torch.where(size[:, 0] == 0, torch.tensor(input_size[0], device=_device, dtype=_dtype), size[:, 0]),
+ )
+
+ if resize_to is None:
+ crop_dst = bbox_generator(
+ torch.tensor([0] * batch_size, device=_device, dtype=_dtype),
+ torch.tensor([0] * batch_size, device=_device, dtype=_dtype),
+ size[:, 1],
+ size[:, 0],
+ )
+ else:
+ if not (
+ len(resize_to) == 2
+ and isinstance(resize_to[0], (int,))
+ and isinstance(resize_to[1], (int,))
+ and resize_to[0] > 0
+ and resize_to[1] > 0
+ ):
+ raise AssertionError(f"`resize_to` must be a tuple of 2 positive integers. Got {resize_to}.")
+ crop_dst = torch.tensor(
+ [[[0, 0], [resize_to[1] - 1, 0], [resize_to[1] - 1, resize_to[0] - 1], [0, resize_to[0] - 1]]],
+ device=_device,
+ dtype=_dtype,
+ ).repeat(batch_size, 1, 1)
+
+ _input_size = torch.tensor(input_size, device=_device, dtype=torch.long).expand(batch_size, -1)
+
+ return dict(src=crop_src, dst=crop_dst, input_size=_input_size)
+
+
+@_deprecated()
+def random_crop_size_generator(
+ batch_size: int,
+ size: Tuple[int, int],
+ scale: torch.Tensor,
+ ratio: torch.Tensor,
+ same_on_batch: bool = False,
+ device: torch.device = torch.device('cpu'),
+ dtype: torch.dtype = torch.float32,
+) -> Dict[str, torch.Tensor]:
+ r"""Get cropping heights and widths for ```crop``` transformation for resized crop transform.
+
+ Args:
+ batch_size (int): the tensor batch size.
+ size (Tuple[int, int]): expected output size of each edge.
+ scale (torch.Tensor): range of size of the origin size cropped with (2,) shape.
+ ratio (torch.Tensor): range of aspect ratio of the origin aspect ratio cropped with (2,) shape.
+ 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.
+ - size (torch.Tensor): element-wise cropping sizes with a shape of (B, 2).
+
+ Note:
+ The generated random numbers are not reproducible across different devices and dtypes.
+
+ Examples:
+ >>> _ = torch.manual_seed(42)
+ >>> random_crop_size_generator(3, (30, 30), scale=torch.tensor([.7, 1.3]), ratio=torch.tensor([.9, 1.]))
+ {'size': tensor([[29., 29.],
+ [27., 28.],
+ [26., 29.]])}
+ """
+ _common_param_check(batch_size, same_on_batch)
+ _joint_range_check(scale, "scale")
+ _joint_range_check(ratio, "ratio")
+ if not (len(size) == 2 and type(size[0]) is int and size[1] > 0 and type(size[1]) is int and size[1] > 0):
+ raise AssertionError(f"'height' and 'width' must be integers. Got {size}.")
+
+ _device, _dtype = _extract_device_dtype([scale, ratio])
+
+ if batch_size == 0:
+ return dict(size=torch.zeros([0, 2], device=_device, dtype=_dtype))
+
+ scale = scale.to(device=device, dtype=dtype)
+ ratio = ratio.to(device=device, dtype=dtype)
+ # 10 trails for each element
+ area = _adapted_uniform((batch_size, 10), scale[0] * size[0] * size[1], scale[1] * size[0] * size[1], same_on_batch)
+ log_ratio = _adapted_uniform((batch_size, 10), torch.log(ratio[0]), torch.log(ratio[1]), same_on_batch)
+ aspect_ratio = torch.exp(log_ratio)
+
+ w = torch.sqrt(area * aspect_ratio).round().floor()
+ h = torch.sqrt(area / aspect_ratio).round().floor()
+ # Element-wise w, h condition
+ cond = ((0 < w) * (w < size[0]) * (0 < h) * (h < size[1])).int()
+
+ # torch.argmax is not reproducible across devices: https://github.com/pytorch/pytorch/issues/17738
+ # Here, we will select the first occurrence of the duplicated elements.
+ cond_bool, argmax_dim1 = ((cond.cumsum(1) == 1) & cond.bool()).max(1)
+ h_out = w[torch.arange(0, batch_size, device=device, dtype=torch.long), argmax_dim1]
+ w_out = h[torch.arange(0, batch_size, device=device, dtype=torch.long), argmax_dim1]
+
+ if not cond_bool.all():
+ # Fallback to center crop
+ in_ratio = float(size[0]) / float(size[1])
+ if in_ratio < ratio.min():
+ h_ct = torch.tensor(size[0], device=device, dtype=dtype)
+ w_ct = torch.round(h_ct / ratio.min())
+ elif in_ratio > ratio.min():
+ w_ct = torch.tensor(size[1], device=device, dtype=dtype)
+ h_ct = torch.round(w_ct * ratio.min())
+ else: # whole image
+ h_ct = torch.tensor(size[0], device=device, dtype=dtype)
+ w_ct = torch.tensor(size[1], device=device, dtype=dtype)
+ h_ct = h_ct.floor()
+ w_ct = w_ct.floor()
+
+ h_out = h_out.where(cond_bool, h_ct)
+ w_out = w_out.where(cond_bool, w_ct)
+
+ return dict(size=torch.stack([h_out, w_out], dim=1).to(device=_device, dtype=_dtype))
+
+
+def center_crop_generator(
+ batch_size: int, height: int, width: int, size: Tuple[int, int], device: torch.device = torch.device('cpu')
+) -> Dict[str, torch.Tensor]:
+ r"""Get parameters for ```center_crop``` transformation for center crop transform.
+
+ Args:
+ batch_size (int): the tensor batch size.
+ height (int) : height of the image.
+ width (int): width of the image.
+ size (tuple): Desired output size of the crop, like (h, w).
+ device (torch.device): the device on which the random numbers will be generated. Default: cpu.
+
+ Returns:
+ params Dict[str, torch.Tensor]: parameters to be passed for transformation.
+ - src (torch.Tensor): cropping bounding boxes with a shape of (B, 4, 2).
+ - dst (torch.Tensor): output bounding boxes with a shape (B, 4, 2).
+
+ Note:
+ No random number will be generated.
+ """
+ _common_param_check(batch_size)
+ if not isinstance(size, (tuple, list)) and len(size) == 2:
+ raise ValueError(f"Input size must be a tuple/list of length 2. Got {size}")
+ 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}.")
+ if not (height >= size[0] and width >= size[1]):
+ raise AssertionError(f"Crop size must be smaller than input size. Got ({height}, {width}) and {size}.")
+
+ # unpack input sizes
+ dst_h, dst_w = size
+ src_h, src_w = height, width
+
+ # compute start/end offsets
+ dst_h_half = dst_h / 2
+ dst_w_half = dst_w / 2
+ src_h_half = src_h / 2
+ src_w_half = src_w / 2
+
+ start_x = int(src_w_half - dst_w_half)
+ start_y = int(src_h_half - dst_h_half)
+
+ end_x = start_x + dst_w - 1
+ end_y = start_y + dst_h - 1
+
+ # [y, x] origin
+ # top-left, top-right, bottom-right, bottom-left
+ points_src: torch.Tensor = torch.tensor(
+ [[[start_x, start_y], [end_x, start_y], [end_x, end_y], [start_x, end_y]]], device=device, dtype=torch.long
+ ).expand(batch_size, -1, -1)
+
+ # [y, x] destination
+ # top-left, top-right, bottom-right, bottom-left
+ points_dst: torch.Tensor = torch.tensor(
+ [[[0, 0], [dst_w - 1, 0], [dst_w - 1, dst_h - 1], [0, dst_h - 1]]], device=device, dtype=torch.long
+ ).expand(batch_size, -1, -1)
+
+ _input_size = torch.tensor((height, width), device=device, dtype=torch.long).expand(batch_size, -1)
+
+ return dict(src=points_src, dst=points_dst, input_size=_input_size)
diff --git a/kornia/augmentation/random_generator/_2d/cutmix.py b/kornia/augmentation/random_generator/_2d/cutmix.py
new file mode 100644
index 000000000..8a9481f42
--- /dev/null
+++ b/kornia/augmentation/random_generator/_2d/cutmix.py
@@ -0,0 +1,276 @@
+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.geometry.bbox import bbox_generator
+from kornia.utils.helpers import _extract_device_dtype
+
+
+class CutmixGenerator(RandomGeneratorBase):
+ r"""Generate cutmix indexes and lambdas for a batch of inputs.
+
+ Args:
+ 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.
+
+ 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. 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,
+ cut_size: Optional[Union[torch.Tensor, Tuple[float, float]]] = None,
+ beta: Optional[Union[torch.Tensor, float]] = None,
+ num_mix: int = 1,
+ p: float = 1.0,
+ ) -> None:
+ super().__init__()
+ self.cut_size = cut_size
+ self.beta = beta
+ self.num_mix = num_mix
+ self.p = p
+
+ 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}.")
+
+ def __repr__(self) -> str:
+ repr = f"cut_size={self.cut_size}, beta={self.beta}, num_mix={self.num_mix}"
+ return repr
+
+ 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)
+ else:
+ self._beta = torch.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)
+ else:
+ self._cut_size = torch.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.rand_sampler = Uniform(
+ torch.tensor(0.0, device=device, dtype=dtype),
+ torch.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]:
+ batch_size = batch_shape[0]
+ height = batch_shape[-2]
+ width = batch_shape[-1]
+
+ 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}.")
+ _device, _dtype = _extract_device_dtype([self.beta, self.cut_size])
+ _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),
+ )
+
+ 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)
+ 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:
+ # Argument 1 to "clamp" of "_TensorBase" has incompatible type "Tensor"; expected "float"
+ cutmix_betas = torch.min(torch.max(cutmix_betas, self._cut_size[0]), self._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: torch.Tensor = _adapted_rsampling(_gen_shape, self.rand_sampler, same_on_batch) * (
+ width - cut_width - 1
+ )
+ y_start: torch.Tensor = _adapted_rsampling(_gen_shape, self.rand_sampler, same_on_batch) * (
+ height - cut_height - 1
+ )
+ x_start = x_start.floor().to(device=_device, dtype=_dtype)
+ y_start = y_start.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(self.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),
+ )
+
+
+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),
+ )
+
+ 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/func.py b/kornia/augmentation/random_generator/_2d/func.py
new file mode 100644
index 000000000..0596903cd
--- /dev/null
+++ b/kornia/augmentation/random_generator/_2d/func.py
@@ -0,0 +1,138 @@
+from typing import Dict
+
+import torch
+
+from kornia.augmentation.utils import _adapted_uniform, _common_param_check, _joint_range_check
+from kornia.utils.helpers import _deprecated, _extract_device_dtype
+
+
+@_deprecated()
+def random_rotation_generator(
+ batch_size: int,
+ degrees: torch.Tensor,
+ same_on_batch: bool = False,
+ device: torch.device = torch.device('cpu'),
+ dtype: torch.dtype = torch.float32,
+) -> Dict[str, torch.Tensor]:
+ r"""Get parameters for ``rotate`` for a random rotate transform.
+
+ Args:
+ batch_size (int): the tensor batch size.
+ degrees (torch.Tensor): range of degrees with shape (2) to select from.
+ 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.
+ - degrees (torch.Tensor): element-wise rotation degrees with a shape of (B,).
+
+ Note:
+ The generated random numbers are not reproducible across different devices and dtypes.
+ """
+ _common_param_check(batch_size, same_on_batch)
+ _joint_range_check(degrees, "degrees")
+
+ _degrees = _adapted_uniform(
+ (batch_size,),
+ degrees[0].to(device=device, dtype=dtype),
+ degrees[1].to(device=device, dtype=dtype),
+ same_on_batch,
+ )
+ _degrees = _degrees.to(device=degrees.device, dtype=degrees.dtype)
+
+ return dict(degrees=_degrees)
+
+
+@_deprecated()
+def random_solarize_generator(
+ batch_size: int,
+ thresholds: torch.Tensor = torch.tensor([0.4, 0.6]),
+ additions: torch.Tensor = torch.tensor([-0.1, 0.1]),
+ same_on_batch: bool = False,
+ device: torch.device = torch.device('cpu'),
+ dtype: torch.dtype = torch.float32,
+) -> Dict[str, torch.Tensor]:
+ r"""Generate random solarize parameters for a batch of images.
+
+ For each pixel in the image less than threshold, we add 'addition' amount to it and then clip the pixel value
+ to be between 0 and 1.0
+
+ Args:
+ batch_size (int): the number of images.
+ thresholds (torch.Tensor): Pixels less than threshold will selected. Otherwise, subtract 1.0 from the pixel.
+ Takes in a range tensor of (0, 1). Default value will be sampled from [0.4, 0.6].
+ additions (torch.Tensor): The value is between -0.5 and 0.5. Default value will be sampled from [-0.1, 0.1]
+ 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.
+ - thresholds_factor (torch.Tensor): element-wise thresholds factors with a shape of (B,).
+ - additions_factor (torch.Tensor): element-wise additions factors with a shape of (B,).
+
+ Note:
+ The generated random numbers are not reproducible across different devices and dtypes.
+ """
+ _common_param_check(batch_size, same_on_batch)
+ _joint_range_check(thresholds, 'thresholds', (0, 1))
+ _joint_range_check(additions, 'additions', (-0.5, 0.5))
+
+ _device, _dtype = _extract_device_dtype([thresholds, additions])
+
+ thresholds_factor = _adapted_uniform(
+ (batch_size,),
+ thresholds[0].to(device=device, dtype=dtype),
+ thresholds[1].to(device=device, dtype=dtype),
+ same_on_batch,
+ )
+
+ additions_factor = _adapted_uniform(
+ (batch_size,),
+ additions[0].to(device=device, dtype=dtype),
+ additions[1].to(device=device, dtype=dtype),
+ same_on_batch,
+ )
+
+ return dict(
+ thresholds_factor=thresholds_factor.to(device=_device, dtype=_dtype),
+ additions_factor=additions_factor.to(device=_device, dtype=_dtype),
+ )
+
+
+@_deprecated()
+def random_sharpness_generator(
+ batch_size: int,
+ sharpness: torch.Tensor = torch.tensor([0, 1.0]),
+ same_on_batch: bool = False,
+ device: torch.device = torch.device('cpu'),
+ dtype: torch.dtype = torch.float32,
+) -> Dict[str, torch.Tensor]:
+ r"""Generate random sharpness parameters for a batch of images.
+
+ Args:
+ batch_size (int): the number of images.
+ sharpness (torch.Tensor): Must be above 0. Default value is sampled from (0, 1).
+ 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.
+ - sharpness_factor (torch.Tensor): element-wise sharpness factors with a shape of (B,).
+
+ Note:
+ The generated random numbers are not reproducible across different devices and dtypes.
+ """
+ _common_param_check(batch_size, same_on_batch)
+ _joint_range_check(sharpness, 'sharpness', bounds=(0, float('inf')))
+
+ sharpness_factor = _adapted_uniform(
+ (batch_size,),
+ sharpness[0].to(device=device, dtype=dtype),
+ sharpness[1].to(device=device, dtype=dtype),
+ same_on_batch,
+ )
+
+ return dict(sharpness_factor=sharpness_factor.to(device=sharpness.device, dtype=sharpness.dtype))
diff --git a/kornia/augmentation/random_generator/_2d/mixup.py b/kornia/augmentation/random_generator/_2d/mixup.py
new file mode 100644
index 000000000..dc3b8fac7
--- /dev/null
+++ b/kornia/augmentation/random_generator/_2d/mixup.py
@@ -0,0 +1,122 @@
+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.utils.helpers import _extract_device_dtype
+
+
+class MixupGenerator(RandomGeneratorBase):
+ r"""Generate mixup indexes and lambdas for a batch of inputs.
+
+ Args:
+ 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.
+
+ Returns:
+ A dict of 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. 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, lambda_val: Optional[Union[torch.Tensor, Tuple[float, float]]] = None, p: float = 1.0) -> None:
+ super().__init__()
+ self.lambda_val = lambda_val
+ self.p = p
+
+ def __repr__(self) -> str:
+ repr = f"lambda_val={self.lambda_val}"
+ return repr
+
+ def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
+ if self.lambda_val is None:
+ lambda_val = torch.tensor([0.0, 1.0], device=device, dtype=dtype)
+ else:
+ lambda_val = torch.as_tensor(self.lambda_val, device=device, dtype=dtype)
+
+ _joint_range_check(lambda_val, 'lambda_val', bounds=(0, 1))
+ self.lambda_sampler = Uniform(lambda_val[0], lambda_val[1], validate_args=False)
+ self.prob_sampler = Bernoulli(torch.tensor(float(self.p), device=device, dtype=dtype))
+
+ def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, torch.Tensor]:
+ batch_size = batch_shape[0]
+
+ _common_param_check(batch_size, same_on_batch)
+ _device, _dtype = _extract_device_dtype([self.lambda_val])
+
+ with torch.no_grad():
+ batch_probs: torch.Tensor = _adapted_sampling((batch_size,), self.prob_sampler, same_on_batch)
+ mixup_pairs: torch.Tensor = torch.randperm(batch_size, device=_device, dtype=_dtype).long()
+ mixup_lambdas: torch.Tensor = _adapted_rsampling((batch_size,), self.lambda_sampler, 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),
+ )
+
+
+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/motion_blur.py b/kornia/augmentation/random_generator/_2d/motion_blur.py
new file mode 100644
index 000000000..a218a47de
--- /dev/null
+++ b/kornia/augmentation/random_generator/_2d/motion_blur.py
@@ -0,0 +1,162 @@
+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,
+ _adapted_uniform,
+ _common_param_check,
+ _joint_range_check,
+ _range_bound,
+)
+from kornia.utils.helpers import _deprecated, _extract_device_dtype
+
+
+class MotionBlurGenerator(RandomGeneratorBase):
+ r"""Get parameters for motion blur.
+
+ Args:
+ kernel_size: motion kernel size (odd and positive).
+ If int, the kernel will have a fixed size.
+ If Tuple[int, int], it will randomly generate the value from the range batch-wisely.
+ angle: angle of the motion blur in degrees (anti-clockwise rotation).
+ If float, it will generate the value from (-angle, angle).
+ direction: forward/backward direction of the motion blur.
+ Lower values towards -1.0 will point the motion blur towards the back (with angle provided via angle),
+ while higher values towards 1.0 will point the motion blur forward. A value of 0.0 leads to a
+ uniformly (but still angled) motion blur.
+ If float, it will generate the value from (-direction, direction).
+ If Tuple[int, int], it will randomly generate the value from the range.
+
+ Returns:
+ A dict of parameters to be passed for transformation.
+ - ksize_factor (torch.Tensor): element-wise kernel size factors with a shape of (B,).
+ - angle_factor (torch.Tensor): element-wise angle factors with a shape of (B,).
+ - direction_factor (torch.Tensor): element-wise direction factors 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,
+ kernel_size: Union[int, Tuple[int, int]],
+ angle: Union[torch.Tensor, float, Tuple[float, float]],
+ direction: Union[torch.Tensor, float, Tuple[float, float]],
+ ) -> None:
+ super().__init__()
+ self.kernel_size = kernel_size
+ self.angle = angle
+ self.direction = direction
+
+ def __repr__(self) -> str:
+ repr = f"kernel_size={self.kernel_size}, angle={self.angle}, direction={self.direction}"
+ return repr
+
+ def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
+ angle = _range_bound(self.angle, 'angle', center=0.0, bounds=(-360, 360)).to(device=device, dtype=dtype)
+ direction = _range_bound(self.direction, 'direction', center=0.0, bounds=(-1, 1)).to(device=device, dtype=dtype)
+ if isinstance(self.kernel_size, int):
+ if not (self.kernel_size >= 3 and self.kernel_size % 2 == 1):
+ raise AssertionError(f"`kernel_size` must be odd and greater than 3. Got {self.kernel_size}.")
+ self.ksize_sampler = Uniform(self.kernel_size // 2, self.kernel_size // 2, validate_args=False)
+ elif isinstance(self.kernel_size, tuple):
+ # kernel_size is fixed across the batch
+ if len(self.kernel_size) != 2:
+ raise AssertionError(f"`kernel_size` must be (2,) if it is a tuple. Got {self.kernel_size}.")
+ self.ksize_sampler = Uniform(self.kernel_size[0] // 2, self.kernel_size[1] // 2, validate_args=False)
+ else:
+ raise TypeError(f"Unsupported type: {type(self.kernel_size)}")
+
+ self.angle_sampler = Uniform(angle[0], angle[1], validate_args=False)
+ self.direction_sampler = Uniform(direction[0], direction[1], validate_args=False)
+
+ def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, torch.Tensor]: # type:ignore
+ batch_size = batch_shape[0]
+ _common_param_check(batch_size, same_on_batch)
+ # self.ksize_factor.expand((batch_size, -1))
+ _device, _dtype = _extract_device_dtype([self.angle, self.direction])
+ angle_factor = _adapted_rsampling((batch_size,), self.angle_sampler, same_on_batch)
+ direction_factor = _adapted_rsampling((batch_size,), self.direction_sampler, same_on_batch)
+ ksize_factor = _adapted_rsampling((batch_size,), self.ksize_sampler, same_on_batch).int() * 2 + 1
+
+ return dict(
+ ksize_factor=ksize_factor.to(device=_device, dtype=torch.int32),
+ angle_factor=angle_factor.to(device=_device, dtype=_dtype),
+ direction_factor=direction_factor.to(device=_device, dtype=_dtype),
+ )
+
+
+@_deprecated(replace_with=MotionBlurGenerator.__name__)
+def random_motion_blur_generator(
+ batch_size: int,
+ kernel_size: Union[int, Tuple[int, int]],
+ angle: torch.Tensor,
+ direction: torch.Tensor,
+ same_on_batch: bool = False,
+ device: torch.device = torch.device('cpu'),
+ dtype: torch.dtype = torch.float32,
+) -> Dict[str, torch.Tensor]:
+ r"""Get parameters for motion blur.
+
+ Args:
+ batch_size (int): the tensor batch size.
+ kernel_size (int or (int, int)): motion kernel size (odd and positive) or range.
+ angle (torch.Tensor): angle of the motion blur in degrees (anti-clockwise rotation).
+ direction (torch.Tensor): forward/backward direction of the motion blur.
+ Lower values towards -1.0 will point the motion blur towards the back (with
+ angle provided via angle), while higher values towards 1.0 will point the motion
+ blur forward. A value of 0.0 leads to a uniformly (but still angled) motion blur.
+ 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.
+ - ksize_factor (torch.Tensor): element-wise kernel size factors with a shape of (B,).
+ - angle_factor (torch.Tensor): element-wise angle factors with a shape of (B,).
+ - direction_factor (torch.Tensor): element-wise direction factors with a shape of (B,).
+
+ Note:
+ The generated random numbers are not reproducible across different devices and dtypes.
+ """
+ _common_param_check(batch_size, same_on_batch)
+ _joint_range_check(angle, 'angle')
+ _joint_range_check(direction, 'direction', (-1, 1))
+
+ _device, _dtype = _extract_device_dtype([angle, direction])
+
+ if isinstance(kernel_size, int):
+ if not (kernel_size >= 3 and kernel_size % 2 == 1):
+ raise AssertionError(f"`kernel_size` must be odd and greater than 3. Got {kernel_size}.")
+ ksize_factor = torch.tensor([kernel_size] * batch_size, device=device, dtype=dtype)
+ elif isinstance(kernel_size, tuple):
+ # kernel_size is fixed across the batch
+ if len(kernel_size) != 2:
+ raise AssertionError(f"`kernel_size` must be (2,) if it is a tuple. Got {kernel_size}.")
+ ksize_factor = (
+ _adapted_uniform((batch_size,), kernel_size[0] // 2, kernel_size[1] // 2, same_on_batch=True).int() * 2 + 1
+ )
+ else:
+ raise TypeError(f"Unsupported type: {type(kernel_size)}")
+
+ angle_factor = _adapted_uniform(
+ (batch_size,), angle[0].to(device=device, dtype=dtype), angle[1].to(device=device, dtype=dtype), same_on_batch
+ )
+
+ direction_factor = _adapted_uniform(
+ (batch_size,),
+ direction[0].to(device=device, dtype=dtype),
+ direction[1].to(device=device, dtype=dtype),
+ same_on_batch,
+ )
+
+ return dict(
+ ksize_factor=ksize_factor.to(device=_device, dtype=torch.int32),
+ angle_factor=angle_factor.to(device=_device, dtype=_dtype),
+ direction_factor=direction_factor.to(device=_device, dtype=_dtype),
+ )
diff --git a/kornia/augmentation/random_generator/_2d/perspective.py b/kornia/augmentation/random_generator/_2d/perspective.py
new file mode 100644
index 000000000..d5141e503
--- /dev/null
+++ b/kornia/augmentation/random_generator/_2d/perspective.py
@@ -0,0 +1,138 @@
+from typing import Dict, Union
+
+import torch
+from torch.distributions import Uniform
+
+from kornia.augmentation.random_generator.base import RandomGeneratorBase
+from kornia.augmentation.utils import _adapted_rsampling, _adapted_uniform, _common_param_check
+from kornia.utils.helpers import _deprecated, _extract_device_dtype
+
+
+class PerspectiveGenerator(RandomGeneratorBase):
+ r"""Get parameters for ``perspective`` for a random perspective transform.
+
+ Args:
+ distortion_scale: the degree of distortion, ranged from 0 to 1.
+
+ Returns:
+ A dict of parameters to be passed for transformation.
+ - start_points (torch.Tensor): element-wise perspective source areas with a shape of (B, 4, 2).
+ - end_points (torch.Tensor): element-wise perspective target areas with a shape of (B, 4, 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, distortion_scale: Union[torch.Tensor, float] = 0.5) -> None:
+ super().__init__()
+ self.distortion_scale = distortion_scale
+
+ def __repr__(self) -> str:
+ repr = f"distortion_scale={self.distortion_scale}"
+ return repr
+
+ def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
+ self._distortion_scale = torch.as_tensor(self.distortion_scale, device=device, dtype=dtype)
+ if not (self._distortion_scale.dim() == 0 and 0 <= self._distortion_scale <= 1):
+ raise AssertionError(f"'distortion_scale' must be a scalar within [0, 1]. Got {self._distortion_scale}.")
+ self.rand_val_sampler = Uniform(
+ torch.tensor(0, device=device, dtype=dtype),
+ torch.tensor(1, device=device, dtype=dtype),
+ validate_args=False,
+ )
+
+ def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, torch.Tensor]: # type:ignore
+ batch_size = batch_shape[0]
+ height = batch_shape[-2]
+ width = batch_shape[-1]
+
+ _device, _dtype = _extract_device_dtype([self.distortion_scale])
+ _common_param_check(batch_size, same_on_batch)
+ 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}.")
+
+ start_points: torch.Tensor = torch.tensor(
+ [[[0.0, 0], [width - 1, 0], [width - 1, height - 1], [0, height - 1]]], device=_device, dtype=_dtype
+ ).expand(batch_size, -1, -1)
+
+ # generate random offset not larger than half of the image
+ fx = self._distortion_scale * width / 2
+ fy = self._distortion_scale * height / 2
+
+ factor = torch.stack([fx, fy], dim=0).view(-1, 1, 2).to(device=_device, dtype=_dtype)
+
+ # TODO: This line somehow breaks the gradcheck
+ rand_val: torch.Tensor = _adapted_rsampling(start_points.shape, self.rand_val_sampler, same_on_batch).to(
+ device=_device, dtype=_dtype
+ )
+
+ pts_norm = torch.tensor([[[1, 1], [-1, 1], [-1, -1], [1, -1]]], device=_device, dtype=_dtype)
+
+ end_points = start_points + factor * rand_val * pts_norm
+
+ return dict(start_points=start_points, end_points=end_points)
+
+
+@_deprecated(replace_with=PerspectiveGenerator.__name__)
+def random_perspective_generator(
+ batch_size: int,
+ height: int,
+ width: int,
+ distortion_scale: torch.Tensor,
+ same_on_batch: bool = False,
+ device: torch.device = torch.device('cpu'),
+ dtype: torch.dtype = torch.float32,
+) -> Dict[str, torch.Tensor]:
+ r"""Get parameters for ``perspective`` for a random perspective transform.
+
+ Args:
+ batch_size (int): the tensor batch size.
+ height (int) : height of the image.
+ width (int): width of the image.
+ distortion_scale (torch.Tensor): it controls the degree of distortion and ranges from 0 to 1.
+ 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.
+ - start_points (torch.Tensor): element-wise perspective source areas with a shape of (B, 4, 2).
+ - end_points (torch.Tensor): element-wise perspective target areas with a shape of (B, 4, 2).
+
+ Note:
+ The generated random numbers are not reproducible across different devices and dtypes.
+ """
+ _common_param_check(batch_size, same_on_batch)
+ if not (distortion_scale.dim() == 0 and 0 <= distortion_scale <= 1):
+ raise AssertionError(f"'distortion_scale' must be a scalar within [0, 1]. Got {distortion_scale}.")
+ 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}.")
+
+ start_points: torch.Tensor = torch.tensor(
+ [[[0.0, 0], [width - 1, 0], [width - 1, height - 1], [0, height - 1]]],
+ device=distortion_scale.device,
+ dtype=distortion_scale.dtype,
+ ).expand(batch_size, -1, -1)
+
+ # generate random offset not larger than half of the image
+ fx = distortion_scale * width / 2
+ fy = distortion_scale * height / 2
+
+ factor = torch.stack([fx, fy], dim=0).view(-1, 1, 2)
+
+ # TODO: This line somehow breaks the gradcheck
+ rand_val: torch.Tensor = _adapted_uniform(
+ start_points.shape,
+ torch.tensor(0, device=device, dtype=dtype),
+ torch.tensor(1, device=device, dtype=dtype),
+ same_on_batch,
+ ).to(device=distortion_scale.device, dtype=distortion_scale.dtype)
+
+ pts_norm = torch.tensor(
+ [[[1, 1], [-1, 1], [-1, -1], [1, -1]]], device=distortion_scale.device, dtype=distortion_scale.dtype
+ )
+ end_points = start_points + factor * rand_val * pts_norm
+
+ return dict(start_points=start_points, end_points=end_points)
diff --git a/kornia/augmentation/random_generator/_2d/plain_uniform.py b/kornia/augmentation/random_generator/_2d/plain_uniform.py
new file mode 100644
index 000000000..6f380b27e
--- /dev/null
+++ b/kornia/augmentation/random_generator/_2d/plain_uniform.py
@@ -0,0 +1,78 @@
+from typing import Any, Dict, Optional, Tuple
+
+import torch
+from torch.distributions import Distribution, Uniform
+
+from kornia.augmentation.random_generator.base import RandomGeneratorBase
+from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _range_bound
+from kornia.utils.helpers import _extract_device_dtype
+
+# factor, name, center, range
+ParameterBound = Tuple[Any, str, Optional[float], Optional[Tuple[float, float]]]
+
+
+class PlainUniformGenerator(RandomGeneratorBase):
+ r"""Generate random parameters that distributed uniformly.
+
+ Args:
+ *samplers: a list of tuple in a pattern of ``(factor, name, center, range)``, in which
+ the factor can be a two-numbered tuple, or a ``(2,)`` shaped torch tensor. The name
+ will be the corresponding key of the returning dict. The center and range must be
+ both provided worked as a validator to the given factor.
+
+ Returns:
+ A dict of parameters to be passed for transformation according the number of samplers
+ and the pointed returning name of each tuple.
+ - ``name``: element-wise probabilities 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)``.
+
+ Example:
+ >>> _ = torch.manual_seed(44)
+ >>> PlainUniformGenerator(
+ ... ((0., 1.), "factor_1", None, None),
+ ... (torch.tensor([-0.5, 0.5]), "factor_2", 0.1, (-1., 1.)),
+ ... )(torch.Size([2]))
+ {'factor_1': tensor([0.7196, 0.7307]), 'factor_2': tensor([ 0.3278, -0.3657])}
+ """
+
+ def __init__(self, *samplers: ParameterBound) -> None:
+ super().__init__()
+ self.samplers = samplers
+ names = []
+ for factor, name, _, _ in samplers:
+ if name in names:
+ raise RuntimeError(f"factor name `{name}` has already been registered. Please check the duplication.")
+ names.append(name)
+ if isinstance(factor, torch.nn.Parameter):
+ self.register_parameter(name, factor)
+ elif isinstance(factor, torch.Tensor):
+ self.register_buffer(name, factor)
+
+ def __repr__(self) -> str:
+ repr = ", ".join([f"{name}={factor}" for factor, name, _, _ in self.samplers])
+ return repr
+
+ def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
+ self.sampler_dict: Dict[str, Distribution] = {}
+ for factor, name, center, bound in self.samplers:
+ if center is None and bound is None:
+ factor = torch.as_tensor(factor, device=device, dtype=dtype)
+ elif center is None or bound is None:
+ raise ValueError(f"`center` and `bound` should be both None or provided. Got {center} and {bound}.")
+ else:
+ factor = _range_bound(factor, name, center=center, bounds=bound, device=device, dtype=dtype)
+ self.sampler_dict.update({name: Uniform(factor[0], factor[1], validate_args=False)})
+
+ def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, torch.Tensor]: # type:ignore
+ batch_size = batch_shape[0]
+ _common_param_check(batch_size, same_on_batch)
+ _device, _dtype = _extract_device_dtype([t for t, _, _, _ in self.samplers])
+
+ return {
+ name: _adapted_rsampling((batch_size,), dist, same_on_batch).to(device=_device, dtype=_dtype)
+ for name, dist in self.sampler_dict.items()
+ }
diff --git a/kornia/augmentation/random_generator/_2d/posterize.py b/kornia/augmentation/random_generator/_2d/posterize.py
new file mode 100644
index 000000000..d4cdcf892
--- /dev/null
+++ b/kornia/augmentation/random_generator/_2d/posterize.py
@@ -0,0 +1,85 @@
+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, _adapted_uniform, _common_param_check, _joint_range_check
+from kornia.utils.helpers import _deprecated, _extract_device_dtype
+
+
+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).
+ If tuple (x, y), bits will be generated from (x, y).
+
+ Returns:
+ A dict of parameters to be passed for transformation.
+ - bits_factor (torch.Tensor): element-wise bit factors 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, bits: Union[int, Tuple[int, int], torch.Tensor]) -> None:
+ super().__init__()
+ self.bits = bits
+
+ def __repr__(self) -> str:
+ repr = f"bits={self.bits}"
+ return repr
+
+ def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
+ bits = torch.as_tensor(self.bits, device=device, dtype=dtype)
+ if len(bits.size()) == 0:
+ bits = bits.repeat(2)
+ bits[1] = 8
+ elif not (len(bits.size()) == 1 and bits.size(0) == 2):
+ raise ValueError(f"'bits' shall be either a scalar or a length 2 tensor. Got {bits}.")
+ _joint_range_check(bits, 'bits', (0, 8))
+ self.bit_sampler = Uniform(bits[0], bits[1], validate_args=False)
+
+ def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, torch.Tensor]: # type:ignore
+ batch_size = batch_shape[0]
+ _common_param_check(batch_size, same_on_batch)
+ _device, _dtype = _extract_device_dtype([self.bits if isinstance(self.bits, torch.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))
+
+
+@_deprecated()
+def random_posterize_generator(
+ batch_size: int,
+ bits: torch.Tensor = torch.tensor([3, 5]),
+ same_on_batch: bool = False,
+ device: torch.device = torch.device('cpu'),
+ dtype: torch.dtype = torch.float32,
+) -> Dict[str, torch.Tensor]:
+ r"""Generate random posterize parameters for a batch of images.
+
+ Args:
+ batch_size (int): the number of images.
+ bits (int or tuple): Takes in an integer tuple tensor that ranged from 0 ~ 8. Default value is [3, 5].
+ 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.
+ - bits_factor (torch.Tensor): element-wise bit factors with a shape of (B,).
+
+ Note:
+ The generated random numbers are not reproducible across different devices and dtypes.
+ """
+ _common_param_check(batch_size, same_on_batch)
+ _joint_range_check(bits, 'bits', (0, 8))
+ bits_factor = _adapted_uniform(
+ (batch_size,), bits[0].to(device=device, dtype=dtype), bits[1].to(device=device, dtype=dtype), same_on_batch
+ ).int()
+
+ return dict(bits_factor=bits_factor.to(device=bits.device, dtype=torch.int32))
diff --git a/kornia/augmentation/random_generator/_2d/probability.py b/kornia/augmentation/random_generator/_2d/probability.py
new file mode 100644
index 000000000..74057c7a0
--- /dev/null
+++ b/kornia/augmentation/random_generator/_2d/probability.py
@@ -0,0 +1,74 @@
+from typing import Dict
+
+import torch
+from torch.distributions import Bernoulli
+
+from kornia.augmentation.random_generator.base import RandomGeneratorBase
+from kornia.augmentation.utils import _adapted_sampling, _common_param_check
+
+
+class ProbabilityGenerator(RandomGeneratorBase):
+ r"""Generate random probabilities for a batch of inputs.
+
+ Args:
+ p: probability to generate an 1-d binary mask. Default value is 0.5.
+
+ Returns:
+ A dict of parameters to be passed for transformation.
+ - probs (torch.Tensor): element-wise probabilities 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, p: float = 0.5) -> None:
+ super().__init__()
+ self.p = p
+
+ def __repr__(self) -> str:
+ repr = f"p={self.p}"
+ return repr
+
+ def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
+ p = torch.tensor(float(self.p), device=device, dtype=dtype)
+ self.sampler = Bernoulli(p)
+
+ def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, torch.Tensor]: # type:ignore
+ batch_size = batch_shape[0]
+ probs_mask: torch.Tensor = _adapted_sampling((batch_size,), self.sampler, same_on_batch).bool()
+ return dict(probs=probs_mask)
+
+
+def random_prob_generator(
+ batch_size: int,
+ p: float = 0.5,
+ same_on_batch: bool = False,
+ device: torch.device = torch.device('cpu'),
+ dtype: torch.dtype = torch.float32,
+) -> torch.Tensor:
+ r"""Generate random probabilities for a batch of inputs.
+
+ Args:
+ batch_size (int): the number of images.
+ p (float): probability to generate an 1-d binary mask. Default value is 0.5.
+ 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:
+ torch.Tensor: parameters to be passed for transformation.
+ - probs (torch.Tensor): element-wise probabilities with a shape of (B,).
+
+ Note:
+ The generated random numbers are not reproducible across different devices and dtypes.
+ """
+ _common_param_check(batch_size, same_on_batch)
+ if not isinstance(p, (int, float)) or p > 1 or p < 0:
+ raise TypeError(f"The probability should be a float number within [0, 1]. Got {type(p)}.")
+
+ _bernoulli = Bernoulli(torch.tensor(float(p), device=device, dtype=dtype))
+ probs_mask: torch.Tensor = _adapted_sampling((batch_size,), _bernoulli, same_on_batch).bool()
+
+ return probs_mask
diff --git a/kornia/augmentation/random_generator/_2d/rectangle_earase.py b/kornia/augmentation/random_generator/_2d/rectangle_earase.py
new file mode 100644
index 000000000..d96ffd30b
--- /dev/null
+++ b/kornia/augmentation/random_generator/_2d/rectangle_earase.py
@@ -0,0 +1,266 @@
+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, _adapted_uniform, _common_param_check, _joint_range_check
+from kornia.utils.helpers import _deprecated, _extract_device_dtype
+
+
+class RectangleEraseGenerator(RandomGeneratorBase):
+ r"""Get parameters for ```erasing``` transformation for erasing transform.
+
+ Args:
+ scale (torch.Tensor): range of size of the origin size cropped. Shape (2).
+ ratio (torch.Tensor): range of aspect ratio of the origin aspect ratio cropped. Shape (2).
+ value (float): value to be filled in the erased area.
+
+ Returns:
+ A dict of parameters to be passed for transformation.
+ - widths (torch.Tensor): element-wise erasing widths with a shape of (B,).
+ - heights (torch.Tensor): element-wise erasing heights with a shape of (B,).
+ - xs (torch.Tensor): element-wise erasing x coordinates with a shape of (B,).
+ - ys (torch.Tensor): element-wise erasing y coordinates with a shape of (B,).
+ - values (torch.Tensor): element-wise filling values 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,
+ scale: Union[torch.Tensor, Tuple[float, float]] = (0.02, 0.33),
+ ratio: Union[torch.Tensor, Tuple[float, float]] = (0.3, 3.3),
+ value: float = 0.0,
+ ) -> None:
+ super().__init__()
+ self.scale = scale
+ self.ratio = ratio
+ self.value = value
+
+ def __repr__(self) -> str:
+ repr = f"scale={self.scale}, resize_to={self.ratio}, value={self.value}"
+ return repr
+
+ def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
+ scale = torch.as_tensor(self.scale, device=device, dtype=dtype)
+ ratio = torch.as_tensor(self.ratio, device=device, dtype=dtype)
+
+ if not (isinstance(self.value, (int, float)) and self.value >= 0 and self.value <= 1):
+ raise AssertionError(f"'value' must be a number between 0 - 1. Got {self.value}.")
+ _joint_range_check(scale, 'scale', bounds=(0, float('inf')))
+ _joint_range_check(ratio, 'ratio', bounds=(0, float('inf')))
+
+ self.scale_sampler = Uniform(scale[0], scale[1], validate_args=False)
+
+ if ratio[0] < 1.0 and ratio[1] > 1.0:
+ self.ratio_sampler1 = Uniform(ratio[0], 1, validate_args=False)
+ self.ratio_sampler2 = Uniform(1, ratio[1], validate_args=False)
+ self.index_sampler = Uniform(
+ torch.tensor(0, device=device, dtype=dtype),
+ torch.tensor(1, device=device, dtype=dtype),
+ validate_args=False,
+ )
+ else:
+ self.ratio_sampler = Uniform(ratio[0], ratio[1], validate_args=False)
+ self.uniform_sampler = Uniform(
+ torch.tensor(0, device=device, dtype=dtype),
+ torch.tensor(1, device=device, dtype=dtype),
+ validate_args=False,
+ )
+
+ def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, torch.Tensor]: # type:ignore
+ batch_size = batch_shape[0]
+ height = batch_shape[-2]
+ width = batch_shape[-1]
+ 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}.")
+
+ _common_param_check(batch_size, same_on_batch)
+ _device, _dtype = _extract_device_dtype([self.ratio, self.scale])
+ images_area = height * width
+ target_areas = (
+ _adapted_rsampling((batch_size,), self.scale_sampler, same_on_batch).to(device=_device, dtype=_dtype)
+ * images_area
+ )
+
+ if self.ratio[0] < 1.0 and self.ratio[1] > 1.0:
+ aspect_ratios1 = _adapted_rsampling((batch_size,), self.ratio_sampler1, same_on_batch)
+ aspect_ratios2 = _adapted_rsampling((batch_size,), self.ratio_sampler2, same_on_batch)
+ if same_on_batch:
+ rand_idxs = (
+ torch.round(_adapted_rsampling((1,), self.index_sampler, same_on_batch)).repeat(batch_size).bool()
+ )
+ else:
+ rand_idxs = torch.round(_adapted_rsampling((batch_size,), self.index_sampler, same_on_batch)).bool()
+ aspect_ratios = torch.where(rand_idxs, aspect_ratios1, aspect_ratios2)
+ else:
+ aspect_ratios = _adapted_rsampling((batch_size,), self.ratio_sampler, same_on_batch)
+
+ aspect_ratios = aspect_ratios.to(device=_device, dtype=_dtype)
+
+ # based on target areas and aspect ratios, rectangle params are computed
+ heights = torch.min(
+ torch.max(
+ torch.round((target_areas * aspect_ratios) ** (1 / 2)), torch.tensor(1.0, device=_device, dtype=_dtype)
+ ),
+ torch.tensor(height, device=_device, dtype=_dtype),
+ )
+
+ widths = torch.min(
+ torch.max(
+ torch.round((target_areas / aspect_ratios) ** (1 / 2)), torch.tensor(1.0, device=_device, dtype=_dtype)
+ ),
+ torch.tensor(width, device=_device, dtype=_dtype),
+ )
+
+ xs_ratio = _adapted_rsampling((batch_size,), self.uniform_sampler, same_on_batch).to(
+ device=_device, dtype=_dtype
+ )
+ ys_ratio = _adapted_rsampling((batch_size,), self.uniform_sampler, same_on_batch).to(
+ device=_device, dtype=_dtype
+ )
+
+ xs = xs_ratio * (width - widths + 1)
+ ys = ys_ratio * (height - heights + 1)
+
+ return dict(
+ widths=widths.floor(),
+ heights=heights.floor(),
+ xs=xs.floor(),
+ ys=ys.floor(),
+ values=torch.tensor([self.value] * batch_size, device=_device, dtype=_dtype),
+ )
+
+
+@_deprecated(replace_with=RectangleEraseGenerator.__name__)
+def random_rectangles_params_generator(
+ batch_size: int,
+ height: int,
+ width: int,
+ scale: torch.Tensor,
+ ratio: torch.Tensor,
+ value: float = 0.0,
+ same_on_batch: bool = False,
+ device: torch.device = torch.device('cpu'),
+ dtype: torch.dtype = torch.float32,
+) -> Dict[str, torch.Tensor]:
+ r"""Get parameters for ```erasing``` transformation for erasing transform.
+
+ Args:
+ batch_size (int): the tensor batch size.
+ height (int) : height of the image.
+ width (int): width of the image.
+ scale (torch.Tensor): range of size of the origin size cropped. Shape (2).
+ ratio (torch.Tensor): range of aspect ratio of the origin aspect ratio cropped. Shape (2).
+ value (float): value to be filled in the erased area.
+ 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.
+ - widths (torch.Tensor): element-wise erasing widths with a shape of (B,).
+ - heights (torch.Tensor): element-wise erasing heights with a shape of (B,).
+ - xs (torch.Tensor): element-wise erasing x coordinates with a shape of (B,).
+ - ys (torch.Tensor): element-wise erasing y coordinates with a shape of (B,).
+ - values (torch.Tensor): element-wise filling values with a shape of (B,).
+
+ Note:
+ The generated random numbers are not reproducible across different devices and dtypes.
+ """
+ _common_param_check(batch_size, same_on_batch)
+ _device, _dtype = _extract_device_dtype([ratio, scale])
+ 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}.")
+ if not (isinstance(value, (int, float)) and value >= 0 and value <= 1):
+ raise AssertionError(f"'value' must be a number between 0 - 1. Got {value}.")
+ _joint_range_check(scale, 'scale', bounds=(0, float('inf')))
+ _joint_range_check(ratio, 'ratio', bounds=(0, float('inf')))
+
+ images_area = height * width
+ target_areas = (
+ _adapted_uniform(
+ (batch_size,),
+ scale[0].to(device=device, dtype=dtype),
+ scale[1].to(device=device, dtype=dtype),
+ same_on_batch,
+ )
+ * images_area
+ )
+
+ if ratio[0] < 1.0 and ratio[1] > 1.0:
+ aspect_ratios1 = _adapted_uniform((batch_size,), ratio[0].to(device=device, dtype=dtype), 1, same_on_batch)
+ aspect_ratios2 = _adapted_uniform((batch_size,), 1, ratio[1].to(device=device, dtype=dtype), same_on_batch)
+ if same_on_batch:
+ rand_idxs = (
+ torch.round(
+ _adapted_uniform(
+ (1,),
+ torch.tensor(0, device=device, dtype=dtype),
+ torch.tensor(1, device=device, dtype=dtype),
+ same_on_batch,
+ )
+ )
+ .repeat(batch_size)
+ .bool()
+ )
+ else:
+ rand_idxs = torch.round(
+ _adapted_uniform(
+ (batch_size,),
+ torch.tensor(0, device=device, dtype=dtype),
+ torch.tensor(1, device=device, dtype=dtype),
+ same_on_batch,
+ )
+ ).bool()
+ aspect_ratios = torch.where(rand_idxs, aspect_ratios1, aspect_ratios2)
+ else:
+ aspect_ratios = _adapted_uniform(
+ (batch_size,),
+ ratio[0].to(device=device, dtype=dtype),
+ ratio[1].to(device=device, dtype=dtype),
+ same_on_batch,
+ )
+
+ # based on target areas and aspect ratios, rectangle params are computed
+ heights = torch.min(
+ torch.max(
+ torch.round((target_areas * aspect_ratios) ** (1 / 2)), torch.tensor(1.0, device=device, dtype=dtype)
+ ),
+ torch.tensor(height, device=device, dtype=dtype),
+ )
+
+ widths = torch.min(
+ torch.max(
+ torch.round((target_areas / aspect_ratios) ** (1 / 2)), torch.tensor(1.0, device=device, dtype=dtype)
+ ),
+ torch.tensor(width, device=device, dtype=dtype),
+ )
+
+ xs_ratio = _adapted_uniform(
+ (batch_size,),
+ torch.tensor(0, device=device, dtype=dtype),
+ torch.tensor(1, device=device, dtype=dtype),
+ same_on_batch,
+ )
+ ys_ratio = _adapted_uniform(
+ (batch_size,),
+ torch.tensor(0, device=device, dtype=dtype),
+ torch.tensor(1, device=device, dtype=dtype),
+ same_on_batch,
+ )
+
+ xs = xs_ratio * (torch.tensor(width, device=device, dtype=dtype) - widths + 1)
+ ys = ys_ratio * (torch.tensor(height, device=device, dtype=dtype) - heights + 1)
+
+ return dict(
+ widths=widths.floor().to(device=_device, dtype=_dtype),
+ heights=heights.floor().to(device=_device, dtype=_dtype),
+ xs=xs.floor().to(device=_device, dtype=_dtype),
+ ys=ys.floor().to(device=_device, dtype=_dtype),
+ values=torch.tensor([value] * batch_size, device=_device, dtype=_dtype),
+ )
diff --git a/kornia/augmentation/random_generator/_3d/__init__.py b/kornia/augmentation/random_generator/_3d/__init__.py
new file mode 100644
index 000000000..2d42c8f98
--- /dev/null
+++ b/kornia/augmentation/random_generator/_3d/__init__.py
@@ -0,0 +1,5 @@
+from kornia.augmentation.random_generator._3d.affine import *
+from kornia.augmentation.random_generator._3d.crop import *
+from kornia.augmentation.random_generator._3d.motion_blur import *
+from kornia.augmentation.random_generator._3d.perspective import *
+from kornia.augmentation.random_generator._3d.rotation import *
diff --git a/kornia/augmentation/random_generator/_3d/affine.py b/kornia/augmentation/random_generator/_3d/affine.py
new file mode 100644
index 000000000..3fb6c605f
--- /dev/null
+++ b/kornia/augmentation/random_generator/_3d/affine.py
@@ -0,0 +1,345 @@
+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, _adapted_uniform, _singular_range_check, _tuple_range_reader
+from kornia.utils.helpers import _deprecated, _extract_device_dtype
+
+
+class AffineGenerator3D(RandomGeneratorBase):
+ r"""Get parameters for ```3d affine``` transformation random affine transform.
+
+ Args:
+ degrees: Range of yaw (x-axis), pitch (y-axis), roll (z-axis) to select from.
+ If degrees is a number, then yaw, pitch, roll will be generated from the range of (-degrees, +degrees).
+ If degrees is a tuple of (min, max), then yaw, pitch, roll will be generated from the range of (min, max).
+ If degrees is a list of floats [a, b, c], then yaw, pitch, roll will be generated from (-a, a), (-b, b)
+ and (-c, c).
+ If degrees is a list of tuple ((a, b), (m, n), (x, y)), then yaw, pitch, roll will be generated from
+ (a, b), (m, n) and (x, y).
+ Set to 0 to deactivate rotations.
+ translate: tuple of maximum absolute fraction for horizontal, vertical and
+ depthical translations (dx,dy,dz). For example translate=(a, b, c), then
+ horizontal shift will be randomly sampled in the range -img_width * a < dx < img_width * a
+ vertical shift will be randomly sampled in the range -img_height * b < dy < img_height * b.
+ depthical shift will be randomly sampled in the range -img_depth * c < dz < img_depth * c.
+ Will not translate by default.
+ scale: scaling factor interval.
+ If (a, b) represents isotropic scaling, the scale is randomly sampled from the range a <= scale <= b.
+ If ((a, b), (c, d), (e, f)), the scale is randomly sampled from the range a <= scale_x <= b,
+ c <= scale_y <= d, e <= scale_z <= f. Will keep original scale by default.
+ shears: Range of degrees to select from.
+ If shear is a number, a shear to the 6 facets in the range (-shear, +shear) will be applied.
+ If shear is a tuple of 2 values, a shear to the 6 facets in the range (shear[0], shear[1]) will be applied.
+ If shear is a tuple of 6 values, a shear to the i-th facet in the range (-shear[i], shear[i])
+ will be applied.
+ If shear is a tuple of 6 tuples, a shear to the i-th facet in the range (-shear[i, 0], shear[i, 1])
+ will be applied.
+
+ Returns:
+ A dict of parameters to be passed for transformation.
+ - translations (torch.Tensor): element-wise translations with a shape of (B, 3).
+ - center (torch.Tensor): element-wise center with a shape of (B, 3).
+ - scale (torch.Tensor): element-wise scales with a shape of (B, 3).
+ - angle (torch.Tensor): element-wise rotation angles with a shape of (B, 3).
+ - sxy (torch.Tensor): element-wise x-y-facet shears with a shape of (B,).
+ - sxz (torch.Tensor): element-wise x-z-facet shears with a shape of (B,).
+ - syx (torch.Tensor): element-wise y-x-facet shears with a shape of (B,).
+ - syz (torch.Tensor): element-wise y-z-facet shears with a shape of (B,).
+ - szx (torch.Tensor): element-wise z-x-facet shears with a shape of (B,).
+ - szy (torch.Tensor): element-wise z-y-facet 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,
+ degrees: Union[
+ torch.Tensor,
+ float,
+ Tuple[float, float],
+ Tuple[float, float, float],
+ Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float]],
+ ],
+ translate: Optional[Union[torch.Tensor, Tuple[float, float, float]]] = None,
+ scale: Optional[
+ Union[
+ torch.Tensor, Tuple[float, float], Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float]]
+ ]
+ ] = None,
+ shears: Union[
+ torch.Tensor,
+ float,
+ Tuple[float, float],
+ Tuple[float, float, float, float, float, float],
+ Tuple[
+ Tuple[float, float],
+ Tuple[float, float],
+ Tuple[float, float],
+ Tuple[float, float],
+ Tuple[float, float],
+ Tuple[float, float],
+ ],
+ ] = None,
+ ) -> None:
+ super().__init__()
+ self.degrees = degrees
+ self.shears = shears
+ self.translate = translate
+ self.scale = scale
+
+ def __repr__(self) -> str:
+ repr = f"degrees={self.degrees}, shears={self.shears}, translate={self.translate}, scale={self.scale}"
+ return repr
+
+ def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
+ degrees = _tuple_range_reader(self.degrees, 3, device, dtype)
+ shear: Optional[torch.Tensor] = None
+ if self.shears is not None:
+ shear = _tuple_range_reader(self.shears, 6, device, dtype)
+ self.sxy_sampler = Uniform(shear[0, 0], shear[0, 1], validate_args=False)
+ self.sxz_sampler = Uniform(shear[1, 0], shear[1, 1], validate_args=False)
+ self.syx_sampler = Uniform(shear[2, 0], shear[2, 1], validate_args=False)
+ self.syz_sampler = Uniform(shear[3, 0], shear[3, 1], validate_args=False)
+ self.szx_sampler = Uniform(shear[4, 0], shear[4, 1], validate_args=False)
+ self.szy_sampler = Uniform(shear[5, 0], shear[5, 1], validate_args=False)
+
+ # check translation range
+ self._translate: Optional[torch.Tensor] = None
+ if self.translate is not None:
+ self._translate = torch.as_tensor(self.translate, device=device, dtype=dtype)
+ _singular_range_check(self._translate, 'translate', bounds=(0, 1), mode='3d')
+
+ # check scale range
+ self._scale: Optional[torch.Tensor] = None
+ if self.scale is not None:
+ _scale = torch.as_tensor(self.scale, device=device, dtype=dtype)
+ if _scale.shape == torch.Size([2]):
+ self._scale = _scale.unsqueeze(0).repeat(3, 1)
+ elif _scale.shape != torch.Size([3, 2]):
+ raise ValueError(f"'scale' shall be either shape (2) or (3, 2). Got {self.scale}.")
+ else:
+ self._scale = _scale
+ _singular_range_check(self._scale[0], 'scale-x', bounds=(0, float('inf')), mode='2d')
+ _singular_range_check(self._scale[1], 'scale-y', bounds=(0, float('inf')), mode='2d')
+ _singular_range_check(self._scale[2], 'scale-z', bounds=(0, float('inf')), mode='2d')
+ self.scale_1_sampler = Uniform(self._scale[0, 0], self._scale[0, 1], validate_args=False)
+ self.scale_2_sampler = Uniform(self._scale[1, 0], self._scale[1, 1], validate_args=False)
+ self.scale_3_sampler = Uniform(self._scale[2, 0], self._scale[2, 1], validate_args=False)
+
+ self.yaw_sampler = Uniform(degrees[0][0], degrees[0][1], validate_args=False)
+ self.pitch_sampler = Uniform(degrees[1][0], degrees[1][1], validate_args=False)
+ self.roll_sampler = Uniform(degrees[2][0], degrees[2][1], validate_args=False)
+
+ self.uniform_sampler = Uniform(
+ torch.tensor(0, device=device, dtype=dtype),
+ torch.tensor(1, device=device, dtype=dtype),
+ validate_args=False,
+ )
+
+ def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, torch.Tensor]:
+ batch_size = batch_shape[0]
+ depth = batch_shape[-3]
+ height = batch_shape[-2]
+ width = batch_shape[-1]
+
+ if not (
+ type(depth) is int and depth > 0 and type(height) is int and height > 0 and type(width) is int and width > 0
+ ):
+ raise AssertionError(f"'depth', 'height' and 'width' must be integers. Got {depth}, {height}, {width}.")
+
+ _device, _dtype = _extract_device_dtype([self.degrees, self.translate, self.scale, self.shears])
+
+ # degrees = degrees.to(device=device, dtype=dtype)
+ yaw = _adapted_rsampling((batch_size,), self.yaw_sampler, same_on_batch)
+ pitch = _adapted_rsampling((batch_size,), self.pitch_sampler, same_on_batch)
+ roll = _adapted_rsampling((batch_size,), self.roll_sampler, same_on_batch)
+ angles = torch.stack([yaw, pitch, roll], dim=1)
+
+ # compute tensor ranges
+ if self._scale is not None:
+ scale = torch.stack(
+ [
+ _adapted_rsampling((batch_size,), self.scale_1_sampler, same_on_batch),
+ _adapted_rsampling((batch_size,), self.scale_2_sampler, same_on_batch),
+ _adapted_rsampling((batch_size,), self.scale_3_sampler, same_on_batch),
+ ],
+ dim=1,
+ )
+ else:
+ scale = torch.ones(batch_size, device=_device, dtype=_dtype).reshape(batch_size, 1).repeat(1, 3)
+
+ if self._translate is not None:
+ max_dx: torch.Tensor = self._translate[0] * width
+ max_dy: torch.Tensor = self._translate[1] * height
+ max_dz: torch.Tensor = self._translate[2] * depth
+ # translations should be in x,y,z
+ translations = torch.stack(
+ [
+ (_adapted_rsampling((batch_size,), self.yaw_sampler, same_on_batch) - 0.5) * max_dx * 2,
+ (_adapted_rsampling((batch_size,), self.pitch_sampler, same_on_batch) - 0.5) * max_dy * 2,
+ (_adapted_rsampling((batch_size,), self.roll_sampler, same_on_batch) - 0.5) * max_dz * 2,
+ ],
+ dim=1,
+ )
+ else:
+ translations = torch.zeros((batch_size, 3), device=_device, dtype=_dtype)
+
+ # center should be in x,y,z
+ center: torch.Tensor = torch.tensor([width, height, depth], device=_device, dtype=_dtype).view(1, 3) / 2.0 - 0.5
+ center = center.expand(batch_size, -1)
+
+ if self.shears is not None:
+ sxy = _adapted_rsampling((batch_size,), self.sxy_sampler, same_on_batch)
+ sxz = _adapted_rsampling((batch_size,), self.sxz_sampler, same_on_batch)
+ syx = _adapted_rsampling((batch_size,), self.syx_sampler, same_on_batch)
+ syz = _adapted_rsampling((batch_size,), self.syz_sampler, same_on_batch)
+ szx = _adapted_rsampling((batch_size,), self.szx_sampler, same_on_batch)
+ szy = _adapted_rsampling((batch_size,), self.szy_sampler, same_on_batch)
+ else:
+ sxy = sxz = syx = syz = szx = szy = torch.tensor([0] * batch_size, device=_device, dtype=_dtype)
+
+ return dict(
+ translations=torch.as_tensor(translations, device=_device, dtype=_dtype),
+ center=torch.as_tensor(center, device=_device, dtype=_dtype),
+ scale=torch.as_tensor(scale, device=_device, dtype=_dtype),
+ angles=torch.as_tensor(angles, device=_device, dtype=_dtype),
+ sxy=torch.as_tensor(sxy, device=_device, dtype=_dtype),
+ sxz=torch.as_tensor(sxz, device=_device, dtype=_dtype),
+ syx=torch.as_tensor(syx, device=_device, dtype=_dtype),
+ syz=torch.as_tensor(syz, device=_device, dtype=_dtype),
+ szx=torch.as_tensor(szx, device=_device, dtype=_dtype),
+ szy=torch.as_tensor(szy, device=_device, dtype=_dtype),
+ )
+
+
+@_deprecated(replace_with=AffineGenerator3D.__name__)
+def random_affine_generator3d(
+ batch_size: int,
+ depth: int,
+ height: int,
+ width: int,
+ degrees: torch.Tensor,
+ translate: Optional[torch.Tensor] = None,
+ scale: Optional[torch.Tensor] = None,
+ shears: 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"""Get parameters for ```3d affine``` transformation random affine transform.
+
+ Args:
+ batch_size (int): the tensor batch size.
+ depth (int) : depth of the image.
+ height (int) : height of the image.
+ width (int): width of the image.
+ degrees (torch.Tensor): Ranges of degrees with shape (3, 2) for yaw, pitch and roll.
+ translate (torch.Tensor, optional): maximum absolute fraction with shape (3,) for horizontal, vertical
+ and depthical translations (dx,dy,dz). Will not translate by default.
+ scale (torch.Tensor, optional): scaling factor interval, e.g (a, b), then scale is
+ randomly sampled from the range a <= scale <= b. Will keep original scale by default.
+ shear (sequence or float, optional): Range of degrees to select from.
+ Shaped as (6, 2) for 6 facet (xy, xz, yx, yz, zx, zy).
+ The shear to the i-th facet in the range (-shear[i, 0], shear[i, 1]) will be applied.
+ same_on_batch (bool): apply the same transformation across the batch. Default: False
+
+ Returns:
+ params Dict[str, torch.Tensor]: parameters to be passed for transformation.
+ - translations (torch.Tensor): element-wise translations with a shape of (B, 3).
+ - center (torch.Tensor): element-wise center with a shape of (B, 3).
+ - scale (torch.Tensor): element-wise scales with a shape of (B, 3).
+ - angle (torch.Tensor): element-wise rotation angles with a shape of (B, 3).
+ - sxy (torch.Tensor): element-wise x-y-facet shears with a shape of (B,).
+ - sxz (torch.Tensor): element-wise x-z-facet shears with a shape of (B,).
+ - syx (torch.Tensor): element-wise y-x-facet shears with a shape of (B,).
+ - syz (torch.Tensor): element-wise y-z-facet shears with a shape of (B,).
+ - szx (torch.Tensor): element-wise z-x-facet shears with a shape of (B,).
+ - szy (torch.Tensor): element-wise z-y-facet shears with a shape of (B,).
+
+ Note:
+ The generated random numbers are not reproducible across different devices and dtypes.
+ """
+ if not (
+ type(depth) is int and depth > 0 and type(height) is int and height > 0 and type(width) is int and width > 0
+ ):
+ raise AssertionError(f"'depth', 'height' and 'width' must be integers. Got {depth}, {height}, {width}.")
+
+ _device, _dtype = _extract_device_dtype([degrees, translate, scale, shears])
+ if degrees.shape != torch.Size([3, 2]):
+ raise AssertionError(f"'degrees' must be the shape of (3, 2). Got {degrees.shape}.")
+ degrees = degrees.to(device=device, dtype=dtype)
+ yaw = _adapted_uniform((batch_size,), degrees[0][0], degrees[0][1], same_on_batch)
+ pitch = _adapted_uniform((batch_size,), degrees[1][0], degrees[1][1], same_on_batch)
+ roll = _adapted_uniform((batch_size,), degrees[2][0], degrees[2][1], same_on_batch)
+ angles = torch.stack([yaw, pitch, roll], dim=1)
+
+ # compute tensor ranges
+ if scale is not None:
+ if scale.shape != torch.Size([3, 2]):
+ raise AssertionError(f"'scale' must be the shape of (3, 2). Got {scale.shape}.")
+ scale = scale.to(device=device, dtype=dtype)
+ scale = torch.stack(
+ [
+ _adapted_uniform((batch_size,), scale[0, 0], scale[0, 1], same_on_batch),
+ _adapted_uniform((batch_size,), scale[1, 0], scale[1, 1], same_on_batch),
+ _adapted_uniform((batch_size,), scale[2, 0], scale[2, 1], same_on_batch),
+ ],
+ dim=1,
+ )
+ else:
+ scale = torch.ones(batch_size, device=device, dtype=dtype).reshape(batch_size, 1).repeat(1, 3)
+
+ if translate is not None:
+ if translate.shape != torch.Size([3]):
+ raise AssertionError(f"'translate' must be the shape of (2). Got {translate.shape}.")
+ translate = translate.to(device=device, dtype=dtype)
+ max_dx: torch.Tensor = translate[0] * width
+ max_dy: torch.Tensor = translate[1] * height
+ max_dz: torch.Tensor = translate[2] * depth
+ # translations should be in x,y,z
+ translations = torch.stack(
+ [
+ _adapted_uniform((batch_size,), -max_dx, max_dx, same_on_batch),
+ _adapted_uniform((batch_size,), -max_dy, max_dy, same_on_batch),
+ _adapted_uniform((batch_size,), -max_dz, max_dz, same_on_batch),
+ ],
+ dim=1,
+ )
+ else:
+ translations = torch.zeros((batch_size, 3), device=device, dtype=dtype)
+
+ # center should be in x,y,z
+ center: torch.Tensor = torch.tensor([width, height, depth], device=device, dtype=dtype).view(1, 3) / 2.0 - 0.5
+ center = center.expand(batch_size, -1)
+
+ if shears is not None:
+ if shears.shape != torch.Size([6, 2]):
+ raise AssertionError(f"'shears' must be the shape of (6, 2). Got {shears.shape}.")
+ shears = shears.to(device=device, dtype=dtype)
+ sxy = _adapted_uniform((batch_size,), shears[0, 0], shears[0, 1], same_on_batch)
+ sxz = _adapted_uniform((batch_size,), shears[1, 0], shears[1, 1], same_on_batch)
+ syx = _adapted_uniform((batch_size,), shears[2, 0], shears[2, 1], same_on_batch)
+ syz = _adapted_uniform((batch_size,), shears[3, 0], shears[3, 1], same_on_batch)
+ szx = _adapted_uniform((batch_size,), shears[4, 0], shears[4, 1], same_on_batch)
+ szy = _adapted_uniform((batch_size,), shears[5, 0], shears[5, 1], same_on_batch)
+ else:
+ sxy = sxz = syx = syz = szx = szy = torch.tensor([0] * batch_size, device=device, dtype=dtype)
+
+ return dict(
+ translations=translations.to(device=_device, dtype=_dtype),
+ center=center.to(device=_device, dtype=_dtype),
+ scale=scale.to(device=_device, dtype=_dtype),
+ angles=angles.to(device=_device, dtype=_dtype),
+ sxy=sxy.to(device=_device, dtype=_dtype),
+ sxz=sxz.to(device=_device, dtype=_dtype),
+ syx=syx.to(device=_device, dtype=_dtype),
+ syz=syz.to(device=_device, dtype=_dtype),
+ szx=szx.to(device=_device, dtype=_dtype),
+ szy=szy.to(device=_device, dtype=_dtype),
+ )
diff --git a/kornia/augmentation/random_generator/_3d/crop.py b/kornia/augmentation/random_generator/_3d/crop.py
new file mode 100644
index 000000000..ecef4cbb8
--- /dev/null
+++ b/kornia/augmentation/random_generator/_3d/crop.py
@@ -0,0 +1,360 @@
+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, _adapted_uniform, _common_param_check
+from kornia.geometry.bbox import bbox_generator3d
+from kornia.utils.helpers import _deprecated, _extract_device_dtype
+
+
+class CropGenerator3D(RandomGeneratorBase):
+ r"""Get parameters for ```crop``` transformation for crop transform.
+
+ Args:
+ size (tuple): Desired size of the crop operation, like (d, h, w).
+ If tensor, it must be (B, 3).
+ resize_to (tuple): Desired output size of the crop, like (d, h, w). If None, no resize will be performed.
+
+ Returns:
+ A dict of parameters to be passed for transformation.
+ - src (torch.Tensor): cropping bounding boxes with a shape of (B, 8, 3).
+ - dst (torch.Tensor): output bounding boxes with a shape (B, 8, 3).
+
+ 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, size: Union[Tuple[int, int, int], torch.Tensor], resize_to: Optional[Tuple[int, int, int]] = None
+ ) -> None:
+ super().__init__()
+ self.size = size
+ self.resize_to = resize_to
+
+ def __repr__(self) -> str:
+ repr = f"crop_size={self.size}"
+ if self.resize_to is not None:
+ repr += f", resize_to={self.resize_to}"
+ return repr
+
+ def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
+ self.rand_sampler = Uniform(
+ torch.tensor(0.0, device=device, dtype=dtype), torch.tensor(1.0, device=device, dtype=dtype)
+ )
+
+ def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, torch.Tensor]: # type:ignore
+ batch_size, _, depth, height, width = batch_shape
+ _common_param_check(batch_size, same_on_batch)
+ _device, _dtype = _extract_device_dtype([self.size if isinstance(self.size, torch.Tensor) else None])
+
+ if not isinstance(self.size, torch.Tensor):
+ size = torch.tensor(self.size, device=_device, dtype=_dtype).repeat(batch_size, 1)
+ else:
+ size = self.size.to(device=_device, dtype=_dtype)
+ if size.shape != torch.Size([batch_size, 3]):
+ raise AssertionError(
+ "If `size` is a tensor, it must be shaped as (B, 3). "
+ f"Got {size.shape} while expecting {torch.Size([batch_size, 3])}."
+ )
+ if not (
+ isinstance(depth, (int,))
+ and isinstance(height, (int,))
+ and isinstance(width, (int,))
+ and depth > 0
+ and height > 0
+ and width > 0
+ ):
+ raise AssertionError(f"`batch_shape` should not contain negative values. Got {(batch_shape)}.")
+
+ x_diff = width - size[:, 2] + 1
+ y_diff = height - size[:, 1] + 1
+ z_diff = depth - size[:, 0] + 1
+
+ if (x_diff < 0).any() or (y_diff < 0).any() or (z_diff < 0).any():
+ raise ValueError(
+ f"input_size {(depth, height, width)} cannot be smaller than crop size {str(size)} in any dimension."
+ )
+
+ if batch_size == 0:
+ return dict(
+ src=torch.zeros([0, 8, 3], device=_device, dtype=_dtype),
+ dst=torch.zeros([0, 8, 3], device=_device, dtype=_dtype),
+ )
+
+ x_start = _adapted_rsampling((batch_size,), self.rand_sampler, same_on_batch).to(device=_device, dtype=_dtype)
+ y_start = _adapted_rsampling((batch_size,), self.rand_sampler, same_on_batch).to(device=_device, dtype=_dtype)
+ z_start = _adapted_rsampling((batch_size,), self.rand_sampler, same_on_batch).to(device=_device, dtype=_dtype)
+
+ x_start = (x_start * x_diff).floor()
+ y_start = (y_start * y_diff).floor()
+ z_start = (z_start * z_diff).floor()
+
+ crop_src = bbox_generator3d(
+ x_start.view(-1), y_start.view(-1), z_start.view(-1), size[:, 2] - 1, size[:, 1] - 1, size[:, 0] - 1
+ )
+
+ if self.resize_to is None:
+ crop_dst = bbox_generator3d(
+ torch.tensor([0] * batch_size, device=_device, dtype=_dtype),
+ torch.tensor([0] * batch_size, device=_device, dtype=_dtype),
+ torch.tensor([0] * batch_size, device=_device, dtype=_dtype),
+ size[:, 2] - 1,
+ size[:, 1] - 1,
+ size[:, 0] - 1,
+ )
+ else:
+ if not (
+ len(self.resize_to) == 3
+ and isinstance(self.resize_to[0], (int,))
+ and isinstance(self.resize_to[1], (int,))
+ and isinstance(self.resize_to[2], (int,))
+ and self.resize_to[0] > 0
+ and self.resize_to[1] > 0
+ and self.resize_to[2] > 0
+ ):
+ raise AssertionError(f"`resize_to` must be a tuple of 3 positive integers. Got {self.resize_to}.")
+ crop_dst = torch.tensor(
+ [
+ [
+ [0, 0, 0],
+ [self.resize_to[-1] - 1, 0, 0],
+ [self.resize_to[-1] - 1, self.resize_to[-2] - 1, 0],
+ [0, self.resize_to[-2] - 1, 0],
+ [0, 0, self.resize_to[-3] - 1],
+ [self.resize_to[-1] - 1, 0, self.resize_to[-3] - 1],
+ [self.resize_to[-1] - 1, self.resize_to[-2] - 1, self.resize_to[-3] - 1],
+ [0, self.resize_to[-2] - 1, self.resize_to[-3] - 1],
+ ]
+ ],
+ device=_device,
+ dtype=_dtype,
+ ).repeat(batch_size, 1, 1)
+
+ return dict(src=crop_src.to(device=_device), dst=crop_dst.to(device=_device))
+
+
+def center_crop_generator3d(
+ batch_size: int,
+ depth: int,
+ height: int,
+ width: int,
+ size: Tuple[int, int, int],
+ device: torch.device = torch.device('cpu'),
+) -> Dict[str, torch.Tensor]:
+ r"""Get parameters for ```center_crop3d``` transformation for center crop transform.
+
+ Args:
+ batch_size (int): the tensor batch size.
+ depth (int) : depth of the image.
+ height (int) : height of the image.
+ width (int): width of the image.
+ size (tuple): Desired output size of the crop, like (d, h, w).
+ device (torch.device): the device on which the random numbers will be generated. Default: cpu.
+
+ Returns:
+ params Dict[str, torch.Tensor]: parameters to be passed for transformation.
+ - src (torch.Tensor): cropping bounding boxes with a shape of (B, 8, 3).
+ - dst (torch.Tensor): output bounding boxes with a shape (B, 8, 3).
+
+ Note:
+ No random number will be generated.
+ """
+ if not isinstance(size, (tuple, list)) and len(size) == 3:
+ raise ValueError(f"Input size must be a tuple/list of length 3. Got {size}")
+ if not (
+ type(depth) is int and depth > 0 and type(height) is int and height > 0 and type(width) is int and width > 0
+ ):
+ raise AssertionError(f"'depth', 'height' and 'width' must be integers. Got {depth}, {height}, {width}.")
+ if not (depth >= size[0] and height >= size[1] and width >= size[2]):
+ raise AssertionError(f"Crop size must be smaller than input size. Got ({depth}, {height}, {width}) and {size}.")
+
+ if batch_size == 0:
+ return dict(src=torch.zeros([0, 8, 3]), dst=torch.zeros([0, 8, 3]))
+ # unpack input sizes
+ dst_d, dst_h, dst_w = size
+ src_d, src_h, src_w = (depth, height, width)
+
+ # compute start/end offsets
+ dst_d_half = dst_d / 2
+ dst_h_half = dst_h / 2
+ dst_w_half = dst_w / 2
+ src_d_half = src_d / 2
+ src_h_half = src_h / 2
+ src_w_half = src_w / 2
+
+ start_x = src_w_half - dst_w_half
+ start_y = src_h_half - dst_h_half
+ start_z = src_d_half - dst_d_half
+
+ end_x = start_x + dst_w - 1
+ end_y = start_y + dst_h - 1
+ end_z = start_z + dst_d - 1
+ # [x, y, z] origin
+ # top-left-front, top-right-front, bottom-right-front, bottom-left-front
+ # top-left-back, top-right-back, bottom-right-back, bottom-left-back
+ # Note: DeprecationWarning: an integer is required (got type float).
+ # Implicit conversion to integers using __int__ is deprecated, and may be removed in a future version of Python.
+ points_src: torch.Tensor = torch.tensor(
+ [
+ [
+ [int(start_x), int(start_y), int(start_z)],
+ [int(end_x), int(start_y), int(start_z)],
+ [int(end_x), int(end_y), int(start_z)],
+ [int(start_x), int(end_y), int(start_z)],
+ [int(start_x), int(start_y), int(end_z)],
+ [int(end_x), int(start_y), int(end_z)],
+ [int(end_x), int(end_y), int(end_z)],
+ [int(start_x), int(end_y), int(end_z)],
+ ]
+ ],
+ device=device,
+ dtype=torch.long,
+ ).expand(batch_size, -1, -1)
+
+ # [x, y, z] destination
+ # top-left-front, top-right-front, bottom-right-front, bottom-left-front
+ # top-left-back, top-right-back, bottom-right-back, bottom-left-back
+ points_dst: torch.Tensor = torch.tensor(
+ [
+ [
+ [0, 0, 0],
+ [dst_w - 1, 0, 0],
+ [dst_w - 1, dst_h - 1, 0],
+ [0, dst_h - 1, 0],
+ [0, 0, dst_d - 1],
+ [dst_w - 1, 0, dst_d - 1],
+ [dst_w - 1, dst_h - 1, dst_d - 1],
+ [0, dst_h - 1, dst_d - 1],
+ ]
+ ],
+ device=device,
+ dtype=torch.long,
+ ).expand(batch_size, -1, -1)
+ return dict(src=points_src, dst=points_dst)
+
+
+@_deprecated(replace_with=CropGenerator3D.__name__)
+def random_crop_generator3d(
+ batch_size: int,
+ input_size: Tuple[int, int, int],
+ size: Union[Tuple[int, int, int], torch.Tensor],
+ resize_to: Optional[Tuple[int, int, int]] = None,
+ same_on_batch: bool = False,
+ device: torch.device = torch.device('cpu'),
+ dtype: torch.dtype = torch.float32,
+) -> Dict[str, torch.Tensor]:
+ r"""Get parameters for ```crop``` transformation for crop transform.
+
+ Args:
+ batch_size (int): the tensor batch size.
+ input_size (tuple): Input image shape, like (d, h, w).
+ size (tuple): Desired size of the crop operation, like (d, h, w).
+ If tensor, it must be (B, 3).
+ resize_to (tuple): Desired output size of the crop, like (d, h, w). If None, no resize will be performed.
+ 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.
+ - src (torch.Tensor): cropping bounding boxes with a shape of (B, 8, 3).
+ - dst (torch.Tensor): output bounding boxes with a shape (B, 8, 3).
+
+ Note:
+ The generated random numbers are not reproducible across different devices and dtypes.
+ """
+ _device, _dtype = _extract_device_dtype([size if isinstance(size, torch.Tensor) else None])
+ if not isinstance(size, torch.Tensor):
+ size = torch.tensor(size, device=device, dtype=dtype).repeat(batch_size, 1)
+ else:
+ size = size.to(device=device, dtype=dtype)
+ if size.shape != torch.Size([batch_size, 3]):
+ raise AssertionError(
+ "If `size` is a tensor, it must be shaped as (B, 3). "
+ f"Got {size.shape} while expecting {torch.Size([batch_size, 3])}."
+ )
+ if not (
+ len(input_size) == 3
+ and isinstance(input_size[0], (int,))
+ and isinstance(input_size[1], (int,))
+ and isinstance(input_size[2], (int,))
+ and input_size[0] > 0
+ and input_size[1] > 0
+ and input_size[2] > 0
+ ):
+ raise AssertionError(f"`input_size` must be a tuple of 3 positive integers. Got {input_size}.")
+
+ x_diff = input_size[2] - size[:, 2] + 1
+ y_diff = input_size[1] - size[:, 1] + 1
+ z_diff = input_size[0] - size[:, 0] + 1
+
+ if (x_diff < 0).any() or (y_diff < 0).any() or (z_diff < 0).any():
+ raise ValueError(f"input_size {str(input_size)} cannot be smaller than crop size {str(size)} in any dimension.")
+
+ if batch_size == 0:
+ return dict(
+ src=torch.zeros([0, 8, 3], device=_device, dtype=_dtype),
+ dst=torch.zeros([0, 8, 3], device=_device, dtype=_dtype),
+ )
+
+ if same_on_batch:
+ # If same_on_batch, select the first then repeat.
+ x_start = _adapted_uniform((batch_size,), 0, x_diff[0], same_on_batch).floor()
+ y_start = _adapted_uniform((batch_size,), 0, y_diff[0], same_on_batch).floor()
+ z_start = _adapted_uniform((batch_size,), 0, z_diff[0], same_on_batch).floor()
+ else:
+ x_start = _adapted_uniform((1,), 0, x_diff, same_on_batch).floor()
+ y_start = _adapted_uniform((1,), 0, y_diff, same_on_batch).floor()
+ z_start = _adapted_uniform((1,), 0, z_diff, same_on_batch).floor()
+
+ crop_src = bbox_generator3d(
+ x_start.to(device=_device, dtype=_dtype).view(-1),
+ y_start.to(device=_device, dtype=_dtype).view(-1),
+ z_start.to(device=_device, dtype=_dtype).view(-1),
+ size[:, 2].to(device=_device, dtype=_dtype) - 1,
+ size[:, 1].to(device=_device, dtype=_dtype) - 1,
+ size[:, 0].to(device=_device, dtype=_dtype) - 1,
+ )
+
+ if resize_to is None:
+ crop_dst = bbox_generator3d(
+ torch.tensor([0] * batch_size, device=_device, dtype=_dtype),
+ torch.tensor([0] * batch_size, device=_device, dtype=_dtype),
+ torch.tensor([0] * batch_size, device=_device, dtype=_dtype),
+ size[:, 2].to(device=_device, dtype=_dtype) - 1,
+ size[:, 1].to(device=_device, dtype=_dtype) - 1,
+ size[:, 0].to(device=_device, dtype=_dtype) - 1,
+ )
+ else:
+ if not (
+ len(resize_to) == 3
+ and isinstance(resize_to[0], (int,))
+ and isinstance(resize_to[1], (int,))
+ and isinstance(resize_to[2], (int,))
+ and resize_to[0] > 0
+ and resize_to[1] > 0
+ and resize_to[2] > 0
+ ):
+ raise AssertionError(f"`resize_to` must be a tuple of 3 positive integers. Got {resize_to}.")
+ crop_dst = torch.tensor(
+ [
+ [
+ [0, 0, 0],
+ [resize_to[-1] - 1, 0, 0],
+ [resize_to[-1] - 1, resize_to[-2] - 1, 0],
+ [0, resize_to[-2] - 1, 0],
+ [0, 0, resize_to[-3] - 1],
+ [resize_to[-1] - 1, 0, resize_to[-3] - 1],
+ [resize_to[-1] - 1, resize_to[-2] - 1, resize_to[-3] - 1],
+ [0, resize_to[-2] - 1, resize_to[-3] - 1],
+ ]
+ ],
+ device=_device,
+ dtype=_dtype,
+ ).repeat(batch_size, 1, 1)
+
+ return dict(src=crop_src.to(device=_device), dst=crop_dst.to(device=_device))
diff --git a/kornia/augmentation/random_generator/_3d/motion_blur.py b/kornia/augmentation/random_generator/_3d/motion_blur.py
new file mode 100644
index 000000000..13a5ad49f
--- /dev/null
+++ b/kornia/augmentation/random_generator/_3d/motion_blur.py
@@ -0,0 +1,170 @@
+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,
+ _adapted_uniform,
+ _common_param_check,
+ _joint_range_check,
+ _range_bound,
+ _tuple_range_reader,
+)
+from kornia.utils.helpers import _deprecated, _extract_device_dtype
+
+
+class MotionBlurGenerator3D(RandomGeneratorBase):
+ r"""Get parameters for motion blur.
+
+ Args:
+ kernel_size: motion kernel size (odd and positive).
+ If int, the kernel will have a fixed size.
+ If Tuple[int, int], it will randomly generate the value from the range batch-wisely.
+ angle: angle of the motion blur in degrees (anti-clockwise rotation).
+ If float, it will generate the value from (-angle, angle).
+ direction: forward/backward direction of the motion blur.
+ Lower values towards -1.0 will point the motion blur towards the back (with angle provided via angle),
+ while higher values towards 1.0 will point the motion blur forward. A value of 0.0 leads to a
+ uniformly (but still angled) motion blur.
+ If float, it will generate the value from (-direction, direction).
+ If Tuple[int, int], it will randomly generate the value from the range.
+
+ Returns:
+ A dict of parameters to be passed for transformation.
+ - ksize_factor (torch.Tensor): element-wise kernel size factors with a shape of (B,).
+ - angle_factor (torch.Tensor): element-wise angle factors with a shape of (B,).
+ - direction_factor (torch.Tensor): element-wise direction factors 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,
+ kernel_size: Union[int, Tuple[int, int]],
+ angle: Union[
+ torch.Tensor,
+ float,
+ Tuple[float, float, float],
+ Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float]],
+ ],
+ direction: Union[torch.Tensor, float, Tuple[float, float]],
+ ) -> None:
+ super().__init__()
+ self.kernel_size = kernel_size
+ self.angle = angle
+ self.direction = direction
+
+ def __repr__(self) -> str:
+ repr = f"kernel_size={self.kernel_size}, angle={self.angle}, direction={self.direction}"
+ return repr
+
+ def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
+ angle: torch.Tensor = _tuple_range_reader(self.angle, 3, device=device, dtype=dtype)
+ direction = _range_bound(self.direction, 'direction', center=0.0, bounds=(-1, 1)).to(device=device, dtype=dtype)
+ if isinstance(self.kernel_size, int):
+ if not (self.kernel_size >= 3 and self.kernel_size % 2 == 1):
+ raise AssertionError(f"`kernel_size` must be odd and greater than 3. Got {self.kernel_size}.")
+ self.ksize_sampler = Uniform(self.kernel_size // 2, self.kernel_size // 2, validate_args=False)
+ elif isinstance(self.kernel_size, tuple):
+ # kernel_size is fixed across the batch
+ if len(self.kernel_size) != 2:
+ raise AssertionError(f"`kernel_size` must be (2,) if it is a tuple. Got {self.kernel_size}.")
+ self.ksize_sampler = Uniform(self.kernel_size[0] // 2, self.kernel_size[1] // 2, validate_args=False)
+ else:
+ raise TypeError(f"Unsupported type: {type(self.kernel_size)}")
+
+ self.yaw_sampler = Uniform(angle[0][0], angle[0][1], validate_args=False)
+ self.pitch_sampler = Uniform(angle[1][0], angle[1][1], validate_args=False)
+ self.roll_sampler = Uniform(angle[2][0], angle[2][1], validate_args=False)
+ self.direction_sampler = Uniform(direction[0], direction[1], validate_args=False)
+
+ def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, torch.Tensor]: # type:ignore
+ batch_size = batch_shape[0]
+ _common_param_check(batch_size, same_on_batch)
+ # self.ksize_factor.expand((batch_size, -1))
+ _device, _dtype = _extract_device_dtype([self.angle, self.direction])
+ yaw_factor = _adapted_rsampling((batch_size,), self.yaw_sampler, same_on_batch)
+ pitch_factor = _adapted_rsampling((batch_size,), self.pitch_sampler, same_on_batch)
+ roll_factor = _adapted_rsampling((batch_size,), self.roll_sampler, same_on_batch)
+ angle_factor = torch.stack([yaw_factor, pitch_factor, roll_factor], dim=1)
+
+ direction_factor = _adapted_rsampling((batch_size,), self.direction_sampler, same_on_batch)
+ ksize_factor = _adapted_rsampling((batch_size,), self.ksize_sampler, same_on_batch).int() * 2 + 1
+
+ return dict(
+ ksize_factor=ksize_factor.to(device=_device, dtype=torch.int32),
+ angle_factor=angle_factor.to(device=_device, dtype=_dtype),
+ direction_factor=direction_factor.to(device=_device, dtype=_dtype),
+ )
+
+
+@_deprecated(replace_with=MotionBlurGenerator3D.__name__)
+def random_motion_blur_generator3d(
+ batch_size: int,
+ kernel_size: Union[int, Tuple[int, int]],
+ angle: torch.Tensor,
+ direction: torch.Tensor,
+ same_on_batch: bool = False,
+ device: torch.device = torch.device('cpu'),
+ dtype: torch.dtype = torch.float32,
+) -> Dict[str, torch.Tensor]:
+ r"""Get parameters for motion blur.
+
+ Args:
+ batch_size (int): the tensor batch size.
+ kernel_size (int or (int, int)): motion kernel size (odd and positive) or range.
+ angle (torch.Tensor): yaw, pitch and roll range of the motion blur in degrees :math:`(3, 2)`.
+ direction (torch.Tensor): forward/backward direction of the motion blur.
+ Lower values towards -1.0 will point the motion blur towards the back (with
+ angle provided via angle), while higher values towards 1.0 will point the motion
+ blur forward. A value of 0.0 leads to a uniformly (but still angled) motion blur.
+ 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.
+ - ksize_factor (torch.Tensor): element-wise kernel size factors with a shape of (B,).
+ - angle_factor (torch.Tensor): element-wise center with a shape of (B,).
+ - direction_factor (torch.Tensor): element-wise scales with a shape of (B,).
+
+ Note:
+ The generated random numbers are not reproducible across different devices and dtypes.
+ """
+ _device, _dtype = _extract_device_dtype([angle, direction])
+ _joint_range_check(direction, 'direction', (-1, 1))
+ if isinstance(kernel_size, int):
+ if not (kernel_size >= 3 and kernel_size % 2 == 1):
+ raise AssertionError(f"`kernel_size` must be odd and greater than 3. Got {kernel_size}.")
+ ksize_factor = torch.tensor([kernel_size] * batch_size, device=device, dtype=dtype).int()
+ elif isinstance(kernel_size, tuple):
+ if not (len(kernel_size) == 2 and kernel_size[0] >= 3 and kernel_size[0] <= kernel_size[1]):
+ raise AssertionError(f"`kernel_size` must be greater than 3. Got range {kernel_size}.")
+ # kernel_size is fixed across the batch
+ ksize_factor = (
+ _adapted_uniform((batch_size,), kernel_size[0] // 2, kernel_size[1] // 2, same_on_batch=True).int() * 2 + 1
+ )
+ else:
+ raise TypeError(f"Unsupported type: {type(kernel_size)}")
+
+ if angle.shape != torch.Size([3, 2]):
+ raise AssertionError(f"'angle' must be the shape of (3, 2). Got {angle.shape}.")
+ angle = angle.to(device=device, dtype=dtype)
+ yaw = _adapted_uniform((batch_size,), angle[0][0], angle[0][1], same_on_batch)
+ pitch = _adapted_uniform((batch_size,), angle[1][0], angle[1][1], same_on_batch)
+ roll = _adapted_uniform((batch_size,), angle[2][0], angle[2][1], same_on_batch)
+ angle_factor = torch.stack([yaw, pitch, roll], dim=1)
+
+ direction = direction.to(device=device, dtype=dtype)
+ direction_factor = _adapted_uniform((batch_size,), direction[0], direction[1], same_on_batch)
+
+ return dict(
+ ksize_factor=ksize_factor.to(device=_device),
+ angle_factor=angle_factor.to(device=_device, dtype=_dtype),
+ direction_factor=direction_factor.to(device=_device, dtype=_dtype),
+ )
diff --git a/kornia/augmentation/random_generator/_3d/perspective.py b/kornia/augmentation/random_generator/_3d/perspective.py
new file mode 100644
index 000000000..68182f109
--- /dev/null
+++ b/kornia/augmentation/random_generator/_3d/perspective.py
@@ -0,0 +1,170 @@
+from typing import Dict, Union
+
+import torch
+from torch.distributions import Uniform
+
+from kornia.augmentation.random_generator.base import RandomGeneratorBase
+from kornia.augmentation.utils import _adapted_rsampling, _adapted_uniform, _common_param_check
+from kornia.utils.helpers import _deprecated, _extract_device_dtype
+
+
+class PerspectiveGenerator3D(RandomGeneratorBase):
+ r"""Get parameters for ``perspective`` for a random perspective transform.
+
+ Args:
+ distortion_scale: controls the degree of distortion and ranges from 0 to 1.
+
+ Returns:
+ A dict of parameters to be passed for transformation.
+ - src (torch.Tensor): perspective source bounding boxes with a shape of (B, 8, 3).
+ - dst (torch.Tensor): perspective target bounding boxes with a shape (B, 8, 3).
+
+ 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, distortion_scale: Union[torch.Tensor, float] = 0.5) -> None:
+ super().__init__()
+ self.distortion_scale = distortion_scale
+
+ def __repr__(self) -> str:
+ repr = f"distortion_scale={self.distortion_scale}"
+ return repr
+
+ def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
+ self._distortion_scale = torch.as_tensor(self.distortion_scale, device=device, dtype=dtype)
+ if not (self._distortion_scale.dim() == 0 and 0 <= self._distortion_scale <= 1):
+ raise AssertionError(f"'distortion_scale' must be a scalar within [0, 1]. Got {self._distortion_scale}")
+ self.rand_sampler = Uniform(
+ torch.tensor(0, device=device, dtype=dtype),
+ torch.tensor(1, device=device, dtype=dtype),
+ validate_args=False,
+ )
+
+ def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, torch.Tensor]: # type:ignore
+ batch_size = batch_shape[0]
+ depth = batch_shape[-3]
+ height = batch_shape[-2]
+ width = batch_shape[-1]
+
+ _common_param_check(batch_size, same_on_batch)
+ _device, _dtype = _extract_device_dtype([self.distortion_scale])
+
+ start_points: torch.Tensor = torch.tensor(
+ [
+ [
+ [0.0, 0, 0],
+ [width - 1, 0, 0],
+ [width - 1, height - 1, 0],
+ [0, height - 1, 0],
+ [0.0, 0, depth - 1],
+ [width - 1, 0, depth - 1],
+ [width - 1, height - 1, depth - 1],
+ [0, height - 1, depth - 1],
+ ]
+ ],
+ device=_device,
+ dtype=_dtype,
+ ).expand(batch_size, -1, -1)
+
+ # generate random offset not larger than half of the image
+ fx = self._distortion_scale * width / 2
+ fy = self._distortion_scale * height / 2
+ fz = self._distortion_scale * depth / 2
+
+ factor = torch.stack([fx, fy, fz], dim=0).view(-1, 1, 3).to(device=_device, dtype=_dtype)
+
+ rand_val: torch.Tensor = _adapted_rsampling(start_points.shape, self.rand_sampler, same_on_batch).to(
+ device=_device, dtype=_dtype
+ )
+
+ pts_norm = torch.tensor(
+ [[[1, 1, 1], [-1, 1, 1], [-1, -1, 1], [1, -1, 1], [1, 1, -1], [-1, 1, -1], [-1, -1, -1], [1, -1, -1]]],
+ device=_device,
+ dtype=_dtype,
+ )
+ end_points = start_points + factor * rand_val * pts_norm
+
+ return dict(start_points=start_points, end_points=end_points)
+
+
+@_deprecated(replace_with=PerspectiveGenerator3D.__name__)
+def random_perspective_generator3d(
+ batch_size: int,
+ depth: int,
+ height: int,
+ width: int,
+ distortion_scale: torch.Tensor,
+ same_on_batch: bool = False,
+ device: torch.device = torch.device('cpu'),
+ dtype: torch.dtype = torch.float32,
+) -> Dict[str, torch.Tensor]:
+ r"""Get parameters for ``perspective`` for a random perspective transform.
+
+ Args:
+ batch_size (int): the tensor batch size.
+ depth (int) : depth of the image.
+ height (int) : height of the image.
+ width (int): width of the image.
+ distortion_scale (torch.Tensor): it controls the degree of distortion and ranges from 0 to 1.
+ 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.
+ - src (torch.Tensor): perspective source bounding boxes with a shape of (B, 8, 3).
+ - dst (torch.Tensor): perspective target bounding boxes with a shape (B, 8, 3).
+
+ Note:
+ The generated random numbers are not reproducible across different devices and dtypes.
+ """
+ if not (distortion_scale.dim() == 0 and 0 <= distortion_scale <= 1):
+ raise AssertionError(f"'distortion_scale' must be a scalar within [0, 1]. Got {distortion_scale}")
+ _device, _dtype = _extract_device_dtype([distortion_scale])
+ distortion_scale = distortion_scale.to(device=device, dtype=dtype)
+
+ start_points: torch.Tensor = torch.tensor(
+ [
+ [
+ [0.0, 0, 0],
+ [width - 1, 0, 0],
+ [width - 1, height - 1, 0],
+ [0, height - 1, 0],
+ [0.0, 0, depth - 1],
+ [width - 1, 0, depth - 1],
+ [width - 1, height - 1, depth - 1],
+ [0, height - 1, depth - 1],
+ ]
+ ],
+ device=device,
+ dtype=dtype,
+ ).expand(batch_size, -1, -1)
+
+ # generate random offset not larger than half of the image
+ fx = distortion_scale * width / 2
+ fy = distortion_scale * height / 2
+ fz = distortion_scale * depth / 2
+
+ factor = torch.stack([fx, fy, fz], dim=0).view(-1, 1, 3)
+
+ rand_val: torch.Tensor = _adapted_uniform(
+ start_points.shape,
+ torch.tensor(0, device=device, dtype=dtype),
+ torch.tensor(1, device=device, dtype=dtype),
+ same_on_batch,
+ )
+
+ pts_norm = torch.tensor(
+ [[[1, 1, 1], [-1, 1, 1], [-1, -1, 1], [1, -1, 1], [1, 1, -1], [-1, 1, -1], [-1, -1, -1], [1, -1, -1]]],
+ device=device,
+ dtype=dtype,
+ )
+ end_points = start_points + factor * rand_val * pts_norm
+
+ return dict(
+ start_points=start_points.to(device=_device, dtype=_dtype),
+ end_points=end_points.to(device=_device, dtype=_dtype),
+ )
diff --git a/kornia/augmentation/random_generator/_3d/rotation.py b/kornia/augmentation/random_generator/_3d/rotation.py
new file mode 100644
index 000000000..327e32c0c
--- /dev/null
+++ b/kornia/augmentation/random_generator/_3d/rotation.py
@@ -0,0 +1,105 @@
+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, _adapted_uniform, _common_param_check, _tuple_range_reader
+from kornia.utils.helpers import _deprecated, _extract_device_dtype
+
+
+class RotationGenerator3D(RandomGeneratorBase):
+ r"""Get parameters for ``rotate`` for a random 3D rotate transform.
+
+ Args:
+ degrees: Range of yaw (x-axis), pitch (y-axis), roll (z-axis) to select from.
+ If degrees is a number, then yaw, pitch, roll will be generated from the range of (-degrees, +degrees).
+ If degrees is a tuple of (min, max), then yaw, pitch, roll will be generated from the range of (min, max).
+ If degrees is a list of floats [a, b, c], then yaw, pitch, roll will be generated from (-a, a), (-b, b)
+ and (-c, c).
+ If degrees is a list of tuple ((a, b), (m, n), (x, y)), then yaw, pitch, roll will be generated from
+ (a, b), (m, n) and (x, y).
+ Set to 0 to deactivate rotations.
+
+ Returns:
+ A dict of parameters to be passed for transformation.
+ - yaw (torch.Tensor): element-wise rotation yaws with a shape of (B,).
+ - pitch (torch.Tensor): element-wise rotation pitches with a shape of (B,).
+ - roll (torch.Tensor): element-wise rotation rolls 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,
+ degrees: Union[
+ torch.Tensor,
+ float,
+ Tuple[float, float, float],
+ Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float]],
+ ],
+ ) -> None:
+ super().__init__()
+ self.degrees = degrees
+
+ def __repr__(self) -> str:
+ repr = f"degrees={self.degrees}"
+ return repr
+
+ def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
+ degrees = _tuple_range_reader(self.degrees, 3, device, dtype)
+ self.yaw_sampler = Uniform(degrees[0][0], degrees[0][1], validate_args=False)
+ self.pitch_sampler = Uniform(degrees[1][0], degrees[1][1], validate_args=False)
+ self.roll_sampler = Uniform(degrees[2][0], degrees[2][1], validate_args=False)
+
+ def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, torch.Tensor]: # type:ignore
+ batch_size = batch_shape[0]
+ _common_param_check(batch_size, same_on_batch)
+ _device, _dtype = _extract_device_dtype([self.degrees])
+
+ return dict(
+ yaw=_adapted_rsampling((batch_size,), self.yaw_sampler, same_on_batch).to(device=_device, dtype=_dtype),
+ pitch=_adapted_rsampling((batch_size,), self.pitch_sampler, same_on_batch).to(device=_device, dtype=_dtype),
+ roll=_adapted_rsampling((batch_size,), self.roll_sampler, same_on_batch).to(device=_device, dtype=_dtype),
+ )
+
+
+@_deprecated(replace_with=RotationGenerator3D.__name__)
+def random_rotation_generator3d(
+ batch_size: int,
+ degrees: torch.Tensor,
+ same_on_batch: bool = False,
+ device: torch.device = torch.device('cpu'),
+ dtype: torch.dtype = torch.float32,
+) -> Dict[str, torch.Tensor]:
+ r"""Get parameters for ``rotate`` for a random rotate transform.
+
+ Args:
+ batch_size (int): the tensor batch size.
+ degrees (torch.Tensor): Ranges of degrees (3, 2) for yaw, pitch and roll.
+ 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.
+ - yaw (torch.Tensor): element-wise rotation yaws with a shape of (B,).
+ - pitch (torch.Tensor): element-wise rotation pitches with a shape of (B,).
+ - roll (torch.Tensor): element-wise rotation rolls with a shape of (B,).
+ """
+ if degrees.shape != torch.Size([3, 2]):
+ raise AssertionError(f"'degrees' must be the shape of (3, 2). Got {degrees.shape}.")
+ _device, _dtype = _extract_device_dtype([degrees])
+ degrees = degrees.to(device=device, dtype=dtype)
+ yaw = _adapted_uniform((batch_size,), degrees[0][0], degrees[0][1], same_on_batch)
+ pitch = _adapted_uniform((batch_size,), degrees[1][0], degrees[1][1], same_on_batch)
+ roll = _adapted_uniform((batch_size,), degrees[2][0], degrees[2][1], same_on_batch)
+
+ return dict(
+ yaw=yaw.to(device=_device, dtype=_dtype),
+ pitch=pitch.to(device=_device, dtype=_dtype),
+ roll=roll.to(device=_device, dtype=_dtype),
+ )
diff --git a/kornia/augmentation/random_generator/__init__.py b/kornia/augmentation/random_generator/__init__.py
index 4e53c2f92..88f47289f 100644
--- a/kornia/augmentation/random_generator/__init__.py
+++ b/kornia/augmentation/random_generator/__init__.py
@@ -1,2 +1,2 @@
-from .random_generator import *
-from .random_generator3d import *
+from kornia.augmentation.random_generator._2d import *
+from kornia.augmentation.random_generator._3d import *
diff --git a/kornia/augmentation/random_generator/base.py b/kornia/augmentation/random_generator/base.py
new file mode 100644
index 000000000..9ed492b24
--- /dev/null
+++ b/kornia/augmentation/random_generator/base.py
@@ -0,0 +1,39 @@
+from typing import Dict
+
+import torch
+import torch.nn as nn
+
+
+class _PostInitInjectionMetaClass(type):
+ """To inject the ``__post_init__`` function after the creation of each instance."""
+
+ def __call__(cls, *args, **kwargs):
+ obj = type.__call__(cls, *args, **kwargs)
+ obj.__post_init__()
+ return obj
+
+
+class RandomGeneratorBase(nn.Module, metaclass=_PostInitInjectionMetaClass):
+ """Base class for generating random augmentation parameters."""
+
+ def __init__(self) -> None:
+ super().__init__()
+
+ def __post_init__(self) -> None:
+ self.set_rng_device_and_dtype()
+
+ def set_rng_device_and_dtype(
+ self, device: torch.device = torch.device('cpu'), dtype: torch.dtype = torch.float32
+ ) -> None:
+ """Change the random generation device and dtype.
+
+ Note:
+ The generated random numbers are not reproducible across different devices and dtypes.
+ """
+ self.make_samplers(device, dtype)
+
+ def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
+ raise NotImplementedError
+
+ def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, torch.Tensor]: # type:ignore
+ raise NotImplementedError
diff --git a/kornia/augmentation/random_generator/random_generator.py b/kornia/augmentation/random_generator/random_generator.py
deleted file mode 100644
index e84620fd4..000000000
--- a/kornia/augmentation/random_generator/random_generator.py
+++ /dev/null
@@ -1,2205 +0,0 @@
-from functools import partial
-from typing import Any, cast, Dict, List, Optional, Tuple, Union
-
-import torch
-import torch.nn as nn
-from torch.distributions import Bernoulli, Beta, Distribution, Uniform
-
-from kornia.geometry.bbox import bbox_generator
-from kornia.utils.helpers import _deprecated, _extract_device_dtype
-
-from ..utils import (
- _adapted_beta,
- _adapted_rsampling,
- _adapted_sampling,
- _adapted_uniform,
- _common_param_check,
- _joint_range_check,
- _range_bound,
-)
-
-# factor, name, center, range
-ParameterBound = Tuple[Any, str, Optional[float], Optional[Tuple[float, float]]]
-
-
-class _PostInitInjectionMetaClass(type):
- """To inject the ``__post_init__`` function after the creation of each instance."""
- def __call__(cls, *args, **kwargs):
- obj = type.__call__(cls, *args, **kwargs)
- obj.__post_init__()
- return obj
-
-
-class RandomGeneratorBase(nn.Module, metaclass=_PostInitInjectionMetaClass):
- """Base class for generating random augmentation parameters."""
- def __init__(self) -> None:
- super().__init__()
-
- def __post_init__(self) -> None:
- self.set_rng_device_and_dtype()
-
- def set_rng_device_and_dtype(
- self, device: torch.device = torch.device('cpu'), dtype: torch.dtype = torch.float32
- ) -> None:
- """Change the random generation device and dtype.
-
- Note:
- The generated random numbers are not reproducible across different devices and dtypes.
- """
- self.make_samplers(device, dtype)
-
- def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
- raise NotImplementedError
-
- def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, torch.Tensor]: # type:ignore
- raise NotImplementedError
-
-
-class PlainUniformGenerator(RandomGeneratorBase):
- r"""Generate random parameters that distributed uniformly.
-
- Args:
- *samplers: a list of tuple in a pattern of ``(factor, name, center, range)``, in which
- the factor can be a two-numbered tuple, or a ``(2,)`` shaped torch tensor. The name
- will be the corresponding key of the returning dict. The center and range must be
- both provided worked as a validator to the given factor.
-
- Returns:
- A dict of parameters to be passed for transformation according the number of samplers
- and the pointed returning name of each tuple.
- - ``name``: element-wise probabilities 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)``.
-
- Example:
- >>> _ = torch.manual_seed(44)
- >>> PlainUniformGenerator(
- ... ((0., 1.), "factor_1", None, None),
- ... (torch.tensor([-0.5, 0.5]), "factor_2", 0.1, (-1., 1.)),
- ... )(torch.Size([2]))
- {'factor_1': tensor([0.7196, 0.7307]), 'factor_2': tensor([ 0.3278, -0.3657])}
- """
- def __init__(self, *samplers: ParameterBound) -> None:
- super().__init__()
- self.samplers = samplers
- names = []
- for factor, name, _, _ in samplers:
- if name in names:
- raise RuntimeError(f"factor name `{name}` has already been registered. Please check the duplication.")
- names.append(name)
- if isinstance(factor, torch.nn.Parameter):
- self.register_parameter(name, factor)
- elif isinstance(factor, torch.Tensor):
- self.register_buffer(name, factor)
-
- def __repr__(self) -> str:
- repr = ", ".join([f"{name}={factor}" for factor, name, _, _ in self.samplers])
- return repr
-
- def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
- self.sampler_dict: Dict[str, Distribution] = {}
- for factor, name, center, bound in self.samplers:
- if center is None and bound is None:
- factor = torch.as_tensor(factor, device=device, dtype=dtype)
- elif center is None or bound is None:
- raise ValueError(f"`center` and `bound` should be both None or provided. Got {center} and {bound}.")
- else:
- factor = _range_bound(
- factor, name, center=center, bounds=bound, device=device, dtype=dtype
- )
- self.sampler_dict.update({name: Uniform(factor[0], factor[1], validate_args=False)})
-
- def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, torch.Tensor]: # type:ignore
- batch_size = batch_shape[0]
- _common_param_check(batch_size, same_on_batch)
- _device, _dtype = _extract_device_dtype([t for t, _, _, _ in self.samplers])
-
- return dict({
- name: _adapted_rsampling((batch_size,), dist, same_on_batch).to(
- device=_device, dtype=_dtype) for name, dist in self.sampler_dict.items()
- })
-
-
-class ProbabilityGenerator(RandomGeneratorBase):
- r"""Generate random probabilities for a batch of inputs.
-
- Args:
- p: probability to generate an 1-d binary mask. Default value is 0.5.
-
- Returns:
- A dict of parameters to be passed for transformation.
- - probs (torch.Tensor): element-wise probabilities 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, p: float = 0.5) -> None:
- super().__init__()
- self.p = p
-
- def __repr__(self) -> str:
- repr = f"p={self.p}"
- return repr
-
- def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
- p = torch.tensor(float(self.p), device=device, dtype=dtype)
- self.sampler = Bernoulli(p)
-
- def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, torch.Tensor]: # type:ignore
- batch_size = batch_shape[0]
- probs_mask: torch.Tensor = _adapted_sampling((batch_size,), self.sampler, same_on_batch).bool()
- return dict(probs=probs_mask)
-
-
-class AffineGenerator(RandomGeneratorBase):
- r"""Get parameters for ``affine`` for a random affine transform.
-
- Args:
- degrees: Range of degrees to select from like (min, max).
- 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.
- scale: scaling factor interval, e.g (a, b), then scale is
- randomly sampled from the range a <= scale <= b. Will keep original scale by default.
- 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.
- - translations (torch.Tensor): element-wise translations with a shape of (B, 2).
- - center (torch.Tensor): element-wise center with a shape of (B, 2).
- - scale (torch.Tensor): element-wise scales with a shape of (B, 2).
- - angle (torch.Tensor): element-wise rotation angles with a shape of (B,).
- - sx (torch.Tensor): element-wise x-axis shears with a shape of (B,).
- - sy (torch.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,
- degrees: Union[torch.Tensor, float, Tuple[float, float]],
- translate: Optional[Union[torch.Tensor, Tuple[float, float]]] = None,
- scale: Optional[Union[torch.Tensor, Tuple[float, float], Tuple[float, float, float, float]]] = None,
- shear: Optional[Union[torch.Tensor, float, Tuple[float, float]]] = None,
- ) -> None:
- super().__init__()
- self.degrees = degrees
- self.translate = translate
- self.scale = scale
- self.shear = shear
-
- def __repr__(self) -> str:
- repr = f"degrees={self.degrees}, translate={self.translate}, scale={self.scale}, shear={self.shear}"
- return repr
-
- def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
- _degrees = _range_bound(self.degrees, 'degrees', 0, (-360, 360)).to(device=device, dtype=dtype)
- _translate = self.translate if self.translate is None else \
- _range_bound(self.translate, 'translate', bounds=(0, 1), check='singular').to(device=device, dtype=dtype)
- _scale: Optional[torch.Tensor] = None
- if self.scale is not None:
- if len(self.scale) == 2:
- _scale = _range_bound(
- self.scale[:2], 'scale', bounds=(0, float('inf')), check='singular').to(device=device, dtype=dtype)
- elif len(self.scale) == 4:
- _scale = torch.cat([
- _range_bound(self.scale[:2], 'scale_x', bounds=(0, float('inf')), check='singular'),
- _range_bound(self.scale[2:], 'scale_y', bounds=(0, float('inf')), check='singular'), # type:ignore
- ]).to(device=device, dtype=dtype)
- else:
- raise ValueError(f"'scale' expected to be either 2 or 4 elements. Got {self.scale}")
- _shear: Optional[torch.Tensor] = None
- if self.shear is not None:
- shear = torch.as_tensor(self.shear, device=device, dtype=dtype)
- if shear.shape == torch.Size([2, 2]):
- _shear = shear
- else:
- _shear = torch.stack([
- _range_bound(shear if shear.dim() == 0 else shear[:2], 'shear-x', 0, (-360, 360)),
- torch.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)),
- ])
-
- translate_x_sampler: Optional[Uniform] = None
- translate_y_sampler: Optional[Uniform] = None
- scale_2_sampler: Optional[Uniform] = None
- scale_4_sampler: Optional[Uniform] = None
- shear_x_sampler: Optional[Uniform] = None
- shear_y_sampler: Optional[Uniform] = None
-
- if _translate is not None:
- translate_x_sampler = Uniform(-_translate[0], _translate[0], validate_args=False)
- translate_y_sampler = Uniform(-_translate[1], _translate[1], validate_args=False)
- if _scale is not None:
- if len(_scale) == 2:
- scale_2_sampler = Uniform(_scale[0], _scale[1], validate_args=False)
- elif len(_scale) == 4:
- scale_2_sampler = Uniform(_scale[0], _scale[1], validate_args=False)
- scale_4_sampler = Uniform(_scale[2], _scale[3], validate_args=False)
- else:
- raise ValueError(f"'scale' expected to be either 2 or 4 elements. Got {self.scale}")
- if _shear is not None:
- _joint_range_check(cast(torch.Tensor, _shear)[0], "shear")
- _joint_range_check(cast(torch.Tensor, _shear)[1], "shear")
- 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.degree_sampler = Uniform(_degrees[0], _degrees[1], validate_args=False)
- self.translate_x_sampler = translate_x_sampler
- self.translate_y_sampler = translate_y_sampler
- self.scale_2_sampler = scale_2_sampler
- self.scale_4_sampler = scale_4_sampler
- 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, torch.Tensor]: # type: ignore
- batch_size = batch_shape[0]
- height = batch_shape[-2]
- width = batch_shape[-1]
-
- _device, _dtype = _extract_device_dtype([self.degrees, self.translate, self.scale, 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}.")
-
- angle = _adapted_rsampling((batch_size,), self.degree_sampler, same_on_batch).to(device=_device, dtype=_dtype)
-
- # compute tensor ranges
- if self.scale_2_sampler is not None:
- _scale = _adapted_rsampling((batch_size,), self.scale_2_sampler, same_on_batch).unsqueeze(1).repeat(1, 2)
- if self.scale_4_sampler is not None:
- _scale[:, 1] = _adapted_rsampling((batch_size,), self.scale_4_sampler, same_on_batch)
- _scale = _scale.to(device=_device, dtype=_dtype)
- else:
- _scale = torch.ones((batch_size, 2), device=_device, dtype=_dtype)
-
- if self.translate_x_sampler is not None and self.translate_y_sampler is not None:
- translations = torch.stack([
- _adapted_rsampling((batch_size,), self.translate_x_sampler, same_on_batch) * width,
- _adapted_rsampling((batch_size,), self.translate_y_sampler, same_on_batch) * height,
- ], dim=-1)
- translations = translations.to(device=_device, dtype=_dtype)
- else:
- translations = torch.zeros((batch_size, 2), device=_device, dtype=_dtype)
-
- center: torch.Tensor = torch.tensor([width, height], device=_device, dtype=_dtype).view(1, 2) / 2.0 - 0.5
- center = center.expand(batch_size, -1)
-
- if self.shear_x_sampler is not None and self.shear_y_sampler is not None:
- 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)
- else:
- sx = sy = torch.tensor([0] * batch_size, device=_device, dtype=_dtype)
-
- return dict(translations=translations, center=center, scale=_scale, angle=angle, sx=sx, sy=sy)
-
-
-class ColorJitterGenerator(RandomGeneratorBase):
- r"""Generate random color jiter parameters for a batch of images.
-
- Args:
- brightness: The brightness factor to apply.
- contrast: The contrast factor to apply.
- saturation: The saturation factor to apply.
- hue: The hue factor to apply.
-
- Returns:
- A dict of parameters to be passed for transformation.
- - brightness_factor: element-wise brightness factors with a shape of (B,).
- - contrast_factor: element-wise contrast factors with a shape of (B,).
- - hue_factor: element-wise hue factors with a shape of (B,).
- - saturation_factor: element-wise saturation factors with a shape of (B,).
- - order: applying orders of the color adjustments with a shape of (4). In which,
- 0 is brightness adjustment; 1 is contrast adjustment;
- 2 is saturation adjustment; 3 is hue adjustment.
-
- 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,
- brightness: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.0,
- contrast: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.0,
- saturation: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.0,
- hue: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.0,
- ) -> None:
- super().__init__()
- self.brightness = brightness
- self.contrast = contrast
- self.saturation = saturation
- self.hue = hue
-
- def __repr__(self) -> str:
- repr = f"brightness={self.brightness}, contrast={self.contrast}, saturation={self.saturation}, hue={self.hue}"
- return repr
-
- def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
- brightness: torch.Tensor = _range_bound(
- self.brightness, 'brightness', center=1.0, bounds=(0, 2), device=device, dtype=dtype
- )
- contrast: torch.Tensor = _range_bound(
- self.contrast, 'contrast', center=1.0, device=device, dtype=dtype
- )
- saturation: torch.Tensor = _range_bound(
- self.saturation, 'saturation', center=1.0, device=device, dtype=dtype
- )
- hue: torch.Tensor = _range_bound(self.hue, 'hue', bounds=(-0.5, 0.5), device=device, dtype=dtype)
-
- _joint_range_check(brightness, "brightness", (0, 2))
- _joint_range_check(contrast, "contrast", (0, float('inf')))
- _joint_range_check(hue, "hue", (-0.5, 0.5))
- _joint_range_check(saturation, "saturation", (0, float('inf')))
-
- self.brightness_sampler = Uniform(brightness[0], brightness[1], validate_args=False)
- self.contrast_sampler = Uniform(contrast[0], contrast[1], validate_args=False)
- self.hue_sampler = Uniform(hue[0], hue[1], validate_args=False)
- self.saturation_sampler = Uniform(saturation[0], saturation[1], validate_args=False)
- self.randperm = partial(torch.randperm, device=device, dtype=dtype)
-
- def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, torch.Tensor]: # type:ignore
- batch_size = batch_shape[0]
- _common_param_check(batch_size, same_on_batch)
- _device, _dtype = _extract_device_dtype([self.brightness, self.contrast, self.hue, self.saturation])
- brightness_factor = _adapted_rsampling((batch_size,), self.brightness_sampler, same_on_batch)
- contrast_factor = _adapted_rsampling((batch_size,), self.contrast_sampler, same_on_batch)
- hue_factor = _adapted_rsampling((batch_size,), self.hue_sampler, same_on_batch)
- saturation_factor = _adapted_rsampling((batch_size,), self.saturation_sampler, same_on_batch)
- return dict(
- brightness_factor=brightness_factor.to(device=_device, dtype=_dtype),
- contrast_factor=contrast_factor.to(device=_device, dtype=_dtype),
- hue_factor=hue_factor.to(device=_device, dtype=_dtype),
- saturation_factor=saturation_factor.to(device=_device, dtype=_dtype),
- order=self.randperm(4).to(device=_device, dtype=_dtype).long(),
- )
-
-
-class CropGenerator(RandomGeneratorBase):
- r"""Get parameters for ```crop``` transformation for crop transform.
-
- Args:
- size (tuple): Desired size of the crop operation, like (h, w).
- If tensor, it must be (B, 2).
- resize_to (tuple): Desired output size of the crop, like (h, w). If None, no resize will be performed.
-
- Returns:
- params Dict[str, torch.Tensor]: parameters to be passed for transformation.
- - src (torch.Tensor): cropping bounding boxes with a shape of (B, 4, 2).
- - dst (torch.Tensor): output bounding boxes with a shape (B, 4, 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,
- size: Union[Tuple[int, int], torch.Tensor],
- resize_to: Optional[Tuple[int, int]] = None
- ) -> None:
- super().__init__()
- self.size = size
- self.resize_to = resize_to
-
- def __repr__(self) -> str:
- repr = f"crop_size={self.size}"
- if self.resize_to is not None:
- repr += f", resize_to={self.resize_to}"
- return repr
-
- def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
- self.rand_sampler = Uniform(
- torch.tensor(0., device=device, dtype=dtype), torch.tensor(1., device=device, dtype=dtype))
-
- def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, torch.Tensor]: # type:ignore
- batch_size = batch_shape[0]
- _common_param_check(batch_size, same_on_batch)
- _device, _dtype = _extract_device_dtype([self.size if isinstance(self.size, torch.Tensor) else None])
-
- if batch_size == 0:
- return dict(
- src=torch.zeros([0, 4, 2], device=_device, dtype=_dtype),
- dst=torch.zeros([0, 4, 2], device=_device, dtype=_dtype),
- )
-
- input_size = (batch_shape[-2], batch_shape[-1])
- if not isinstance(self.size, torch.Tensor):
- size = torch.tensor(self.size, device=_device, dtype=_dtype).repeat(batch_size, 1)
- else:
- size = self.size.to(device=_device, dtype=_dtype)
- if size.shape != torch.Size([batch_size, 2]):
- raise AssertionError(
- "If `size` is a tensor, it must be shaped as (B, 2). "
- f"Got {size.shape} while expecting {torch.Size([batch_size, 2])}."
- )
- if not (input_size[0] > 0 and input_size[1] > 0 and (size > 0).all()):
- raise AssertionError(f"Got non-positive input size or size. {input_size}, {size}.")
- size = size.floor()
-
- x_diff = input_size[1] - size[:, 1] + 1
- y_diff = input_size[0] - size[:, 0] + 1
-
- # Start point will be 0 if diff < 0
- x_diff = x_diff.clamp(0)
- y_diff = y_diff.clamp(0)
-
- if same_on_batch:
- # If same_on_batch, select the first then repeat.
- x_start = (_adapted_rsampling(
- (batch_size,), self.rand_sampler, same_on_batch).to(x_diff) * x_diff[0]).floor()
- y_start = (_adapted_rsampling(
- (batch_size,), self.rand_sampler, same_on_batch).to(y_diff) * y_diff[0]).floor()
- else:
- x_start = (_adapted_rsampling(
- (batch_size,), self.rand_sampler, same_on_batch).to(x_diff) * x_diff).floor()
- y_start = (_adapted_rsampling(
- (batch_size,), self.rand_sampler, same_on_batch).to(y_diff) * y_diff).floor()
- crop_src = bbox_generator(
- x_start.view(-1).to(device=_device, dtype=_dtype),
- y_start.view(-1).to(device=_device, dtype=_dtype),
- torch.where(size[:, 1] == 0, torch.tensor(input_size[1], device=_device, dtype=_dtype), size[:, 1]),
- torch.where(size[:, 0] == 0, torch.tensor(input_size[0], device=_device, dtype=_dtype), size[:, 0]),
- )
-
- if self.resize_to is None:
- crop_dst = bbox_generator(
- torch.tensor([0] * batch_size, device=_device, dtype=_dtype),
- torch.tensor([0] * batch_size, device=_device, dtype=_dtype),
- size[:, 1],
- size[:, 0],
- )
- else:
- if not (
- len(self.resize_to) == 2
- and isinstance(self.resize_to[0], (int,))
- and isinstance(self.resize_to[1], (int,))
- and self.resize_to[0] > 0
- and self.resize_to[1] > 0
- ):
- raise AssertionError(f"`resize_to` must be a tuple of 2 positive integers. Got {self.resize_to}.")
- crop_dst = torch.tensor(
- [[
- [0, 0],
- [self.resize_to[1] - 1, 0],
- [self.resize_to[1] - 1, self.resize_to[0] - 1],
- [0, self.resize_to[0] - 1]
- ]],
- device=_device,
- dtype=_dtype,
- ).repeat(batch_size, 1, 1)
-
- _input_size = torch.tensor(input_size, device=_device, dtype=torch.long).expand(batch_size, -1)
-
- return dict(src=crop_src, dst=crop_dst, input_size=_input_size)
-
-
-class ResizedCropGenerator(CropGenerator):
- r"""Get cropping heights and widths for ```crop``` transformation for resized crop transform.
-
- Args:
- output_size (Tuple[int, int]): expected output size of each edge.
- scale (torch.Tensor): range of size of the origin size cropped with (2,) shape.
- ratio (torch.Tensor): range of aspect ratio of the origin aspect ratio cropped with (2,) shape.
-
- Returns:
- params Dict[str, torch.Tensor]: parameters to be passed for transformation.
- - size (torch.Tensor): element-wise cropping sizes with a shape of (B, 2).
-
- Note:
- The generated random numbers are not reproducible across different devices and dtypes.
-
- Examples:
- >>> _ = torch.manual_seed(42)
- >>> random_crop_size_generator(3, (30, 30), scale=torch.tensor([.7, 1.3]), ratio=torch.tensor([.9, 1.]))
- {'size': tensor([[29., 29.],
- [27., 28.],
- [26., 29.]])}
- """
- def __init__(
- self,
- output_size: Tuple[int, int],
- scale: Union[torch.Tensor, Tuple[float, float]],
- ratio: Union[torch.Tensor, Tuple[float, float]]
- ) -> None:
- self.scale = scale
- self.ratio = ratio
- self.output_size = output_size
- if not (
- len(output_size) == 2
- and isinstance(output_size[0], (int,))
- and isinstance(output_size[1], (int,))
- and output_size[0] > 0
- and output_size[1] > 0
- ):
- raise AssertionError(f"`output_size` must be a tuple of 2 positive integers. Got {output_size}.")
- super().__init__(size=output_size, resize_to=self.output_size) # fake an intermedia crop size
-
- def __repr__(self) -> str:
- repr = f"scale={self.scale}, resize_to={self.ratio}, output_size={self.output_size}"
- return repr
-
- def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
- scale = torch.as_tensor(self.scale, device=device, dtype=dtype)
- ratio = torch.as_tensor(self.ratio, device=device, dtype=dtype)
- _joint_range_check(scale, "scale")
- _joint_range_check(ratio, "ratio")
- self.rand_sampler = Uniform(
- torch.tensor(0., device=device, dtype=dtype), torch.tensor(1., device=device, dtype=dtype))
- self.log_ratio_sampler = Uniform(torch.log(ratio[0]), torch.log(ratio[1]), validate_args=False)
-
- def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, torch.Tensor]: # type:ignore
- batch_size = batch_shape[0]
- size = (batch_shape[-2], batch_shape[-1])
- _device, _dtype = _extract_device_dtype([self.scale, self.ratio])
-
- if batch_size == 0:
- return dict(
- src=torch.zeros([0, 4, 2], device=_device, dtype=_dtype),
- dst=torch.zeros([0, 4, 2], device=_device, dtype=_dtype),
- size=torch.zeros([0, 2], device=_device, dtype=_dtype),
- )
-
- rand = _adapted_rsampling(
- (batch_size, 10), self.rand_sampler, same_on_batch).to(device=_device, dtype=_dtype)
- area = (rand * (self.scale[1] - self.scale[0]) + self.scale[0]) * size[0] * size[1]
- log_ratio = _adapted_rsampling(
- (batch_size, 10), self.log_ratio_sampler, same_on_batch).to(device=_device, dtype=_dtype)
- aspect_ratio = torch.exp(log_ratio)
-
- w = torch.sqrt(area * aspect_ratio).round().floor()
- h = torch.sqrt(area / aspect_ratio).round().floor()
- # Element-wise w, h condition
- cond = ((0 < w) * (w < size[0]) * (0 < h) * (h < size[1])).int()
-
- # torch.argmax is not reproducible across devices: https://github.com/pytorch/pytorch/issues/17738
- # Here, we will select the first occurrence of the duplicated elements.
- cond_bool, argmax_dim1 = ((cond.cumsum(1) == 1) & cond.bool()).max(1)
- h_out = w[torch.arange(0, batch_size, device=_device, dtype=torch.long), argmax_dim1]
- w_out = h[torch.arange(0, batch_size, device=_device, dtype=torch.long), argmax_dim1]
-
- if not cond_bool.all():
- # Fallback to center crop
- in_ratio = float(size[0]) / float(size[1])
- _min = self.ratio.min() if isinstance(self.ratio, torch.Tensor) else min(self.ratio)
- if in_ratio < _min: # type:ignore
- h_ct = torch.tensor(size[0], device=_device, dtype=_dtype)
- w_ct = torch.round(h_ct / _min)
- elif in_ratio > _min: # type:ignore
- w_ct = torch.tensor(size[1], device=_device, dtype=_dtype)
- h_ct = torch.round(w_ct * _min)
- else: # whole image
- h_ct = torch.tensor(size[0], device=_device, dtype=_dtype)
- w_ct = torch.tensor(size[1], device=_device, dtype=_dtype)
- h_ct = h_ct.floor()
- w_ct = w_ct.floor()
-
- h_out = h_out.where(cond_bool, h_ct)
- w_out = w_out.where(cond_bool, w_ct)
-
- # Update the crop size.
- self.size = torch.stack([h_out, w_out], dim=1)
- return super().forward(batch_shape, same_on_batch)
-
-
-class PerspectiveGenerator(RandomGeneratorBase):
- r"""Get parameters for ``perspective`` for a random perspective transform.
-
- Args:
- distortion_scale: the degree of distortion, ranged from 0 to 1.
-
- Returns:
- A dict of parameters to be passed for transformation.
- - start_points (torch.Tensor): element-wise perspective source areas with a shape of (B, 4, 2).
- - end_points (torch.Tensor): element-wise perspective target areas with a shape of (B, 4, 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, distortion_scale: Union[torch.Tensor, float] = 0.5) -> None:
- super().__init__()
- self.distortion_scale = distortion_scale
-
- def __repr__(self) -> str:
- repr = f"distortion_scale={self.distortion_scale}"
- return repr
-
- def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
- self._distortion_scale = torch.as_tensor(self.distortion_scale, device=device, dtype=dtype)
- if not (self._distortion_scale.dim() == 0 and 0 <= self._distortion_scale <= 1):
- raise AssertionError(f"'distortion_scale' must be a scalar within [0, 1]. Got {self._distortion_scale}.")
- self.rand_val_sampler = Uniform(
- torch.tensor(0, device=device, dtype=dtype),
- torch.tensor(1, device=device, dtype=dtype),
- validate_args=False
- )
-
- def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, torch.Tensor]: # type:ignore
- batch_size = batch_shape[0]
- height = batch_shape[-2]
- width = batch_shape[-1]
-
- _device, _dtype = _extract_device_dtype([self.distortion_scale])
- _common_param_check(batch_size, same_on_batch)
- 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}.")
-
- start_points: torch.Tensor = torch.tensor(
- [[[0.0, 0], [width - 1, 0], [width - 1, height - 1], [0, height - 1]]],
- device=_device,
- dtype=_dtype,
- ).expand(batch_size, -1, -1)
-
- # generate random offset not larger than half of the image
- fx = self._distortion_scale * width / 2
- fy = self._distortion_scale * height / 2
-
- factor = torch.stack([fx, fy], dim=0).view(-1, 1, 2).to(device=_device, dtype=_dtype)
-
- # TODO: This line somehow breaks the gradcheck
- rand_val: torch.Tensor = _adapted_rsampling(
- start_points.shape, self.rand_val_sampler, same_on_batch).to(device=_device, dtype=_dtype)
-
- pts_norm = torch.tensor(
- [[[1, 1], [-1, 1], [-1, -1], [1, -1]]], device=_device, dtype=_dtype
- )
-
- end_points = start_points + factor * rand_val * pts_norm
-
- return dict(start_points=start_points, end_points=end_points)
-
-
-class RectangleEraseGenerator(RandomGeneratorBase):
- r"""Get parameters for ```erasing``` transformation for erasing transform.
-
- Args:
- scale (torch.Tensor): range of size of the origin size cropped. Shape (2).
- ratio (torch.Tensor): range of aspect ratio of the origin aspect ratio cropped. Shape (2).
- value (float): value to be filled in the erased area.
-
- Returns:
- A dict of parameters to be passed for transformation.
- - widths (torch.Tensor): element-wise erasing widths with a shape of (B,).
- - heights (torch.Tensor): element-wise erasing heights with a shape of (B,).
- - xs (torch.Tensor): element-wise erasing x coordinates with a shape of (B,).
- - ys (torch.Tensor): element-wise erasing y coordinates with a shape of (B,).
- - values (torch.Tensor): element-wise filling values 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,
- scale: Union[torch.Tensor, Tuple[float, float]] = (0.02, 0.33),
- ratio: Union[torch.Tensor, Tuple[float, float]] = (0.3, 3.3),
- value: float = 0.
- ) -> None:
- super().__init__()
- self.scale = scale
- self.ratio = ratio
- self.value = value
-
- def __repr__(self) -> str:
- repr = f"scale={self.scale}, resize_to={self.ratio}, value={self.value}"
- return repr
-
- def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
- scale = torch.as_tensor(self.scale, device=device, dtype=dtype)
- ratio = torch.as_tensor(self.ratio, device=device, dtype=dtype)
-
- if not (isinstance(self.value, (int, float)) and self.value >= 0 and self.value <= 1):
- raise AssertionError(f"'value' must be a number between 0 - 1. Got {self.value}.")
- _joint_range_check(scale, 'scale', bounds=(0, float('inf')))
- _joint_range_check(ratio, 'ratio', bounds=(0, float('inf')))
-
- self.scale_sampler = Uniform(scale[0], scale[1], validate_args=False)
-
- if ratio[0] < 1.0 and ratio[1] > 1.0:
- self.ratio_sampler1 = Uniform(ratio[0], 1, validate_args=False)
- self.ratio_sampler2 = Uniform(1, ratio[1], validate_args=False)
- self.index_sampler = Uniform(
- torch.tensor(0, device=device, dtype=dtype),
- torch.tensor(1, device=device, dtype=dtype),
- validate_args=False
- )
- else:
- self.ratio_sampler = Uniform(ratio[0], ratio[1], validate_args=False)
- self.uniform_sampler = Uniform(
- torch.tensor(0, device=device, dtype=dtype),
- torch.tensor(1, device=device, dtype=dtype),
- validate_args=False
- )
-
- def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, torch.Tensor]: # type:ignore
- batch_size = batch_shape[0]
- height = batch_shape[-2]
- width = batch_shape[-1]
- 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}.")
-
- _common_param_check(batch_size, same_on_batch)
- _device, _dtype = _extract_device_dtype([self.ratio, self.scale])
- images_area = height * width
- target_areas = _adapted_rsampling(
- (batch_size,), self.scale_sampler, same_on_batch).to(device=_device, dtype=_dtype) * images_area
-
- if self.ratio[0] < 1.0 and self.ratio[1] > 1.0:
- aspect_ratios1 = _adapted_rsampling((batch_size,), self.ratio_sampler1, same_on_batch)
- aspect_ratios2 = _adapted_rsampling((batch_size,), self.ratio_sampler2, same_on_batch)
- if same_on_batch:
- rand_idxs = torch.round(
- _adapted_rsampling((1,), self.index_sampler, same_on_batch)).repeat(batch_size).bool()
- else:
- rand_idxs = torch.round(
- _adapted_rsampling((batch_size,), self.index_sampler, same_on_batch)).bool()
- aspect_ratios = torch.where(rand_idxs, aspect_ratios1, aspect_ratios2)
- else:
- aspect_ratios = _adapted_rsampling((batch_size,), self.ratio_sampler, same_on_batch)
-
- aspect_ratios = aspect_ratios.to(device=_device, dtype=_dtype)
-
- # based on target areas and aspect ratios, rectangle params are computed
- heights = torch.min(
- torch.max(
- torch.round((target_areas * aspect_ratios) ** (1 / 2)), torch.tensor(1.0, device=_device, dtype=_dtype)
- ),
- torch.tensor(height, device=_device, dtype=_dtype),
- )
-
- widths = torch.min(
- torch.max(
- torch.round((target_areas / aspect_ratios) ** (1 / 2)), torch.tensor(1.0, device=_device, dtype=_dtype)
- ),
- torch.tensor(width, device=_device, dtype=_dtype),
- )
-
- xs_ratio = _adapted_rsampling(
- (batch_size,), self.uniform_sampler, same_on_batch).to(device=_device, dtype=_dtype)
- ys_ratio = _adapted_rsampling(
- (batch_size,), self.uniform_sampler, same_on_batch).to(device=_device, dtype=_dtype)
-
- xs = xs_ratio * (width - widths + 1)
- ys = ys_ratio * (height - heights + 1)
-
- return dict(
- widths=widths.floor(),
- heights=heights.floor(),
- xs=xs.floor(),
- ys=ys.floor(),
- values=torch.tensor([self.value] * batch_size, device=_device, dtype=_dtype),
- )
-
-
-class MotionBlurGenerator(RandomGeneratorBase):
- r"""Get parameters for motion blur.
-
- Args:
- kernel_size: motion kernel size (odd and positive).
- If int, the kernel will have a fixed size.
- If Tuple[int, int], it will randomly generate the value from the range batch-wisely.
- angle: angle of the motion blur in degrees (anti-clockwise rotation).
- If float, it will generate the value from (-angle, angle).
- direction: forward/backward direction of the motion blur.
- Lower values towards -1.0 will point the motion blur towards the back (with angle provided via angle),
- while higher values towards 1.0 will point the motion blur forward. A value of 0.0 leads to a
- uniformly (but still angled) motion blur.
- If float, it will generate the value from (-direction, direction).
- If Tuple[int, int], it will randomly generate the value from the range.
-
- Returns:
- A dict of parameters to be passed for transformation.
- - ksize_factor (torch.Tensor): element-wise kernel size factors with a shape of (B,).
- - angle_factor (torch.Tensor): element-wise angle factors with a shape of (B,).
- - direction_factor (torch.Tensor): element-wise direction factors 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,
- kernel_size: Union[int, Tuple[int, int]],
- angle: Union[torch.Tensor, float, Tuple[float, float]],
- direction: Union[torch.Tensor, float, Tuple[float, float]],
- ) -> None:
- super().__init__()
- self.kernel_size = kernel_size
- self.angle = angle
- self.direction = direction
-
- def __repr__(self) -> str:
- repr = f"kernel_size={self.kernel_size}, angle={self.angle}, direction={self.direction}"
- return repr
-
- def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
- angle = _range_bound(self.angle, 'angle', center=0.0, bounds=(-360, 360)).to(device=device, dtype=dtype)
- direction = _range_bound(self.direction, 'direction', center=0.0, bounds=(-1, 1)).to(device=device, dtype=dtype)
- if isinstance(self.kernel_size, int):
- if not (self.kernel_size >= 3 and self.kernel_size % 2 == 1):
- raise AssertionError(f"`kernel_size` must be odd and greater than 3. Got {self.kernel_size}.")
- self.ksize_sampler = Uniform(self.kernel_size // 2, self.kernel_size // 2, validate_args=False)
- elif isinstance(self.kernel_size, tuple):
- # kernel_size is fixed across the batch
- if len(self.kernel_size) != 2:
- raise AssertionError(f"`kernel_size` must be (2,) if it is a tuple. Got {self.kernel_size}.")
- self.ksize_sampler = Uniform(self.kernel_size[0] // 2, self.kernel_size[1] // 2, validate_args=False)
- else:
- raise TypeError(f"Unsupported type: {type(self.kernel_size)}")
-
- self.angle_sampler = Uniform(angle[0], angle[1], validate_args=False)
- self.direction_sampler = Uniform(direction[0], direction[1], validate_args=False)
-
- def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, torch.Tensor]: # type:ignore
- batch_size = batch_shape[0]
- _common_param_check(batch_size, same_on_batch)
- # self.ksize_factor.expand((batch_size, -1))
- _device, _dtype = _extract_device_dtype([self.angle, self.direction])
- angle_factor = _adapted_rsampling((batch_size,), self.angle_sampler, same_on_batch)
- direction_factor = _adapted_rsampling((batch_size,), self.direction_sampler, same_on_batch)
- ksize_factor = _adapted_rsampling((batch_size,), self.ksize_sampler, same_on_batch).int() * 2 + 1
-
- return dict(
- ksize_factor=ksize_factor.to(device=_device, dtype=torch.int32),
- angle_factor=angle_factor.to(device=_device, dtype=_dtype),
- direction_factor=direction_factor.to(device=_device, dtype=_dtype),
- )
-
-
-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).
- If tuple (x, y), bits will be generated from (x, y).
-
- Returns:
- A dict of parameters to be passed for transformation.
- - bits_factor (torch.Tensor): element-wise bit factors 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, bits: Union[int, Tuple[int, int], torch.Tensor]) -> None:
- super().__init__()
- self.bits = bits
-
- def __repr__(self) -> str:
- repr = f"bits={self.bits}"
- return repr
-
- def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
- bits = torch.as_tensor(self.bits, device=device, dtype=dtype)
- if len(bits.size()) == 0:
- bits = bits.repeat(2)
- bits[1] = 8
- elif not (len(bits.size()) == 1 and bits.size(0) == 2):
- raise ValueError(f"'bits' shall be either a scalar or a length 2 tensor. Got {bits}.")
- _joint_range_check(bits, 'bits', (0, 8))
- self.bit_sampler = Uniform(bits[0], bits[1], validate_args=False)
-
- def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, torch.Tensor]: # type:ignore
- batch_size = batch_shape[0]
- _common_param_check(batch_size, same_on_batch)
- _device, _dtype = _extract_device_dtype([self.bits if isinstance(self.bits, torch.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))
-
-
-class MixupGenerator(RandomGeneratorBase):
- r"""Generate mixup indexes and lambdas for a batch of inputs.
-
- Args:
- 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.
-
- Returns:
- A dict of 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. 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, lambda_val: Optional[Union[torch.Tensor, Tuple[float, float]]] = None, p: float = 1.0) -> None:
- super().__init__()
- self.lambda_val = lambda_val
- self.p = p
-
- def __repr__(self) -> str:
- repr = f"lambda_val={self.lambda_val}"
- return repr
-
- def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
- if self.lambda_val is None:
- lambda_val = torch.tensor([0.0, 1.0], device=device, dtype=dtype)
- else:
- lambda_val = torch.as_tensor(self.lambda_val, device=device, dtype=dtype)
-
- _joint_range_check(lambda_val, 'lambda_val', bounds=(0, 1))
- self.lambda_sampler = Uniform(lambda_val[0], lambda_val[1], validate_args=False)
- self.prob_sampler = Bernoulli(torch.tensor(float(self.p), device=device, dtype=dtype))
-
- def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, torch.Tensor]:
- batch_size = batch_shape[0]
-
- _common_param_check(batch_size, same_on_batch)
- _device, _dtype = _extract_device_dtype([self.lambda_val])
-
- with torch.no_grad():
- batch_probs: torch.Tensor = _adapted_sampling((batch_size,), self.prob_sampler, same_on_batch)
- mixup_pairs: torch.Tensor = torch.randperm(batch_size, device=_device, dtype=_dtype).long()
- mixup_lambdas: torch.Tensor = _adapted_rsampling((batch_size,), self.lambda_sampler, 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),
- )
-
-
-class CutmixGenerator(RandomGeneratorBase):
- r"""Generate cutmix indexes and lambdas for a batch of inputs.
-
- Args:
- 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.
-
- 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. 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,
- cut_size: Optional[Union[torch.Tensor, Tuple[float, float]]] = None,
- beta: Optional[Union[torch.Tensor, float]] = None,
- num_mix: int = 1,
- p: float = 1.0,
- ) -> None:
- super().__init__()
- self.cut_size = cut_size
- self.beta = beta
- self.num_mix = num_mix
- self.p = p
-
- 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}.")
-
- def __repr__(self) -> str:
- repr = f"cut_size={self.cut_size}, beta={self.beta}, num_mix={self.num_mix}"
- return repr
-
- 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)
- else:
- self._beta = torch.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)
- else:
- self._cut_size = torch.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.rand_sampler = Uniform(
- torch.tensor(0., device=device, dtype=dtype),
- torch.tensor(1., device=device, dtype=dtype),
- validate_args=False
- )
-
- def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, torch.Tensor]:
- batch_size = batch_shape[0]
- height = batch_shape[-2]
- width = batch_shape[-1]
-
- 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}.")
- _device, _dtype = _extract_device_dtype([self.beta, self.cut_size])
- _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),
- )
-
- 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)
- 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:
- # Argument 1 to "clamp" of "_TensorBase" has incompatible type "Tensor"; expected "float"
- cutmix_betas = torch.min(torch.max(cutmix_betas, self._cut_size[0]), self._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: torch.Tensor = _adapted_rsampling(
- _gen_shape, self.rand_sampler, same_on_batch) * (width - cut_width - 1)
- y_start: torch.Tensor = _adapted_rsampling(
- _gen_shape, self.rand_sampler, same_on_batch) * (height - cut_height - 1)
- x_start = x_start.floor().to(device=_device, dtype=_dtype)
- y_start = y_start.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(self.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),
- )
-
-
-def random_prob_generator(
- batch_size: int,
- p: float = 0.5,
- same_on_batch: bool = False,
- device: torch.device = torch.device('cpu'),
- dtype: torch.dtype = torch.float32,
-) -> torch.Tensor:
- r"""Generate random probabilities for a batch of inputs.
-
- Args:
- batch_size (int): the number of images.
- p (float): probability to generate an 1-d binary mask. Default value is 0.5.
- 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:
- torch.Tensor: parameters to be passed for transformation.
- - probs (torch.Tensor): element-wise probabilities with a shape of (B,).
-
- Note:
- The generated random numbers are not reproducible across different devices and dtypes.
- """
- _common_param_check(batch_size, same_on_batch)
- if not isinstance(p, (int, float)) or p > 1 or p < 0:
- raise TypeError(f"The probability should be a float number within [0, 1]. Got {type(p)}.")
-
- _bernoulli = Bernoulli(torch.tensor(float(p), device=device, dtype=dtype))
- probs_mask: torch.Tensor = _adapted_sampling((batch_size,), _bernoulli, same_on_batch).bool()
-
- return probs_mask
-
-
-@_deprecated(replace_with=ColorJitterGenerator.__name__)
-def random_color_jitter_generator(
- batch_size: int,
- brightness: Optional[torch.Tensor] = None,
- contrast: Optional[torch.Tensor] = None,
- saturation: Optional[torch.Tensor] = None,
- hue: 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 random color jiter parameters for a batch of images.
-
- Args:
- batch_size (int): the number of images.
- brightness (torch.Tensor, optional): Brightness factor tensor of range (a, b).
- The provided range must follow 0 <= a <= b <= 2. Default value is [0., 0.].
- contrast (torch.Tensor, optional): Contrast factor tensor of range (a, b).
- The provided range must follow 0 <= a <= b. Default value is [0., 0.].
- saturation (torch.Tensor, optional): Saturation factor tensor of range (a, b).
- The provided range must follow 0 <= a <= b. Default value is [0., 0.].
- hue (torch.Tensor, optional): Saturation factor tensor of range (a, b).
- The provided range must follow -0.5 <= a <= b < 0.5. Default value is [0., 0.].
- 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.
- - brightness_factor (torch.Tensor): element-wise brightness factors with a shape of (B,).
- - contrast_factor (torch.Tensor): element-wise contrast factors with a shape of (B,).
- - hue_factor (torch.Tensor): element-wise hue factors with a shape of (B,).
- - saturation_factor (torch.Tensor): element-wise saturation factors with a shape of (B,).
- - order (torch.Tensor): applying orders of the color adjustments with a shape of (4). In which,
- 0 is brightness adjustment; 1 is contrast adjustment;
- 2 is saturation adjustment; 3 is hue adjustment.
-
- Note:
- The generated random numbers are not reproducible across different devices and dtypes.
- """
- _common_param_check(batch_size, same_on_batch)
- _device, _dtype = _extract_device_dtype([brightness, contrast, hue, saturation])
- brightness = torch.as_tensor([0.0, 0.0] if brightness is None else brightness, device=device, dtype=dtype)
- contrast = torch.as_tensor([0.0, 0.0] if contrast is None else contrast, device=device, dtype=dtype)
- hue = torch.as_tensor([0.0, 0.0] if hue is None else hue, device=device, dtype=dtype)
- saturation = torch.as_tensor([0.0, 0.0] if saturation is None else saturation, device=device, dtype=dtype)
-
- _joint_range_check(brightness, "brightness", (0, 2))
- _joint_range_check(contrast, "contrast", (0, float('inf')))
- _joint_range_check(hue, "hue", (-0.5, 0.5))
- _joint_range_check(saturation, "saturation", (0, float('inf')))
-
- brightness_factor = _adapted_uniform((batch_size,), brightness[0], brightness[1], same_on_batch)
- contrast_factor = _adapted_uniform((batch_size,), contrast[0], contrast[1], same_on_batch)
- hue_factor = _adapted_uniform((batch_size,), hue[0], hue[1], same_on_batch)
- saturation_factor = _adapted_uniform((batch_size,), saturation[0], saturation[1], same_on_batch)
-
- return dict(
- brightness_factor=brightness_factor.to(device=_device, dtype=_dtype),
- contrast_factor=contrast_factor.to(device=_device, dtype=_dtype),
- hue_factor=hue_factor.to(device=_device, dtype=_dtype),
- saturation_factor=saturation_factor.to(device=_device, dtype=_dtype),
- order=torch.randperm(4, device=_device, dtype=_dtype).long(),
- )
-
-
-@_deprecated(replace_with=PerspectiveGenerator.__name__)
-def random_perspective_generator(
- batch_size: int,
- height: int,
- width: int,
- distortion_scale: torch.Tensor,
- same_on_batch: bool = False,
- device: torch.device = torch.device('cpu'),
- dtype: torch.dtype = torch.float32,
-) -> Dict[str, torch.Tensor]:
- r"""Get parameters for ``perspective`` for a random perspective transform.
-
- Args:
- batch_size (int): the tensor batch size.
- height (int) : height of the image.
- width (int): width of the image.
- distortion_scale (torch.Tensor): it controls the degree of distortion and ranges from 0 to 1.
- 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.
- - start_points (torch.Tensor): element-wise perspective source areas with a shape of (B, 4, 2).
- - end_points (torch.Tensor): element-wise perspective target areas with a shape of (B, 4, 2).
-
- Note:
- The generated random numbers are not reproducible across different devices and dtypes.
- """
- _common_param_check(batch_size, same_on_batch)
- if not (distortion_scale.dim() == 0 and 0 <= distortion_scale <= 1):
- raise AssertionError(f"'distortion_scale' must be a scalar within [0, 1]. Got {distortion_scale}.")
- 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}.")
-
- start_points: torch.Tensor = torch.tensor(
- [[[0.0, 0], [width - 1, 0], [width - 1, height - 1], [0, height - 1]]],
- device=distortion_scale.device,
- dtype=distortion_scale.dtype,
- ).expand(batch_size, -1, -1)
-
- # generate random offset not larger than half of the image
- fx = distortion_scale * width / 2
- fy = distortion_scale * height / 2
-
- factor = torch.stack([fx, fy], dim=0).view(-1, 1, 2)
-
- # TODO: This line somehow breaks the gradcheck
- rand_val: torch.Tensor = _adapted_uniform(
- start_points.shape,
- torch.tensor(0, device=device, dtype=dtype),
- torch.tensor(1, device=device, dtype=dtype),
- same_on_batch,
- ).to(device=distortion_scale.device, dtype=distortion_scale.dtype)
-
- pts_norm = torch.tensor(
- [[[1, 1], [-1, 1], [-1, -1], [1, -1]]], device=distortion_scale.device, dtype=distortion_scale.dtype
- )
- end_points = start_points + factor * rand_val * pts_norm
-
- return dict(start_points=start_points, end_points=end_points)
-
-
-@_deprecated(replace_with=AffineGenerator.__name__)
-def random_affine_generator(
- batch_size: int,
- height: int,
- width: int,
- degrees: torch.Tensor,
- translate: Optional[torch.Tensor] = None,
- scale: Optional[torch.Tensor] = None,
- shear: 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"""Get parameters for ``affine`` for a random affine transform.
-
- Args:
- batch_size (int): the tensor batch size.
- height (int) : height of the image.
- width (int): width of the image.
- degrees (torch.Tensor): Range of degrees to select from like (min, max).
- translate (tensor, optional): 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.
- scale (tensor, optional): scaling factor interval, e.g (a, b), then scale is
- randomly sampled from the range a <= scale <= b. Will keep original scale by default.
- shear (tensor, optional): Range of degrees to select from.
- 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.
- 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.
- - translations (torch.Tensor): element-wise translations with a shape of (B, 2).
- - center (torch.Tensor): element-wise center with a shape of (B, 2).
- - scale (torch.Tensor): element-wise scales with a shape of (B, 2).
- - angle (torch.Tensor): element-wise rotation angles with a shape of (B,).
- - sx (torch.Tensor): element-wise x-axis shears with a shape of (B,).
- - sy (torch.Tensor): element-wise y-axis shears with a shape of (B,).
-
- Note:
- The generated random numbers are not reproducible across different devices and dtypes.
- """
- _common_param_check(batch_size, same_on_batch)
- _joint_range_check(degrees, "degrees")
- 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}.")
-
- _device, _dtype = _extract_device_dtype([degrees, translate, scale, shear])
- degrees = degrees.to(device=device, dtype=dtype)
- angle = _adapted_uniform((batch_size,), degrees[0], degrees[1], same_on_batch)
- angle = angle.to(device=_device, dtype=_dtype)
-
- # compute tensor ranges
- if scale is not None:
- scale = scale.to(device=device, dtype=dtype)
- if not (len(scale.shape) == 1 and len(scale) in (2, 4)):
- raise AssertionError(f"`scale` shall have 2 or 4 elements. Got {scale}.")
- _joint_range_check(cast(torch.Tensor, scale[:2]), "scale")
- _scale = _adapted_uniform((batch_size,), scale[0], scale[1], same_on_batch).unsqueeze(1).repeat(1, 2)
- if len(scale) == 4:
- _joint_range_check(cast(torch.Tensor, scale[2:]), "scale_y")
- _scale[:, 1] = _adapted_uniform((batch_size,), scale[2], scale[3], same_on_batch)
- _scale = _scale.to(device=_device, dtype=_dtype)
- else:
- _scale = torch.ones((batch_size, 2), device=_device, dtype=_dtype)
-
- if translate is not None:
- translate = translate.to(device=device, dtype=dtype)
- if not (0.0 <= translate[0] <= 1.0 and 0.0 <= translate[1] <= 1.0 and translate.shape == torch.Size([2])):
- raise AssertionError(f"Expect translate contains two elements and ranges are in [0, 1]. Got {translate}.")
- max_dx: torch.Tensor = translate[0] * width
- max_dy: torch.Tensor = translate[1] * height
- translations = torch.stack(
- [
- _adapted_uniform((batch_size,), -max_dx, max_dx, same_on_batch),
- _adapted_uniform((batch_size,), -max_dy, max_dy, same_on_batch),
- ],
- dim=-1,
- )
- translations = translations.to(device=_device, dtype=_dtype)
- else:
- translations = torch.zeros((batch_size, 2), device=_device, dtype=_dtype)
-
- center: torch.Tensor = torch.tensor([width, height], device=_device, dtype=_dtype).view(1, 2) / 2.0 - 0.5
- center = center.expand(batch_size, -1)
-
- if shear is not None:
- shear = shear.to(device=device, dtype=dtype)
- _joint_range_check(cast(torch.Tensor, shear)[0], "shear")
- _joint_range_check(cast(torch.Tensor, shear)[1], "shear")
- sx = _adapted_uniform((batch_size,), shear[0][0], shear[0][1], same_on_batch)
- sy = _adapted_uniform((batch_size,), shear[1][0], shear[1][1], same_on_batch)
- sx = sx.to(device=_device, dtype=_dtype)
- sy = sy.to(device=_device, dtype=_dtype)
- else:
- sx = sy = torch.tensor([0] * batch_size, device=_device, dtype=_dtype)
-
- return dict(translations=translations, center=center, scale=_scale, angle=angle, sx=sx, sy=sy)
-
-
-@_deprecated()
-def random_rotation_generator(
- batch_size: int,
- degrees: torch.Tensor,
- same_on_batch: bool = False,
- device: torch.device = torch.device('cpu'),
- dtype: torch.dtype = torch.float32,
-) -> Dict[str, torch.Tensor]:
- r"""Get parameters for ``rotate`` for a random rotate transform.
-
- Args:
- batch_size (int): the tensor batch size.
- degrees (torch.Tensor): range of degrees with shape (2) to select from.
- 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.
- - degrees (torch.Tensor): element-wise rotation degrees with a shape of (B,).
-
- Note:
- The generated random numbers are not reproducible across different devices and dtypes.
- """
- _common_param_check(batch_size, same_on_batch)
- _joint_range_check(degrees, "degrees")
-
- _degrees = _adapted_uniform(
- (batch_size,),
- degrees[0].to(device=device, dtype=dtype),
- degrees[1].to(device=device, dtype=dtype),
- same_on_batch,
- )
- _degrees = _degrees.to(device=degrees.device, dtype=degrees.dtype)
-
- return dict(degrees=_degrees)
-
-
-@_deprecated(replace_with=CropGenerator.__name__)
-def random_crop_generator(
- batch_size: int,
- input_size: Tuple[int, int],
- size: Union[Tuple[int, int], torch.Tensor],
- resize_to: Optional[Tuple[int, int]] = None,
- same_on_batch: bool = False,
- device: torch.device = torch.device('cpu'),
- dtype: torch.dtype = torch.float32,
-) -> Dict[str, torch.Tensor]:
- r"""Get parameters for ```crop``` transformation for crop transform.
-
- Args:
- batch_size (int): the tensor batch size.
- input_size (tuple): Input image shape, like (h, w).
- size (tuple): Desired size of the crop operation, like (h, w).
- If tensor, it must be (B, 2).
- resize_to (tuple): Desired output size of the crop, like (h, w). If None, no resize will be performed.
- 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.
- - src (torch.Tensor): cropping bounding boxes with a shape of (B, 4, 2).
- - dst (torch.Tensor): output bounding boxes with a shape (B, 4, 2).
-
- Note:
- The generated random numbers are not reproducible across different devices and dtypes.
-
- Example:
- >>> _ = torch.manual_seed(0)
- >>> crop_size = torch.tensor([[25, 28], [27, 29], [26, 28]])
- >>> random_crop_generator(3, (30, 30), size=crop_size, same_on_batch=False)
- {'src': tensor([[[ 1., 0.],
- [28., 0.],
- [28., 24.],
- [ 1., 24.]],
- <BLANKLINE>
- [[ 1., 1.],
- [29., 1.],
- [29., 27.],
- [ 1., 27.]],
- <BLANKLINE>
- [[ 0., 3.],
- [27., 3.],
- [27., 28.],
- [ 0., 28.]]]), 'dst': tensor([[[ 0., 0.],
- [27., 0.],
- [27., 24.],
- [ 0., 24.]],
- <BLANKLINE>
- [[ 0., 0.],
- [28., 0.],
- [28., 26.],
- [ 0., 26.]],
- <BLANKLINE>
- [[ 0., 0.],
- [27., 0.],
- [27., 25.],
- [ 0., 25.]]]), 'input_size': tensor([[30, 30],
- [30, 30],
- [30, 30]])}
- """
- _common_param_check(batch_size, same_on_batch)
- _device, _dtype = _extract_device_dtype([size if isinstance(size, torch.Tensor) else None])
- # Use float point instead
- _dtype = _dtype if _dtype in [torch.float16, torch.float32, torch.float64] else dtype
- if not isinstance(size, torch.Tensor):
- size = torch.tensor(size, device=_device, dtype=_dtype).repeat(batch_size, 1)
- else:
- size = size.to(device=_device, dtype=_dtype)
- if size.shape != torch.Size([batch_size, 2]):
- raise AssertionError(
- "If `size` is a tensor, it must be shaped as (B, 2). "
- f"Got {size.shape} while expecting {torch.Size([batch_size, 2])}."
- )
- if not (input_size[0] > 0 and input_size[1] > 0 and (size > 0).all()):
- raise AssertionError(f"Got non-positive input size or size. {input_size}, {size}.")
- size = size.floor()
-
- x_diff = input_size[1] - size[:, 1] + 1
- y_diff = input_size[0] - size[:, 0] + 1
-
- # Start point will be 0 if diff < 0
- x_diff = x_diff.clamp(0)
- y_diff = y_diff.clamp(0)
-
- if batch_size == 0:
- return dict(
- src=torch.zeros([0, 4, 2], device=_device, dtype=_dtype),
- dst=torch.zeros([0, 4, 2], device=_device, dtype=_dtype),
- )
-
- if same_on_batch:
- # If same_on_batch, select the first then repeat.
- x_start = _adapted_uniform((batch_size,), 0, x_diff[0].to(device=device, dtype=dtype), same_on_batch).floor()
- y_start = _adapted_uniform((batch_size,), 0, y_diff[0].to(device=device, dtype=dtype), same_on_batch).floor()
- else:
- x_start = _adapted_uniform((1,), 0, x_diff.to(device=device, dtype=dtype), same_on_batch).floor()
- y_start = _adapted_uniform((1,), 0, y_diff.to(device=device, dtype=dtype), same_on_batch).floor()
- crop_src = bbox_generator(
- x_start.view(-1).to(device=_device, dtype=_dtype),
- y_start.view(-1).to(device=_device, dtype=_dtype),
- torch.where(size[:, 1] == 0, torch.tensor(input_size[1], device=_device, dtype=_dtype), size[:, 1]),
- torch.where(size[:, 0] == 0, torch.tensor(input_size[0], device=_device, dtype=_dtype), size[:, 0]),
- )
-
- if resize_to is None:
- crop_dst = bbox_generator(
- torch.tensor([0] * batch_size, device=_device, dtype=_dtype),
- torch.tensor([0] * batch_size, device=_device, dtype=_dtype),
- size[:, 1],
- size[:, 0],
- )
- else:
- if not (
- len(resize_to) == 2
- and isinstance(resize_to[0], (int,))
- and isinstance(resize_to[1], (int,))
- and resize_to[0] > 0
- and resize_to[1] > 0
- ):
- raise AssertionError(f"`resize_to` must be a tuple of 2 positive integers. Got {resize_to}.")
- crop_dst = torch.tensor(
- [[[0, 0], [resize_to[1] - 1, 0], [resize_to[1] - 1, resize_to[0] - 1], [0, resize_to[0] - 1]]],
- device=_device,
- dtype=_dtype,
- ).repeat(batch_size, 1, 1)
-
- _input_size = torch.tensor(input_size, device=_device, dtype=torch.long).expand(batch_size, -1)
-
- return dict(src=crop_src, dst=crop_dst, input_size=_input_size)
-
-
-@_deprecated()
-def random_crop_size_generator(
- batch_size: int,
- size: Tuple[int, int],
- scale: torch.Tensor,
- ratio: torch.Tensor,
- same_on_batch: bool = False,
- device: torch.device = torch.device('cpu'),
- dtype: torch.dtype = torch.float32,
-) -> Dict[str, torch.Tensor]:
- r"""Get cropping heights and widths for ```crop``` transformation for resized crop transform.
-
- Args:
- batch_size (int): the tensor batch size.
- size (Tuple[int, int]): expected output size of each edge.
- scale (torch.Tensor): range of size of the origin size cropped with (2,) shape.
- ratio (torch.Tensor): range of aspect ratio of the origin aspect ratio cropped with (2,) shape.
- 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.
- - size (torch.Tensor): element-wise cropping sizes with a shape of (B, 2).
-
- Note:
- The generated random numbers are not reproducible across different devices and dtypes.
-
- Examples:
- >>> _ = torch.manual_seed(42)
- >>> random_crop_size_generator(3, (30, 30), scale=torch.tensor([.7, 1.3]), ratio=torch.tensor([.9, 1.]))
- {'size': tensor([[29., 29.],
- [27., 28.],
- [26., 29.]])}
- """
- _common_param_check(batch_size, same_on_batch)
- _joint_range_check(scale, "scale")
- _joint_range_check(ratio, "ratio")
- if not (len(size) == 2 and type(size[0]) is int and size[1] > 0 and type(size[1]) is int and size[1] > 0):
- raise AssertionError(f"'height' and 'width' must be integers. Got {size}.")
-
- _device, _dtype = _extract_device_dtype([scale, ratio])
-
- if batch_size == 0:
- return dict(size=torch.zeros([0, 2], device=_device, dtype=_dtype))
-
- scale = scale.to(device=device, dtype=dtype)
- ratio = ratio.to(device=device, dtype=dtype)
- # 10 trails for each element
- area = _adapted_uniform((batch_size, 10), scale[0] * size[0] * size[1], scale[1] * size[0] * size[1], same_on_batch)
- log_ratio = _adapted_uniform((batch_size, 10), torch.log(ratio[0]), torch.log(ratio[1]), same_on_batch)
- aspect_ratio = torch.exp(log_ratio)
-
- w = torch.sqrt(area * aspect_ratio).round().floor()
- h = torch.sqrt(area / aspect_ratio).round().floor()
- # Element-wise w, h condition
- cond = ((0 < w) * (w < size[0]) * (0 < h) * (h < size[1])).int()
-
- # torch.argmax is not reproducible across devices: https://github.com/pytorch/pytorch/issues/17738
- # Here, we will select the first occurrence of the duplicated elements.
- cond_bool, argmax_dim1 = ((cond.cumsum(1) == 1) & cond.bool()).max(1)
- h_out = w[torch.arange(0, batch_size, device=device, dtype=torch.long), argmax_dim1]
- w_out = h[torch.arange(0, batch_size, device=device, dtype=torch.long), argmax_dim1]
-
- if not cond_bool.all():
- # Fallback to center crop
- in_ratio = float(size[0]) / float(size[1])
- if in_ratio < ratio.min():
- h_ct = torch.tensor(size[0], device=device, dtype=dtype)
- w_ct = torch.round(h_ct / ratio.min())
- elif in_ratio > ratio.min():
- w_ct = torch.tensor(size[1], device=device, dtype=dtype)
- h_ct = torch.round(w_ct * ratio.min())
- else: # whole image
- h_ct = torch.tensor(size[0], device=device, dtype=dtype)
- w_ct = torch.tensor(size[1], device=device, dtype=dtype)
- h_ct = h_ct.floor()
- w_ct = w_ct.floor()
-
- h_out = h_out.where(cond_bool, h_ct)
- w_out = w_out.where(cond_bool, w_ct)
-
- return dict(size=torch.stack([h_out, w_out], dim=1).to(device=_device, dtype=_dtype))
-
-
-@_deprecated(replace_with=RectangleEraseGenerator.__name__)
-def random_rectangles_params_generator(
- batch_size: int,
- height: int,
- width: int,
- scale: torch.Tensor,
- ratio: torch.Tensor,
- value: float = 0.0,
- same_on_batch: bool = False,
- device: torch.device = torch.device('cpu'),
- dtype: torch.dtype = torch.float32,
-) -> Dict[str, torch.Tensor]:
- r"""Get parameters for ```erasing``` transformation for erasing transform.
-
- Args:
- batch_size (int): the tensor batch size.
- height (int) : height of the image.
- width (int): width of the image.
- scale (torch.Tensor): range of size of the origin size cropped. Shape (2).
- ratio (torch.Tensor): range of aspect ratio of the origin aspect ratio cropped. Shape (2).
- value (float): value to be filled in the erased area.
- 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.
- - widths (torch.Tensor): element-wise erasing widths with a shape of (B,).
- - heights (torch.Tensor): element-wise erasing heights with a shape of (B,).
- - xs (torch.Tensor): element-wise erasing x coordinates with a shape of (B,).
- - ys (torch.Tensor): element-wise erasing y coordinates with a shape of (B,).
- - values (torch.Tensor): element-wise filling values with a shape of (B,).
-
- Note:
- The generated random numbers are not reproducible across different devices and dtypes.
- """
- _common_param_check(batch_size, same_on_batch)
- _device, _dtype = _extract_device_dtype([ratio, scale])
- 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}.")
- if not (isinstance(value, (int, float)) and value >= 0 and value <= 1):
- raise AssertionError(f"'value' must be a number between 0 - 1. Got {value}.")
- _joint_range_check(scale, 'scale', bounds=(0, float('inf')))
- _joint_range_check(ratio, 'ratio', bounds=(0, float('inf')))
-
- images_area = height * width
- target_areas = (
- _adapted_uniform(
- (batch_size,),
- scale[0].to(device=device, dtype=dtype),
- scale[1].to(device=device, dtype=dtype),
- same_on_batch,
- )
- * images_area
- )
-
- if ratio[0] < 1.0 and ratio[1] > 1.0:
- aspect_ratios1 = _adapted_uniform((batch_size,), ratio[0].to(device=device, dtype=dtype), 1, same_on_batch)
- aspect_ratios2 = _adapted_uniform((batch_size,), 1, ratio[1].to(device=device, dtype=dtype), same_on_batch)
- if same_on_batch:
- rand_idxs = (
- torch.round(
- _adapted_uniform(
- (1,),
- torch.tensor(0, device=device, dtype=dtype),
- torch.tensor(1, device=device, dtype=dtype),
- same_on_batch,
- )
- )
- .repeat(batch_size)
- .bool()
- )
- else:
- rand_idxs = torch.round(
- _adapted_uniform(
- (batch_size,),
- torch.tensor(0, device=device, dtype=dtype),
- torch.tensor(1, device=device, dtype=dtype),
- same_on_batch,
- )
- ).bool()
- aspect_ratios = torch.where(rand_idxs, aspect_ratios1, aspect_ratios2)
- else:
- aspect_ratios = _adapted_uniform(
- (batch_size,),
- ratio[0].to(device=device, dtype=dtype),
- ratio[1].to(device=device, dtype=dtype),
- same_on_batch,
- )
-
- # based on target areas and aspect ratios, rectangle params are computed
- heights = torch.min(
- torch.max(
- torch.round((target_areas * aspect_ratios) ** (1 / 2)), torch.tensor(1.0, device=device, dtype=dtype)
- ),
- torch.tensor(height, device=device, dtype=dtype),
- )
-
- widths = torch.min(
- torch.max(
- torch.round((target_areas / aspect_ratios) ** (1 / 2)), torch.tensor(1.0, device=device, dtype=dtype)
- ),
- torch.tensor(width, device=device, dtype=dtype),
- )
-
- xs_ratio = _adapted_uniform(
- (batch_size,),
- torch.tensor(0, device=device, dtype=dtype),
- torch.tensor(1, device=device, dtype=dtype),
- same_on_batch,
- )
- ys_ratio = _adapted_uniform(
- (batch_size,),
- torch.tensor(0, device=device, dtype=dtype),
- torch.tensor(1, device=device, dtype=dtype),
- same_on_batch,
- )
-
- xs = xs_ratio * (torch.tensor(width, device=device, dtype=dtype) - widths + 1)
- ys = ys_ratio * (torch.tensor(height, device=device, dtype=dtype) - heights + 1)
-
- return dict(
- widths=widths.floor().to(device=_device, dtype=_dtype),
- heights=heights.floor().to(device=_device, dtype=_dtype),
- xs=xs.floor().to(device=_device, dtype=_dtype),
- ys=ys.floor().to(device=_device, dtype=_dtype),
- values=torch.tensor([value] * batch_size, device=_device, dtype=_dtype),
- )
-
-
-def center_crop_generator(
- batch_size: int, height: int, width: int, size: Tuple[int, int], device: torch.device = torch.device('cpu')
-) -> Dict[str, torch.Tensor]:
- r"""Get parameters for ```center_crop``` transformation for center crop transform.
-
- Args:
- batch_size (int): the tensor batch size.
- height (int) : height of the image.
- width (int): width of the image.
- size (tuple): Desired output size of the crop, like (h, w).
- device (torch.device): the device on which the random numbers will be generated. Default: cpu.
-
- Returns:
- params Dict[str, torch.Tensor]: parameters to be passed for transformation.
- - src (torch.Tensor): cropping bounding boxes with a shape of (B, 4, 2).
- - dst (torch.Tensor): output bounding boxes with a shape (B, 4, 2).
-
- Note:
- No random number will be generated.
- """
- _common_param_check(batch_size)
- if not isinstance(size, (tuple, list)) and len(size) == 2:
- raise ValueError(f"Input size must be a tuple/list of length 2. Got {size}")
- 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}.")
- if not (height >= size[0] and width >= size[1]):
- raise AssertionError(f"Crop size must be smaller than input size. Got ({height}, {width}) and {size}.")
-
- # unpack input sizes
- dst_h, dst_w = size
- src_h, src_w = height, width
-
- # compute start/end offsets
- dst_h_half = dst_h / 2
- dst_w_half = dst_w / 2
- src_h_half = src_h / 2
- src_w_half = src_w / 2
-
- start_x = int(src_w_half - dst_w_half)
- start_y = int(src_h_half - dst_h_half)
-
- end_x = start_x + dst_w - 1
- end_y = start_y + dst_h - 1
-
- # [y, x] origin
- # top-left, top-right, bottom-right, bottom-left
- points_src: torch.Tensor = torch.tensor(
- [[[start_x, start_y], [end_x, start_y], [end_x, end_y], [start_x, end_y]]], device=device, dtype=torch.long
- ).expand(batch_size, -1, -1)
-
- # [y, x] destination
- # top-left, top-right, bottom-right, bottom-left
- points_dst: torch.Tensor = torch.tensor(
- [[[0, 0], [dst_w - 1, 0], [dst_w - 1, dst_h - 1], [0, dst_h - 1]]], device=device, dtype=torch.long
- ).expand(batch_size, -1, -1)
-
- _input_size = torch.tensor((height, width), device=device, dtype=torch.long).expand(batch_size, -1)
-
- return dict(src=points_src, dst=points_dst, input_size=_input_size)
-
-
-@_deprecated(replace_with=MotionBlurGenerator.__name__)
-def random_motion_blur_generator(
- batch_size: int,
- kernel_size: Union[int, Tuple[int, int]],
- angle: torch.Tensor,
- direction: torch.Tensor,
- same_on_batch: bool = False,
- device: torch.device = torch.device('cpu'),
- dtype: torch.dtype = torch.float32,
-) -> Dict[str, torch.Tensor]:
- r"""Get parameters for motion blur.
-
- Args:
- batch_size (int): the tensor batch size.
- kernel_size (int or (int, int)): motion kernel size (odd and positive) or range.
- angle (torch.Tensor): angle of the motion blur in degrees (anti-clockwise rotation).
- direction (torch.Tensor): forward/backward direction of the motion blur.
- Lower values towards -1.0 will point the motion blur towards the back (with
- angle provided via angle), while higher values towards 1.0 will point the motion
- blur forward. A value of 0.0 leads to a uniformly (but still angled) motion blur.
- 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.
- - ksize_factor (torch.Tensor): element-wise kernel size factors with a shape of (B,).
- - angle_factor (torch.Tensor): element-wise angle factors with a shape of (B,).
- - direction_factor (torch.Tensor): element-wise direction factors with a shape of (B,).
-
- Note:
- The generated random numbers are not reproducible across different devices and dtypes.
- """
- _common_param_check(batch_size, same_on_batch)
- _joint_range_check(angle, 'angle')
- _joint_range_check(direction, 'direction', (-1, 1))
-
- _device, _dtype = _extract_device_dtype([angle, direction])
-
- if isinstance(kernel_size, int):
- if not (kernel_size >= 3 and kernel_size % 2 == 1):
- raise AssertionError(f"`kernel_size` must be odd and greater than 3. Got {kernel_size}.")
- ksize_factor = torch.tensor([kernel_size] * batch_size, device=device, dtype=dtype)
- elif isinstance(kernel_size, tuple):
- # kernel_size is fixed across the batch
- if len(kernel_size) != 2:
- raise AssertionError(f"`kernel_size` must be (2,) if it is a tuple. Got {kernel_size}.")
- ksize_factor = (
- _adapted_uniform((batch_size,), kernel_size[0] // 2, kernel_size[1] // 2, same_on_batch=True).int() * 2 + 1
- )
- else:
- raise TypeError(f"Unsupported type: {type(kernel_size)}")
-
- angle_factor = _adapted_uniform(
- (batch_size,), angle[0].to(device=device, dtype=dtype), angle[1].to(device=device, dtype=dtype), same_on_batch
- )
-
- direction_factor = _adapted_uniform(
- (batch_size,),
- direction[0].to(device=device, dtype=dtype),
- direction[1].to(device=device, dtype=dtype),
- same_on_batch,
- )
-
- return dict(
- ksize_factor=ksize_factor.to(device=_device, dtype=torch.int32),
- angle_factor=angle_factor.to(device=_device, dtype=_dtype),
- direction_factor=direction_factor.to(device=_device, dtype=_dtype),
- )
-
-
-@_deprecated()
-def random_solarize_generator(
- batch_size: int,
- thresholds: torch.Tensor = torch.tensor([0.4, 0.6]),
- additions: torch.Tensor = torch.tensor([-0.1, 0.1]),
- same_on_batch: bool = False,
- device: torch.device = torch.device('cpu'),
- dtype: torch.dtype = torch.float32,
-) -> Dict[str, torch.Tensor]:
- r"""Generate random solarize parameters for a batch of images.
-
- For each pixel in the image less than threshold, we add 'addition' amount to it and then clip the pixel value
- to be between 0 and 1.0
-
- Args:
- batch_size (int): the number of images.
- thresholds (torch.Tensor): Pixels less than threshold will selected. Otherwise, subtract 1.0 from the pixel.
- Takes in a range tensor of (0, 1). Default value will be sampled from [0.4, 0.6].
- additions (torch.Tensor): The value is between -0.5 and 0.5. Default value will be sampled from [-0.1, 0.1]
- 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.
- - thresholds_factor (torch.Tensor): element-wise thresholds factors with a shape of (B,).
- - additions_factor (torch.Tensor): element-wise additions factors with a shape of (B,).
-
- Note:
- The generated random numbers are not reproducible across different devices and dtypes.
- """
- _common_param_check(batch_size, same_on_batch)
- _joint_range_check(thresholds, 'thresholds', (0, 1))
- _joint_range_check(additions, 'additions', (-0.5, 0.5))
-
- _device, _dtype = _extract_device_dtype([thresholds, additions])
-
- thresholds_factor = _adapted_uniform(
- (batch_size,),
- thresholds[0].to(device=device, dtype=dtype),
- thresholds[1].to(device=device, dtype=dtype),
- same_on_batch,
- )
-
- additions_factor = _adapted_uniform(
- (batch_size,),
- additions[0].to(device=device, dtype=dtype),
- additions[1].to(device=device, dtype=dtype),
- same_on_batch,
- )
-
- return dict(
- thresholds_factor=thresholds_factor.to(device=_device, dtype=_dtype),
- additions_factor=additions_factor.to(device=_device, dtype=_dtype),
- )
-
-
-@_deprecated()
-def random_posterize_generator(
- batch_size: int,
- bits: torch.Tensor = torch.tensor([3, 5]),
- same_on_batch: bool = False,
- device: torch.device = torch.device('cpu'),
- dtype: torch.dtype = torch.float32,
-) -> Dict[str, torch.Tensor]:
- r"""Generate random posterize parameters for a batch of images.
-
- Args:
- batch_size (int): the number of images.
- bits (int or tuple): Takes in an integer tuple tensor that ranged from 0 ~ 8. Default value is [3, 5].
- 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.
- - bits_factor (torch.Tensor): element-wise bit factors with a shape of (B,).
-
- Note:
- The generated random numbers are not reproducible across different devices and dtypes.
- """
- _common_param_check(batch_size, same_on_batch)
- _joint_range_check(bits, 'bits', (0, 8))
- bits_factor = _adapted_uniform(
- (batch_size,), bits[0].to(device=device, dtype=dtype), bits[1].to(device=device, dtype=dtype), same_on_batch
- ).int()
-
- return dict(bits_factor=bits_factor.to(device=bits.device, dtype=torch.int32))
-
-
-@_deprecated()
-def random_sharpness_generator(
- batch_size: int,
- sharpness: torch.Tensor = torch.tensor([0, 1.0]),
- same_on_batch: bool = False,
- device: torch.device = torch.device('cpu'),
- dtype: torch.dtype = torch.float32,
-) -> Dict[str, torch.Tensor]:
- r"""Generate random sharpness parameters for a batch of images.
-
- Args:
- batch_size (int): the number of images.
- sharpness (torch.Tensor): Must be above 0. Default value is sampled from (0, 1).
- 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.
- - sharpness_factor (torch.Tensor): element-wise sharpness factors with a shape of (B,).
-
- Note:
- The generated random numbers are not reproducible across different devices and dtypes.
- """
- _common_param_check(batch_size, same_on_batch)
- _joint_range_check(sharpness, 'sharpness', bounds=(0, float('inf')))
-
- sharpness_factor = _adapted_uniform(
- (batch_size,),
- sharpness[0].to(device=device, dtype=dtype),
- sharpness[1].to(device=device, dtype=dtype),
- same_on_batch,
- )
-
- return dict(sharpness_factor=sharpness_factor.to(device=sharpness.device, dtype=sharpness.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),
- )
-
-
-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),
- )
-
- 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/random_generator3d.py b/kornia/augmentation/random_generator/random_generator3d.py
deleted file mode 100644
index 746eda56d..000000000
--- a/kornia/augmentation/random_generator/random_generator3d.py
+++ /dev/null
@@ -1,1123 +0,0 @@
-from typing import Dict, Optional, Tuple, Union
-
-import torch
-from torch.distributions import Uniform
-
-from kornia.geometry.bbox import bbox_generator3d
-from kornia.utils.helpers import _deprecated, _extract_device_dtype
-
-from ..utils import (
- _adapted_rsampling,
- _adapted_uniform,
- _common_param_check,
- _joint_range_check,
- _range_bound,
- _singular_range_check,
- _tuple_range_reader,
-)
-from .random_generator import RandomGeneratorBase
-
-
-class AffineGenerator3D(RandomGeneratorBase):
- r"""Get parameters for ```3d affine``` transformation random affine transform.
-
- Args:
- degrees: Range of yaw (x-axis), pitch (y-axis), roll (z-axis) to select from.
- If degrees is a number, then yaw, pitch, roll will be generated from the range of (-degrees, +degrees).
- If degrees is a tuple of (min, max), then yaw, pitch, roll will be generated from the range of (min, max).
- If degrees is a list of floats [a, b, c], then yaw, pitch, roll will be generated from (-a, a), (-b, b)
- and (-c, c).
- If degrees is a list of tuple ((a, b), (m, n), (x, y)), then yaw, pitch, roll will be generated from
- (a, b), (m, n) and (x, y).
- Set to 0 to deactivate rotations.
- translate: tuple of maximum absolute fraction for horizontal, vertical and
- depthical translations (dx,dy,dz). For example translate=(a, b, c), then
- horizontal shift will be randomly sampled in the range -img_width * a < dx < img_width * a
- vertical shift will be randomly sampled in the range -img_height * b < dy < img_height * b.
- depthical shift will be randomly sampled in the range -img_depth * c < dz < img_depth * c.
- Will not translate by default.
- scale: scaling factor interval.
- If (a, b) represents isotropic scaling, the scale is randomly sampled from the range a <= scale <= b.
- If ((a, b), (c, d), (e, f)), the scale is randomly sampled from the range a <= scale_x <= b,
- c <= scale_y <= d, e <= scale_z <= f. Will keep original scale by default.
- shears: Range of degrees to select from.
- If shear is a number, a shear to the 6 facets in the range (-shear, +shear) will be applied.
- If shear is a tuple of 2 values, a shear to the 6 facets in the range (shear[0], shear[1]) will be applied.
- If shear is a tuple of 6 values, a shear to the i-th facet in the range (-shear[i], shear[i])
- will be applied.
- If shear is a tuple of 6 tuples, a shear to the i-th facet in the range (-shear[i, 0], shear[i, 1])
- will be applied.
-
- Returns:
- A dict of parameters to be passed for transformation.
- - translations (torch.Tensor): element-wise translations with a shape of (B, 3).
- - center (torch.Tensor): element-wise center with a shape of (B, 3).
- - scale (torch.Tensor): element-wise scales with a shape of (B, 3).
- - angle (torch.Tensor): element-wise rotation angles with a shape of (B, 3).
- - sxy (torch.Tensor): element-wise x-y-facet shears with a shape of (B,).
- - sxz (torch.Tensor): element-wise x-z-facet shears with a shape of (B,).
- - syx (torch.Tensor): element-wise y-x-facet shears with a shape of (B,).
- - syz (torch.Tensor): element-wise y-z-facet shears with a shape of (B,).
- - szx (torch.Tensor): element-wise z-x-facet shears with a shape of (B,).
- - szy (torch.Tensor): element-wise z-y-facet 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,
- degrees: Union[
- torch.Tensor,
- float,
- Tuple[float, float],
- Tuple[float, float, float],
- Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float]],
- ],
- translate: Optional[Union[torch.Tensor, Tuple[float, float, float]]] = None,
- scale: Optional[
- Union[
- torch.Tensor, Tuple[float, float], Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float]]
- ]
- ] = None,
- shears: Union[
- torch.Tensor,
- float,
- Tuple[float, float],
- Tuple[float, float, float, float, float, float],
- Tuple[
- Tuple[float, float],
- Tuple[float, float],
- Tuple[float, float],
- Tuple[float, float],
- Tuple[float, float],
- Tuple[float, float],
- ],
- ] = None,
- ) -> None:
- super().__init__()
- self.degrees = degrees
- self.shears = shears
- self.translate = translate
- self.scale = scale
-
- def __repr__(self) -> str:
- repr = f"degrees={self.degrees}, shears={self.shears}, translate={self.translate}, scale={self.scale}"
- return repr
-
- def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
- degrees = _tuple_range_reader(self.degrees, 3, device, dtype)
- shear: Optional[torch.Tensor] = None
- if self.shears is not None:
- shear = _tuple_range_reader(self.shears, 6, device, dtype)
- self.sxy_sampler = Uniform(shear[0, 0], shear[0, 1], validate_args=False)
- self.sxz_sampler = Uniform(shear[1, 0], shear[1, 1], validate_args=False)
- self.syx_sampler = Uniform(shear[2, 0], shear[2, 1], validate_args=False)
- self.syz_sampler = Uniform(shear[3, 0], shear[3, 1], validate_args=False)
- self.szx_sampler = Uniform(shear[4, 0], shear[4, 1], validate_args=False)
- self.szy_sampler = Uniform(shear[5, 0], shear[5, 1], validate_args=False)
-
- # check translation range
- self._translate: Optional[torch.Tensor] = None
- if self.translate is not None:
- self._translate = torch.as_tensor(self.translate, device=device, dtype=dtype)
- _singular_range_check(self._translate, 'translate', bounds=(0, 1), mode='3d')
-
- # check scale range
- self._scale: Optional[torch.Tensor] = None
- if self.scale is not None:
- _scale = torch.as_tensor(self.scale, device=device, dtype=dtype)
- if _scale.shape == torch.Size([2]):
- self._scale = _scale.unsqueeze(0).repeat(3, 1)
- elif _scale.shape != torch.Size([3, 2]):
- raise ValueError(f"'scale' shall be either shape (2) or (3, 2). Got {self.scale}.")
- else:
- self._scale = _scale
- _singular_range_check(self._scale[0], 'scale-x', bounds=(0, float('inf')), mode='2d')
- _singular_range_check(self._scale[1], 'scale-y', bounds=(0, float('inf')), mode='2d')
- _singular_range_check(self._scale[2], 'scale-z', bounds=(0, float('inf')), mode='2d')
- self.scale_1_sampler = Uniform(self._scale[0, 0], self._scale[0, 1], validate_args=False)
- self.scale_2_sampler = Uniform(self._scale[1, 0], self._scale[1, 1], validate_args=False)
- self.scale_3_sampler = Uniform(self._scale[2, 0], self._scale[2, 1], validate_args=False)
-
- self.yaw_sampler = Uniform(degrees[0][0], degrees[0][1], validate_args=False)
- self.pitch_sampler = Uniform(degrees[1][0], degrees[1][1], validate_args=False)
- self.roll_sampler = Uniform(degrees[2][0], degrees[2][1], validate_args=False)
-
- self.uniform_sampler = Uniform(
- torch.tensor(0, device=device, dtype=dtype),
- torch.tensor(1, device=device, dtype=dtype),
- validate_args=False
- )
-
- def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, torch.Tensor]:
- batch_size = batch_shape[0]
- depth = batch_shape[-3]
- height = batch_shape[-2]
- width = batch_shape[-1]
-
- if not (
- type(depth) is int and depth > 0 and type(height) is int and height > 0 and type(width) is int and width > 0
- ):
- raise AssertionError(f"'depth', 'height' and 'width' must be integers. Got {depth}, {height}, {width}.")
-
- _device, _dtype = _extract_device_dtype([self.degrees, self.translate, self.scale, self.shears])
-
- # degrees = degrees.to(device=device, dtype=dtype)
- yaw = _adapted_rsampling((batch_size,), self.yaw_sampler, same_on_batch)
- pitch = _adapted_rsampling((batch_size,), self.pitch_sampler, same_on_batch)
- roll = _adapted_rsampling((batch_size,), self.roll_sampler, same_on_batch)
- angles = torch.stack([yaw, pitch, roll], dim=1)
-
- # compute tensor ranges
- if self._scale is not None:
- scale = torch.stack(
- [
- _adapted_rsampling((batch_size,), self.scale_1_sampler, same_on_batch),
- _adapted_rsampling((batch_size,), self.scale_2_sampler, same_on_batch),
- _adapted_rsampling((batch_size,), self.scale_3_sampler, same_on_batch),
- ],
- dim=1,
- )
- else:
- scale = torch.ones(batch_size, device=_device, dtype=_dtype).reshape(batch_size, 1).repeat(1, 3)
-
- if self._translate is not None:
- max_dx: torch.Tensor = self._translate[0] * width
- max_dy: torch.Tensor = self._translate[1] * height
- max_dz: torch.Tensor = self._translate[2] * depth
- # translations should be in x,y,z
- translations = torch.stack(
- [
- (_adapted_rsampling((batch_size,), self.yaw_sampler, same_on_batch) - 0.5) * max_dx * 2,
- (_adapted_rsampling((batch_size,), self.pitch_sampler, same_on_batch) - 0.5) * max_dy * 2,
- (_adapted_rsampling((batch_size,), self.roll_sampler, same_on_batch) - 0.5) * max_dz * 2,
- ],
- dim=1,
- )
- else:
- translations = torch.zeros((batch_size, 3), device=_device, dtype=_dtype)
-
- # center should be in x,y,z
- center: torch.Tensor = torch.tensor([width, height, depth], device=_device, dtype=_dtype).view(1, 3) / 2.0 - 0.5
- center = center.expand(batch_size, -1)
-
- if self.shears is not None:
- sxy = _adapted_rsampling((batch_size,), self.sxy_sampler, same_on_batch)
- sxz = _adapted_rsampling((batch_size,), self.sxz_sampler, same_on_batch)
- syx = _adapted_rsampling((batch_size,), self.syx_sampler, same_on_batch)
- syz = _adapted_rsampling((batch_size,), self.syz_sampler, same_on_batch)
- szx = _adapted_rsampling((batch_size,), self.szx_sampler, same_on_batch)
- szy = _adapted_rsampling((batch_size,), self.szy_sampler, same_on_batch)
- else:
- sxy = sxz = syx = syz = szx = szy = torch.tensor([0] * batch_size, device=_device, dtype=_dtype)
-
- return dict(
- translations=torch.as_tensor(translations, device=_device, dtype=_dtype),
- center=torch.as_tensor(center, device=_device, dtype=_dtype),
- scale=torch.as_tensor(scale, device=_device, dtype=_dtype),
- angles=torch.as_tensor(angles, device=_device, dtype=_dtype),
- sxy=torch.as_tensor(sxy, device=_device, dtype=_dtype),
- sxz=torch.as_tensor(sxz, device=_device, dtype=_dtype),
- syx=torch.as_tensor(syx, device=_device, dtype=_dtype),
- syz=torch.as_tensor(syz, device=_device, dtype=_dtype),
- szx=torch.as_tensor(szx, device=_device, dtype=_dtype),
- szy=torch.as_tensor(szy, device=_device, dtype=_dtype),
- )
-
-
-class CropGenerator3D(RandomGeneratorBase):
- r"""Get parameters for ```crop``` transformation for crop transform.
-
- Args:
- size (tuple): Desired size of the crop operation, like (d, h, w).
- If tensor, it must be (B, 3).
- resize_to (tuple): Desired output size of the crop, like (d, h, w). If None, no resize will be performed.
-
- Returns:
- A dict of parameters to be passed for transformation.
- - src (torch.Tensor): cropping bounding boxes with a shape of (B, 8, 3).
- - dst (torch.Tensor): output bounding boxes with a shape (B, 8, 3).
-
- 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,
- size: Union[Tuple[int, int, int], torch.Tensor],
- resize_to: Optional[Tuple[int, int, int]] = None
- ) -> None:
- super().__init__()
- self.size = size
- self.resize_to = resize_to
-
- def __repr__(self) -> str:
- repr = f"crop_size={self.size}"
- if self.resize_to is not None:
- repr += f", resize_to={self.resize_to}"
- return repr
-
- def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
- self.rand_sampler = Uniform(
- torch.tensor(0., device=device, dtype=dtype), torch.tensor(1., device=device, dtype=dtype))
-
- def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, torch.Tensor]: # type:ignore
- batch_size, _, depth, height, width = batch_shape
- _common_param_check(batch_size, same_on_batch)
- _device, _dtype = _extract_device_dtype([self.size if isinstance(self.size, torch.Tensor) else None])
-
- if not isinstance(self.size, torch.Tensor):
- size = torch.tensor(self.size, device=_device, dtype=_dtype).repeat(batch_size, 1)
- else:
- size = self.size.to(device=_device, dtype=_dtype)
- if size.shape != torch.Size([batch_size, 3]):
- raise AssertionError(
- "If `size` is a tensor, it must be shaped as (B, 3). "
- f"Got {size.shape} while expecting {torch.Size([batch_size, 3])}."
- )
- if not (
- isinstance(depth, (int,)) and isinstance(height, (int,)) and isinstance(width, (int,))
- and depth > 0 and height > 0 and width > 0
- ):
- raise AssertionError(f"`batch_shape` should not contain negative values. Got {(batch_shape)}.")
-
- x_diff = width - size[:, 2] + 1
- y_diff = height - size[:, 1] + 1
- z_diff = depth - size[:, 0] + 1
-
- if (x_diff < 0).any() or (y_diff < 0).any() or (z_diff < 0).any():
- raise ValueError(
- f"input_size {(depth, height, width)} cannot be smaller than crop size {str(size)} in any dimension.")
-
- if batch_size == 0:
- return dict(
- src=torch.zeros([0, 8, 3], device=_device, dtype=_dtype),
- dst=torch.zeros([0, 8, 3], device=_device, dtype=_dtype),
- )
-
- x_start = _adapted_rsampling((batch_size,), self.rand_sampler, same_on_batch).to(device=_device, dtype=_dtype)
- y_start = _adapted_rsampling((batch_size,), self.rand_sampler, same_on_batch).to(device=_device, dtype=_dtype)
- z_start = _adapted_rsampling((batch_size,), self.rand_sampler, same_on_batch).to(device=_device, dtype=_dtype)
-
- x_start = (x_start * x_diff).floor()
- y_start = (y_start * y_diff).floor()
- z_start = (z_start * z_diff).floor()
-
- crop_src = bbox_generator3d(
- x_start.view(-1),
- y_start.view(-1),
- z_start.view(-1),
- size[:, 2] - 1,
- size[:, 1] - 1,
- size[:, 0] - 1,
- )
-
- if self.resize_to is None:
- crop_dst = bbox_generator3d(
- torch.tensor([0] * batch_size, device=_device, dtype=_dtype),
- torch.tensor([0] * batch_size, device=_device, dtype=_dtype),
- torch.tensor([0] * batch_size, device=_device, dtype=_dtype),
- size[:, 2] - 1,
- size[:, 1] - 1,
- size[:, 0] - 1,
- )
- else:
- if not (
- len(self.resize_to) == 3
- and isinstance(self.resize_to[0], (int,))
- and isinstance(self.resize_to[1], (int,))
- and isinstance(self.resize_to[2], (int,))
- and self.resize_to[0] > 0
- and self.resize_to[1] > 0
- and self.resize_to[2] > 0
- ):
- raise AssertionError(f"`resize_to` must be a tuple of 3 positive integers. Got {self.resize_to}.")
- crop_dst = torch.tensor(
- [
- [
- [0, 0, 0],
- [self.resize_to[-1] - 1, 0, 0],
- [self.resize_to[-1] - 1, self.resize_to[-2] - 1, 0],
- [0, self.resize_to[-2] - 1, 0],
- [0, 0, self.resize_to[-3] - 1],
- [self.resize_to[-1] - 1, 0, self.resize_to[-3] - 1],
- [self.resize_to[-1] - 1, self.resize_to[-2] - 1, self.resize_to[-3] - 1],
- [0, self.resize_to[-2] - 1, self.resize_to[-3] - 1],
- ]
- ],
- device=_device,
- dtype=_dtype,
- ).repeat(batch_size, 1, 1)
-
- return dict(src=crop_src.to(device=_device), dst=crop_dst.to(device=_device))
-
-
-class RotationGenerator3D(RandomGeneratorBase):
- r"""Get parameters for ``rotate`` for a random 3D rotate transform.
-
- Args:
- degrees: Range of yaw (x-axis), pitch (y-axis), roll (z-axis) to select from.
- If degrees is a number, then yaw, pitch, roll will be generated from the range of (-degrees, +degrees).
- If degrees is a tuple of (min, max), then yaw, pitch, roll will be generated from the range of (min, max).
- If degrees is a list of floats [a, b, c], then yaw, pitch, roll will be generated from (-a, a), (-b, b)
- and (-c, c).
- If degrees is a list of tuple ((a, b), (m, n), (x, y)), then yaw, pitch, roll will be generated from
- (a, b), (m, n) and (x, y).
- Set to 0 to deactivate rotations.
-
- Returns:
- A dict of parameters to be passed for transformation.
- - yaw (torch.Tensor): element-wise rotation yaws with a shape of (B,).
- - pitch (torch.Tensor): element-wise rotation pitches with a shape of (B,).
- - roll (torch.Tensor): element-wise rotation rolls 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,
- degrees: Union[
- torch.Tensor,
- float,
- Tuple[float, float, float],
- Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float]],
- ]
- ) -> None:
- super().__init__()
- self.degrees = degrees
-
- def __repr__(self) -> str:
- repr = f"degrees={self.degrees}"
- return repr
-
- def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
- degrees = _tuple_range_reader(self.degrees, 3, device, dtype)
- self.yaw_sampler = Uniform(degrees[0][0], degrees[0][1], validate_args=False)
- self.pitch_sampler = Uniform(degrees[1][0], degrees[1][1], validate_args=False)
- self.roll_sampler = Uniform(degrees[2][0], degrees[2][1], validate_args=False)
-
- def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, torch.Tensor]: # type:ignore
- batch_size = batch_shape[0]
- _common_param_check(batch_size, same_on_batch)
- _device, _dtype = _extract_device_dtype([self.degrees])
-
- return dict(
- yaw=_adapted_rsampling(
- (batch_size,), self.yaw_sampler, same_on_batch).to(device=_device, dtype=_dtype),
- pitch=_adapted_rsampling(
- (batch_size,), self.pitch_sampler, same_on_batch).to(device=_device, dtype=_dtype),
- roll=_adapted_rsampling(
- (batch_size,), self.roll_sampler, same_on_batch).to(device=_device, dtype=_dtype),
- )
-
-
-class MotionBlurGenerator3D(RandomGeneratorBase):
- r"""Get parameters for motion blur.
-
- Args:
- kernel_size: motion kernel size (odd and positive).
- If int, the kernel will have a fixed size.
- If Tuple[int, int], it will randomly generate the value from the range batch-wisely.
- angle: angle of the motion blur in degrees (anti-clockwise rotation).
- If float, it will generate the value from (-angle, angle).
- direction: forward/backward direction of the motion blur.
- Lower values towards -1.0 will point the motion blur towards the back (with angle provided via angle),
- while higher values towards 1.0 will point the motion blur forward. A value of 0.0 leads to a
- uniformly (but still angled) motion blur.
- If float, it will generate the value from (-direction, direction).
- If Tuple[int, int], it will randomly generate the value from the range.
-
- Returns:
- A dict of parameters to be passed for transformation.
- - ksize_factor (torch.Tensor): element-wise kernel size factors with a shape of (B,).
- - angle_factor (torch.Tensor): element-wise angle factors with a shape of (B,).
- - direction_factor (torch.Tensor): element-wise direction factors 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,
- kernel_size: Union[int, Tuple[int, int]],
- angle: Union[
- torch.Tensor,
- float,
- Tuple[float, float, float],
- Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float]],
- ],
- direction: Union[torch.Tensor, float, Tuple[float, float]],
- ) -> None:
- super().__init__()
- self.kernel_size = kernel_size
- self.angle = angle
- self.direction = direction
-
- def __repr__(self) -> str:
- repr = f"kernel_size={self.kernel_size}, angle={self.angle}, direction={self.direction}"
- return repr
-
- def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
- angle: torch.Tensor = _tuple_range_reader(self.angle, 3, device=device, dtype=dtype)
- direction = _range_bound(self.direction, 'direction', center=0.0, bounds=(-1, 1)).to(device=device, dtype=dtype)
- if isinstance(self.kernel_size, int):
- if not (self.kernel_size >= 3 and self.kernel_size % 2 == 1):
- raise AssertionError(f"`kernel_size` must be odd and greater than 3. Got {self.kernel_size}.")
- self.ksize_sampler = Uniform(self.kernel_size // 2, self.kernel_size // 2, validate_args=False)
- elif isinstance(self.kernel_size, tuple):
- # kernel_size is fixed across the batch
- if len(self.kernel_size) != 2:
- raise AssertionError(f"`kernel_size` must be (2,) if it is a tuple. Got {self.kernel_size}.")
- self.ksize_sampler = Uniform(self.kernel_size[0] // 2, self.kernel_size[1] // 2, validate_args=False)
- else:
- raise TypeError(f"Unsupported type: {type(self.kernel_size)}")
-
- self.yaw_sampler = Uniform(angle[0][0], angle[0][1], validate_args=False)
- self.pitch_sampler = Uniform(angle[1][0], angle[1][1], validate_args=False)
- self.roll_sampler = Uniform(angle[2][0], angle[2][1], validate_args=False)
- self.direction_sampler = Uniform(direction[0], direction[1], validate_args=False)
-
- def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, torch.Tensor]: # type:ignore
- batch_size = batch_shape[0]
- _common_param_check(batch_size, same_on_batch)
- # self.ksize_factor.expand((batch_size, -1))
- _device, _dtype = _extract_device_dtype([self.angle, self.direction])
- yaw_factor = _adapted_rsampling((batch_size,), self.yaw_sampler, same_on_batch)
- pitch_factor = _adapted_rsampling((batch_size,), self.pitch_sampler, same_on_batch)
- roll_factor = _adapted_rsampling((batch_size,), self.roll_sampler, same_on_batch)
- angle_factor = torch.stack([yaw_factor, pitch_factor, roll_factor], dim=1)
-
- direction_factor = _adapted_rsampling((batch_size,), self.direction_sampler, same_on_batch)
- ksize_factor = _adapted_rsampling((batch_size,), self.ksize_sampler, same_on_batch).int() * 2 + 1
-
- return dict(
- ksize_factor=ksize_factor.to(device=_device, dtype=torch.int32),
- angle_factor=angle_factor.to(device=_device, dtype=_dtype),
- direction_factor=direction_factor.to(device=_device, dtype=_dtype),
- )
-
-
-class PerspectiveGenerator3D(RandomGeneratorBase):
- r"""Get parameters for ``perspective`` for a random perspective transform.
-
- Args:
- distortion_scale: controls the degree of distortion and ranges from 0 to 1.
-
- Returns:
- A dict of parameters to be passed for transformation.
- - src (torch.Tensor): perspective source bounding boxes with a shape of (B, 8, 3).
- - dst (torch.Tensor): perspective target bounding boxes with a shape (B, 8, 3).
-
- 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, distortion_scale: Union[torch.Tensor, float] = 0.5) -> None:
- super().__init__()
- self.distortion_scale = distortion_scale
-
- def __repr__(self) -> str:
- repr = f"distortion_scale={self.distortion_scale}"
- return repr
-
- def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
- self._distortion_scale = torch.as_tensor(self.distortion_scale, device=device, dtype=dtype)
- if not (self._distortion_scale.dim() == 0 and 0 <= self._distortion_scale <= 1):
- raise AssertionError(
- f"'distortion_scale' must be a scalar within [0, 1]. Got {self._distortion_scale}")
- self.rand_sampler = Uniform(
- torch.tensor(0, device=device, dtype=dtype),
- torch.tensor(1, device=device, dtype=dtype),
- validate_args=False
- )
-
- def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, torch.Tensor]: # type:ignore
- batch_size = batch_shape[0]
- depth = batch_shape[-3]
- height = batch_shape[-2]
- width = batch_shape[-1]
-
- _common_param_check(batch_size, same_on_batch)
- _device, _dtype = _extract_device_dtype([self.distortion_scale])
-
- start_points: torch.Tensor = torch.tensor(
- [
- [
- [0.0, 0, 0],
- [width - 1, 0, 0],
- [width - 1, height - 1, 0],
- [0, height - 1, 0],
- [0.0, 0, depth - 1],
- [width - 1, 0, depth - 1],
- [width - 1, height - 1, depth - 1],
- [0, height - 1, depth - 1],
- ]
- ],
- device=_device,
- dtype=_dtype,
- ).expand(batch_size, -1, -1)
-
- # generate random offset not larger than half of the image
- fx = self._distortion_scale * width / 2
- fy = self._distortion_scale * height / 2
- fz = self._distortion_scale * depth / 2
-
- factor = torch.stack([fx, fy, fz], dim=0).view(-1, 1, 3).to(device=_device, dtype=_dtype)
-
- rand_val: torch.Tensor = _adapted_rsampling(
- start_points.shape, self.rand_sampler, same_on_batch).to(device=_device, dtype=_dtype)
-
- pts_norm = torch.tensor(
- [[[1, 1, 1], [-1, 1, 1], [-1, -1, 1], [1, -1, 1], [1, 1, -1], [-1, 1, -1], [-1, -1, -1], [1, -1, -1]]],
- device=_device,
- dtype=_dtype,
- )
- end_points = start_points + factor * rand_val * pts_norm
-
- return dict(
- start_points=start_points,
- end_points=end_points,
- )
-
-
-@_deprecated(replace_with=RotationGenerator3D.__name__)
-def random_rotation_generator3d(
- batch_size: int,
- degrees: torch.Tensor,
- same_on_batch: bool = False,
- device: torch.device = torch.device('cpu'),
- dtype: torch.dtype = torch.float32,
-) -> Dict[str, torch.Tensor]:
- r"""Get parameters for ``rotate`` for a random rotate transform.
-
- Args:
- batch_size (int): the tensor batch size.
- degrees (torch.Tensor): Ranges of degrees (3, 2) for yaw, pitch and roll.
- 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.
- - yaw (torch.Tensor): element-wise rotation yaws with a shape of (B,).
- - pitch (torch.Tensor): element-wise rotation pitches with a shape of (B,).
- - roll (torch.Tensor): element-wise rotation rolls with a shape of (B,).
- """
- if degrees.shape != torch.Size([3, 2]):
- raise AssertionError(f"'degrees' must be the shape of (3, 2). Got {degrees.shape}.")
- _device, _dtype = _extract_device_dtype([degrees])
- degrees = degrees.to(device=device, dtype=dtype)
- yaw = _adapted_uniform((batch_size,), degrees[0][0], degrees[0][1], same_on_batch)
- pitch = _adapted_uniform((batch_size,), degrees[1][0], degrees[1][1], same_on_batch)
- roll = _adapted_uniform((batch_size,), degrees[2][0], degrees[2][1], same_on_batch)
-
- return dict(
- yaw=yaw.to(device=_device, dtype=_dtype),
- pitch=pitch.to(device=_device, dtype=_dtype),
- roll=roll.to(device=_device, dtype=_dtype),
- )
-
-
-@_deprecated(replace_with=AffineGenerator3D.__name__)
-def random_affine_generator3d(
- batch_size: int,
- depth: int,
- height: int,
- width: int,
- degrees: torch.Tensor,
- translate: Optional[torch.Tensor] = None,
- scale: Optional[torch.Tensor] = None,
- shears: 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"""Get parameters for ```3d affine``` transformation random affine transform.
-
- Args:
- batch_size (int): the tensor batch size.
- depth (int) : depth of the image.
- height (int) : height of the image.
- width (int): width of the image.
- degrees (torch.Tensor): Ranges of degrees with shape (3, 2) for yaw, pitch and roll.
- translate (torch.Tensor, optional): maximum absolute fraction with shape (3,) for horizontal, vertical
- and depthical translations (dx,dy,dz). Will not translate by default.
- scale (torch.Tensor, optional): scaling factor interval, e.g (a, b), then scale is
- randomly sampled from the range a <= scale <= b. Will keep original scale by default.
- shear (sequence or float, optional): Range of degrees to select from.
- Shaped as (6, 2) for 6 facet (xy, xz, yx, yz, zx, zy).
- The shear to the i-th facet in the range (-shear[i, 0], shear[i, 1]) will be applied.
- same_on_batch (bool): apply the same transformation across the batch. Default: False
-
- Returns:
- params Dict[str, torch.Tensor]: parameters to be passed for transformation.
- - translations (torch.Tensor): element-wise translations with a shape of (B, 3).
- - center (torch.Tensor): element-wise center with a shape of (B, 3).
- - scale (torch.Tensor): element-wise scales with a shape of (B, 3).
- - angle (torch.Tensor): element-wise rotation angles with a shape of (B, 3).
- - sxy (torch.Tensor): element-wise x-y-facet shears with a shape of (B,).
- - sxz (torch.Tensor): element-wise x-z-facet shears with a shape of (B,).
- - syx (torch.Tensor): element-wise y-x-facet shears with a shape of (B,).
- - syz (torch.Tensor): element-wise y-z-facet shears with a shape of (B,).
- - szx (torch.Tensor): element-wise z-x-facet shears with a shape of (B,).
- - szy (torch.Tensor): element-wise z-y-facet shears with a shape of (B,).
-
- Note:
- The generated random numbers are not reproducible across different devices and dtypes.
- """
- if not (
- type(depth) is int and depth > 0 and type(height) is int and height > 0 and type(width) is int and width > 0
- ):
- raise AssertionError(f"'depth', 'height' and 'width' must be integers. Got {depth}, {height}, {width}.")
-
- _device, _dtype = _extract_device_dtype([degrees, translate, scale, shears])
- if degrees.shape != torch.Size([3, 2]):
- raise AssertionError(f"'degrees' must be the shape of (3, 2). Got {degrees.shape}.")
- degrees = degrees.to(device=device, dtype=dtype)
- yaw = _adapted_uniform((batch_size,), degrees[0][0], degrees[0][1], same_on_batch)
- pitch = _adapted_uniform((batch_size,), degrees[1][0], degrees[1][1], same_on_batch)
- roll = _adapted_uniform((batch_size,), degrees[2][0], degrees[2][1], same_on_batch)
- angles = torch.stack([yaw, pitch, roll], dim=1)
-
- # compute tensor ranges
- if scale is not None:
- if scale.shape != torch.Size([3, 2]):
- raise AssertionError(f"'scale' must be the shape of (3, 2). Got {scale.shape}.")
- scale = scale.to(device=device, dtype=dtype)
- scale = torch.stack(
- [
- _adapted_uniform((batch_size,), scale[0, 0], scale[0, 1], same_on_batch),
- _adapted_uniform((batch_size,), scale[1, 0], scale[1, 1], same_on_batch),
- _adapted_uniform((batch_size,), scale[2, 0], scale[2, 1], same_on_batch),
- ],
- dim=1,
- )
- else:
- scale = torch.ones(batch_size, device=device, dtype=dtype).reshape(batch_size, 1).repeat(1, 3)
-
- if translate is not None:
- if translate.shape != torch.Size([3]):
- raise AssertionError(f"'translate' must be the shape of (2). Got {translate.shape}.")
- translate = translate.to(device=device, dtype=dtype)
- max_dx: torch.Tensor = translate[0] * width
- max_dy: torch.Tensor = translate[1] * height
- max_dz: torch.Tensor = translate[2] * depth
- # translations should be in x,y,z
- translations = torch.stack(
- [
- _adapted_uniform((batch_size,), -max_dx, max_dx, same_on_batch),
- _adapted_uniform((batch_size,), -max_dy, max_dy, same_on_batch),
- _adapted_uniform((batch_size,), -max_dz, max_dz, same_on_batch),
- ],
- dim=1,
- )
- else:
- translations = torch.zeros((batch_size, 3), device=device, dtype=dtype)
-
- # center should be in x,y,z
- center: torch.Tensor = torch.tensor([width, height, depth], device=device, dtype=dtype).view(1, 3) / 2.0 - 0.5
- center = center.expand(batch_size, -1)
-
- if shears is not None:
- if shears.shape != torch.Size([6, 2]):
- raise AssertionError(f"'shears' must be the shape of (6, 2). Got {shears.shape}.")
- shears = shears.to(device=device, dtype=dtype)
- sxy = _adapted_uniform((batch_size,), shears[0, 0], shears[0, 1], same_on_batch)
- sxz = _adapted_uniform((batch_size,), shears[1, 0], shears[1, 1], same_on_batch)
- syx = _adapted_uniform((batch_size,), shears[2, 0], shears[2, 1], same_on_batch)
- syz = _adapted_uniform((batch_size,), shears[3, 0], shears[3, 1], same_on_batch)
- szx = _adapted_uniform((batch_size,), shears[4, 0], shears[4, 1], same_on_batch)
- szy = _adapted_uniform((batch_size,), shears[5, 0], shears[5, 1], same_on_batch)
- else:
- sxy = sxz = syx = syz = szx = szy = torch.tensor([0] * batch_size, device=device, dtype=dtype)
-
- return dict(
- translations=translations.to(device=_device, dtype=_dtype),
- center=center.to(device=_device, dtype=_dtype),
- scale=scale.to(device=_device, dtype=_dtype),
- angles=angles.to(device=_device, dtype=_dtype),
- sxy=sxy.to(device=_device, dtype=_dtype),
- sxz=sxz.to(device=_device, dtype=_dtype),
- syx=syx.to(device=_device, dtype=_dtype),
- syz=syz.to(device=_device, dtype=_dtype),
- szx=szx.to(device=_device, dtype=_dtype),
- szy=szy.to(device=_device, dtype=_dtype),
- )
-
-
-@_deprecated(replace_with=MotionBlurGenerator3D.__name__)
-def random_motion_blur_generator3d(
- batch_size: int,
- kernel_size: Union[int, Tuple[int, int]],
- angle: torch.Tensor,
- direction: torch.Tensor,
- same_on_batch: bool = False,
- device: torch.device = torch.device('cpu'),
- dtype: torch.dtype = torch.float32,
-) -> Dict[str, torch.Tensor]:
- r"""Get parameters for motion blur.
-
- Args:
- batch_size (int): the tensor batch size.
- kernel_size (int or (int, int)): motion kernel size (odd and positive) or range.
- angle (torch.Tensor): yaw, pitch and roll range of the motion blur in degrees :math:`(3, 2)`.
- direction (torch.Tensor): forward/backward direction of the motion blur.
- Lower values towards -1.0 will point the motion blur towards the back (with
- angle provided via angle), while higher values towards 1.0 will point the motion
- blur forward. A value of 0.0 leads to a uniformly (but still angled) motion blur.
- 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.
- - ksize_factor (torch.Tensor): element-wise kernel size factors with a shape of (B,).
- - angle_factor (torch.Tensor): element-wise center with a shape of (B,).
- - direction_factor (torch.Tensor): element-wise scales with a shape of (B,).
-
- Note:
- The generated random numbers are not reproducible across different devices and dtypes.
- """
- _device, _dtype = _extract_device_dtype([angle, direction])
- _joint_range_check(direction, 'direction', (-1, 1))
- if isinstance(kernel_size, int):
- if not (kernel_size >= 3 and kernel_size % 2 == 1):
- raise AssertionError(f"`kernel_size` must be odd and greater than 3. Got {kernel_size}.")
- ksize_factor = torch.tensor([kernel_size] * batch_size, device=device, dtype=dtype).int()
- elif isinstance(kernel_size, tuple):
- if not (len(kernel_size) == 2 and kernel_size[0] >= 3 and kernel_size[0] <= kernel_size[1]):
- raise AssertionError(f"`kernel_size` must be greater than 3. Got range {kernel_size}.")
- # kernel_size is fixed across the batch
- ksize_factor = (
- _adapted_uniform((batch_size,), kernel_size[0] // 2, kernel_size[1] // 2, same_on_batch=True).int() * 2 + 1
- )
- else:
- raise TypeError(f"Unsupported type: {type(kernel_size)}")
-
- if angle.shape != torch.Size([3, 2]):
- raise AssertionError(f"'angle' must be the shape of (3, 2). Got {angle.shape}.")
- angle = angle.to(device=device, dtype=dtype)
- yaw = _adapted_uniform((batch_size,), angle[0][0], angle[0][1], same_on_batch)
- pitch = _adapted_uniform((batch_size,), angle[1][0], angle[1][1], same_on_batch)
- roll = _adapted_uniform((batch_size,), angle[2][0], angle[2][1], same_on_batch)
- angle_factor = torch.stack([yaw, pitch, roll], dim=1)
-
- direction = direction.to(device=device, dtype=dtype)
- direction_factor = _adapted_uniform((batch_size,), direction[0], direction[1], same_on_batch)
-
- return dict(
- ksize_factor=ksize_factor.to(device=_device),
- angle_factor=angle_factor.to(device=_device, dtype=_dtype),
- direction_factor=direction_factor.to(device=_device, dtype=_dtype),
- )
-
-
-def center_crop_generator3d(
- batch_size: int,
- depth: int,
- height: int,
- width: int,
- size: Tuple[int, int, int],
- device: torch.device = torch.device('cpu'),
-) -> Dict[str, torch.Tensor]:
- r"""Get parameters for ```center_crop3d``` transformation for center crop transform.
-
- Args:
- batch_size (int): the tensor batch size.
- depth (int) : depth of the image.
- height (int) : height of the image.
- width (int): width of the image.
- size (tuple): Desired output size of the crop, like (d, h, w).
- device (torch.device): the device on which the random numbers will be generated. Default: cpu.
-
- Returns:
- params Dict[str, torch.Tensor]: parameters to be passed for transformation.
- - src (torch.Tensor): cropping bounding boxes with a shape of (B, 8, 3).
- - dst (torch.Tensor): output bounding boxes with a shape (B, 8, 3).
-
- Note:
- No random number will be generated.
- """
- if not isinstance(size, (tuple, list)) and len(size) == 3:
- raise ValueError(f"Input size must be a tuple/list of length 3. Got {size}")
- if not (
- type(depth) is int and depth > 0 and type(height) is int and height > 0 and type(width) is int and width > 0
- ):
- raise AssertionError(f"'depth', 'height' and 'width' must be integers. Got {depth}, {height}, {width}.")
- if not (depth >= size[0] and height >= size[1] and width >= size[2]):
- raise AssertionError(f"Crop size must be smaller than input size. Got ({depth}, {height}, {width}) and {size}.")
-
- if batch_size == 0:
- return dict(src=torch.zeros([0, 8, 3]), dst=torch.zeros([0, 8, 3]))
- # unpack input sizes
- dst_d, dst_h, dst_w = size
- src_d, src_h, src_w = (depth, height, width)
-
- # compute start/end offsets
- dst_d_half = dst_d / 2
- dst_h_half = dst_h / 2
- dst_w_half = dst_w / 2
- src_d_half = src_d / 2
- src_h_half = src_h / 2
- src_w_half = src_w / 2
-
- start_x = src_w_half - dst_w_half
- start_y = src_h_half - dst_h_half
- start_z = src_d_half - dst_d_half
-
- end_x = start_x + dst_w - 1
- end_y = start_y + dst_h - 1
- end_z = start_z + dst_d - 1
- # [x, y, z] origin
- # top-left-front, top-right-front, bottom-right-front, bottom-left-front
- # top-left-back, top-right-back, bottom-right-back, bottom-left-back
- # Note: DeprecationWarning: an integer is required (got type float).
- # Implicit conversion to integers using __int__ is deprecated, and may be removed in a future version of Python.
- points_src: torch.Tensor = torch.tensor(
- [
- [
- [int(start_x), int(start_y), int(start_z)],
- [int(end_x), int(start_y), int(start_z)],
- [int(end_x), int(end_y), int(start_z)],
- [int(start_x), int(end_y), int(start_z)],
- [int(start_x), int(start_y), int(end_z)],
- [int(end_x), int(start_y), int(end_z)],
- [int(end_x), int(end_y), int(end_z)],
- [int(start_x), int(end_y), int(end_z)],
- ]
- ],
- device=device,
- dtype=torch.long,
- ).expand(batch_size, -1, -1)
-
- # [x, y, z] destination
- # top-left-front, top-right-front, bottom-right-front, bottom-left-front
- # top-left-back, top-right-back, bottom-right-back, bottom-left-back
- points_dst: torch.Tensor = torch.tensor(
- [
- [
- [0, 0, 0],
- [dst_w - 1, 0, 0],
- [dst_w - 1, dst_h - 1, 0],
- [0, dst_h - 1, 0],
- [0, 0, dst_d - 1],
- [dst_w - 1, 0, dst_d - 1],
- [dst_w - 1, dst_h - 1, dst_d - 1],
- [0, dst_h - 1, dst_d - 1],
- ]
- ],
- device=device,
- dtype=torch.long,
- ).expand(batch_size, -1, -1)
- return dict(src=points_src, dst=points_dst)
-
-
-@_deprecated(replace_with=CropGenerator3D.__name__)
-def random_crop_generator3d(
- batch_size: int,
- input_size: Tuple[int, int, int],
- size: Union[Tuple[int, int, int], torch.Tensor],
- resize_to: Optional[Tuple[int, int, int]] = None,
- same_on_batch: bool = False,
- device: torch.device = torch.device('cpu'),
- dtype: torch.dtype = torch.float32,
-) -> Dict[str, torch.Tensor]:
- r"""Get parameters for ```crop``` transformation for crop transform.
-
- Args:
- batch_size (int): the tensor batch size.
- input_size (tuple): Input image shape, like (d, h, w).
- size (tuple): Desired size of the crop operation, like (d, h, w).
- If tensor, it must be (B, 3).
- resize_to (tuple): Desired output size of the crop, like (d, h, w). If None, no resize will be performed.
- 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.
- - src (torch.Tensor): cropping bounding boxes with a shape of (B, 8, 3).
- - dst (torch.Tensor): output bounding boxes with a shape (B, 8, 3).
-
- Note:
- The generated random numbers are not reproducible across different devices and dtypes.
- """
- _device, _dtype = _extract_device_dtype([size if isinstance(size, torch.Tensor) else None])
- if not isinstance(size, torch.Tensor):
- size = torch.tensor(size, device=device, dtype=dtype).repeat(batch_size, 1)
- else:
- size = size.to(device=device, dtype=dtype)
- if size.shape != torch.Size([batch_size, 3]):
- raise AssertionError(
- "If `size` is a tensor, it must be shaped as (B, 3). "
- f"Got {size.shape} while expecting {torch.Size([batch_size, 3])}."
- )
- if not (
- len(input_size) == 3
- and isinstance(input_size[0], (int,))
- and isinstance(input_size[1], (int,))
- and isinstance(input_size[2], (int,))
- and input_size[0] > 0
- and input_size[1] > 0
- and input_size[2] > 0
- ):
- raise AssertionError(f"`input_size` must be a tuple of 3 positive integers. Got {input_size}.")
-
- x_diff = input_size[2] - size[:, 2] + 1
- y_diff = input_size[1] - size[:, 1] + 1
- z_diff = input_size[0] - size[:, 0] + 1
-
- if (x_diff < 0).any() or (y_diff < 0).any() or (z_diff < 0).any():
- raise ValueError(f"input_size {str(input_size)} cannot be smaller than crop size {str(size)} in any dimension.")
-
- if batch_size == 0:
- return dict(
- src=torch.zeros([0, 8, 3], device=_device, dtype=_dtype),
- dst=torch.zeros([0, 8, 3], device=_device, dtype=_dtype),
- )
-
- if same_on_batch:
- # If same_on_batch, select the first then repeat.
- x_start = _adapted_uniform((batch_size,), 0, x_diff[0], same_on_batch).floor()
- y_start = _adapted_uniform((batch_size,), 0, y_diff[0], same_on_batch).floor()
- z_start = _adapted_uniform((batch_size,), 0, z_diff[0], same_on_batch).floor()
- else:
- x_start = _adapted_uniform((1,), 0, x_diff, same_on_batch).floor()
- y_start = _adapted_uniform((1,), 0, y_diff, same_on_batch).floor()
- z_start = _adapted_uniform((1,), 0, z_diff, same_on_batch).floor()
-
- crop_src = bbox_generator3d(
- x_start.to(device=_device, dtype=_dtype).view(-1),
- y_start.to(device=_device, dtype=_dtype).view(-1),
- z_start.to(device=_device, dtype=_dtype).view(-1),
- size[:, 2].to(device=_device, dtype=_dtype) - 1,
- size[:, 1].to(device=_device, dtype=_dtype) - 1,
- size[:, 0].to(device=_device, dtype=_dtype) - 1,
- )
-
- if resize_to is None:
- crop_dst = bbox_generator3d(
- torch.tensor([0] * batch_size, device=_device, dtype=_dtype),
- torch.tensor([0] * batch_size, device=_device, dtype=_dtype),
- torch.tensor([0] * batch_size, device=_device, dtype=_dtype),
- size[:, 2].to(device=_device, dtype=_dtype) - 1,
- size[:, 1].to(device=_device, dtype=_dtype) - 1,
- size[:, 0].to(device=_device, dtype=_dtype) - 1,
- )
- else:
- if not (
- len(resize_to) == 3
- and isinstance(resize_to[0], (int,))
- and isinstance(resize_to[1], (int,))
- and isinstance(resize_to[2], (int,))
- and resize_to[0] > 0
- and resize_to[1] > 0
- and resize_to[2] > 0
- ):
- raise AssertionError(f"`resize_to` must be a tuple of 3 positive integers. Got {resize_to}.")
- crop_dst = torch.tensor(
- [
- [
- [0, 0, 0],
- [resize_to[-1] - 1, 0, 0],
- [resize_to[-1] - 1, resize_to[-2] - 1, 0],
- [0, resize_to[-2] - 1, 0],
- [0, 0, resize_to[-3] - 1],
- [resize_to[-1] - 1, 0, resize_to[-3] - 1],
- [resize_to[-1] - 1, resize_to[-2] - 1, resize_to[-3] - 1],
- [0, resize_to[-2] - 1, resize_to[-3] - 1],
- ]
- ],
- device=_device,
- dtype=_dtype,
- ).repeat(batch_size, 1, 1)
-
- return dict(src=crop_src.to(device=_device), dst=crop_dst.to(device=_device))
-
-
-@_deprecated(replace_with=PerspectiveGenerator3D.__name__)
-def random_perspective_generator3d(
- batch_size: int,
- depth: int,
- height: int,
- width: int,
- distortion_scale: torch.Tensor,
- same_on_batch: bool = False,
- device: torch.device = torch.device('cpu'),
- dtype: torch.dtype = torch.float32,
-) -> Dict[str, torch.Tensor]:
- r"""Get parameters for ``perspective`` for a random perspective transform.
-
- Args:
- batch_size (int): the tensor batch size.
- depth (int) : depth of the image.
- height (int) : height of the image.
- width (int): width of the image.
- distortion_scale (torch.Tensor): it controls the degree of distortion and ranges from 0 to 1.
- 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.
- - src (torch.Tensor): perspective source bounding boxes with a shape of (B, 8, 3).
- - dst (torch.Tensor): perspective target bounding boxes with a shape (B, 8, 3).
-
- Note:
- The generated random numbers are not reproducible across different devices and dtypes.
- """
- if not (distortion_scale.dim() == 0 and 0 <= distortion_scale <= 1):
- raise AssertionError(f"'distortion_scale' must be a scalar within [0, 1]. Got {distortion_scale}")
- _device, _dtype = _extract_device_dtype([distortion_scale])
- distortion_scale = distortion_scale.to(device=device, dtype=dtype)
-
- start_points: torch.Tensor = torch.tensor(
- [
- [
- [0.0, 0, 0],
- [width - 1, 0, 0],
- [width - 1, height - 1, 0],
- [0, height - 1, 0],
- [0.0, 0, depth - 1],
- [width - 1, 0, depth - 1],
- [width - 1, height - 1, depth - 1],
- [0, height - 1, depth - 1],
- ]
- ],
- device=device,
- dtype=dtype,
- ).expand(batch_size, -1, -1)
-
- # generate random offset not larger than half of the image
- fx = distortion_scale * width / 2
- fy = distortion_scale * height / 2
- fz = distortion_scale * depth / 2
-
- factor = torch.stack([fx, fy, fz], dim=0).view(-1, 1, 3)
-
- rand_val: torch.Tensor = _adapted_uniform(
- start_points.shape,
- torch.tensor(0, device=device, dtype=dtype),
- torch.tensor(1, device=device, dtype=dtype),
- same_on_batch,
- )
-
- pts_norm = torch.tensor(
- [[[1, 1, 1], [-1, 1, 1], [-1, -1, 1], [1, -1, 1], [1, 1, -1], [-1, 1, -1], [-1, -1, -1], [1, -1, -1]]],
- device=device,
- dtype=dtype,
- )
- end_points = start_points + factor * rand_val * pts_norm
-
- return dict(
- start_points=start_points.to(device=_device, dtype=_dtype),
- end_points=end_points.to(device=_device, dtype=_dtype),
- )
diff --git a/kornia/augmentation/utils/helpers.py b/kornia/augmentation/utils/helpers.py
index ccc29ea73..36ea4f33c 100644
--- a/kornia/augmentation/utils/helpers.py
+++ b/kornia/augmentation/utils/helpers.py
@@ -1,5 +1,5 @@
from functools import wraps
-from typing import Callable, cast, List, Optional, Tuple, Union
+from typing import Callable, List, Optional, Tuple, Union, cast
import torch
from torch.distributions import Beta, Uniform
diff --git a/kornia/augmentation/utils/param_validation.py b/kornia/augmentation/utils/param_validation.py
index 0acc3043f..98ad5830a 100644
--- a/kornia/augmentation/utils/param_validation.py
+++ b/kornia/augmentation/utils/param_validation.py
@@ -1,4 +1,4 @@
-from typing import cast, List, Optional, Tuple, Union
+from typing import List, Optional, Tuple, Union, cast
import torch
diff --git a/kornia/color/__init__.py b/kornia/color/__init__.py
index c3a2543fd..7f4ecafac 100644
--- a/kornia/color/__init__.py
+++ b/kornia/color/__init__.py
@@ -1,42 +1,42 @@
-from .gray import bgr_to_grayscale, BgrToGrayscale, grayscale_to_rgb, GrayscaleToRgb, rgb_to_grayscale, RgbToGrayscale
-from .hls import hls_to_rgb, HlsToRgb, rgb_to_hls, RgbToHls
-from .hsv import hsv_to_rgb, HsvToRgb, rgb_to_hsv, RgbToHsv
-from .lab import lab_to_rgb, LabToRgb, rgb_to_lab, RgbToLab
-from .luv import luv_to_rgb, LuvToRgb, rgb_to_luv, RgbToLuv
-from .raw import CFA, raw_to_rgb, RawToRgb, rgb_to_raw, RgbToRaw
+from .gray import BgrToGrayscale, GrayscaleToRgb, RgbToGrayscale, bgr_to_grayscale, grayscale_to_rgb, rgb_to_grayscale
+from .hls import HlsToRgb, RgbToHls, hls_to_rgb, rgb_to_hls
+from .hsv import HsvToRgb, RgbToHsv, hsv_to_rgb, rgb_to_hsv
+from .lab import LabToRgb, RgbToLab, lab_to_rgb, rgb_to_lab
+from .luv import LuvToRgb, RgbToLuv, luv_to_rgb, rgb_to_luv
+from .raw import CFA, RawToRgb, RgbToRaw, raw_to_rgb, rgb_to_raw
from .rgb import (
- bgr_to_rgb,
- bgr_to_rgba,
BgrToRgb,
BgrToRgba,
- linear_rgb_to_rgb,
LinearRgbToRgb,
- rgb_to_bgr,
- rgb_to_linear_rgb,
- rgb_to_rgba,
- rgba_to_bgr,
- rgba_to_rgb,
RgbaToBgr,
RgbaToRgb,
RgbToBgr,
RgbToLinearRgb,
RgbToRgba,
+ bgr_to_rgb,
+ bgr_to_rgba,
+ linear_rgb_to_rgb,
+ rgb_to_bgr,
+ rgb_to_linear_rgb,
+ rgb_to_rgba,
+ rgba_to_bgr,
+ rgba_to_rgb,
)
-from .xyz import rgb_to_xyz, RgbToXyz, xyz_to_rgb, XyzToRgb
-from .ycbcr import rgb_to_ycbcr, RgbToYcbcr, ycbcr_to_rgb, YcbcrToRgb
+from .xyz import RgbToXyz, XyzToRgb, rgb_to_xyz, xyz_to_rgb
+from .ycbcr import RgbToYcbcr, YcbcrToRgb, rgb_to_ycbcr, ycbcr_to_rgb
from .yuv import (
- rgb_to_yuv,
- rgb_to_yuv420,
- rgb_to_yuv422,
RgbToYuv,
RgbToYuv420,
RgbToYuv422,
- yuv420_to_rgb,
Yuv420ToRgb,
- yuv422_to_rgb,
Yuv422ToRgb,
- yuv_to_rgb,
YuvToRgb,
+ rgb_to_yuv,
+ rgb_to_yuv420,
+ rgb_to_yuv422,
+ yuv420_to_rgb,
+ yuv422_to_rgb,
+ yuv_to_rgb,
)
__all__ = [
diff --git a/kornia/color/rgb.py b/kornia/color/rgb.py
index c54866814..e311b003e 100644
--- a/kornia/color/rgb.py
+++ b/kornia/color/rgb.py
@@ -1,4 +1,4 @@
-from typing import cast, Union
+from typing import Union, cast
import torch
import torch.nn as nn
diff --git a/kornia/constants.py b/kornia/constants.py
index 95ffefaa1..8cd8f816e 100644
--- a/kornia/constants.py
+++ b/kornia/constants.py
@@ -1,5 +1,5 @@
from enum import Enum, EnumMeta
-from typing import cast, TypeVar, Union
+from typing import TypeVar, Union, cast
import torch
diff --git a/kornia/contrib/__init__.py b/kornia/contrib/__init__.py
index a532e8efc..cc4e701c9 100644
--- a/kornia/contrib/__init__.py
+++ b/kornia/contrib/__init__.py
@@ -1,6 +1,6 @@
from .classification import ClassificationHead
from .connected_components import connected_components
-from .extract_patches import combine_tensor_patches, CombineTensorPatches, extract_tensor_patches, ExtractTensorPatches
+from .extract_patches import CombineTensorPatches, ExtractTensorPatches, combine_tensor_patches, extract_tensor_patches
from .face_detection import *
from .histogram_matching import histogram_matching, interp
from .image_stitching import ImageStitcher
diff --git a/kornia/enhance/__init__.py b/kornia/enhance/__init__.py
index e20b29196..87639a789 100644
--- a/kornia/enhance/__init__.py
+++ b/kornia/enhance/__init__.py
@@ -1,4 +1,10 @@
from .adjust import (
+ AdjustBrightness,
+ AdjustContrast,
+ AdjustGamma,
+ AdjustHue,
+ AdjustSaturation,
+ Invert,
adjust_brightness,
adjust_contrast,
adjust_gamma,
@@ -6,24 +12,18 @@ from .adjust import (
adjust_hue_raw,
adjust_saturation,
adjust_saturation_raw,
- AdjustBrightness,
- AdjustContrast,
- AdjustGamma,
- AdjustHue,
- AdjustSaturation,
equalize,
equalize3d,
invert,
- Invert,
posterize,
sharpness,
solarize,
)
-from .core import add_weighted, AddWeighted
+from .core import AddWeighted, add_weighted
from .equalization import equalize_clahe
from .histogram import histogram, histogram2d, image_histogram2d
-from .normalize import denormalize, Denormalize, normalize, Normalize, normalize_min_max
-from .zca import linear_transform, zca_mean, zca_whiten, ZCAWhitening
+from .normalize import Denormalize, Normalize, denormalize, normalize, normalize_min_max
+from .zca import ZCAWhitening, linear_transform, zca_mean, zca_whiten
__all__ = [
"adjust_brightness",
diff --git a/kornia/feature/__init__.py b/kornia/feature/__init__.py
index 364621b03..b37b71256 100644
--- a/kornia/feature/__init__.py
+++ b/kornia/feature/__init__.py
@@ -2,12 +2,12 @@ from .affine_shape import LAFAffineShapeEstimator, LAFAffNetShapeEstimator, Patc
from .defmo import DeFMO
from .hardnet import HardNet, HardNet8
from .integrated import (
- get_laf_descriptors,
GFTTAffNetHardNet,
LAFDescriptor,
LocalFeature,
LocalFeatureMatcher,
SIFTFeature,
+ get_laf_descriptors,
)
from .laf import (
denormalize_laf,
diff --git a/kornia/feature/orientation.py b/kornia/feature/orientation.py
index a9c767f3f..30eef5807 100644
--- a/kornia/feature/orientation.py
+++ b/kornia/feature/orientation.py
@@ -6,7 +6,7 @@ import torch.nn as nn
import torch.nn.functional as F
from kornia.constants import pi
-from kornia.filters import get_gaussian_kernel2d, SpatialGradient
+from kornia.filters import SpatialGradient, get_gaussian_kernel2d
from kornia.geometry import rad2deg
from .laf import extract_patches_from_pyramid, get_laf_orientation, raise_error_if_laf_is_not_valid, set_laf_orientation
diff --git a/kornia/filters/__init__.py b/kornia/filters/__init__.py
index 2e7fcb870..cae7e6389 100644
--- a/kornia/filters/__init__.py
+++ b/kornia/filters/__init__.py
@@ -1,8 +1,8 @@
-from .blur import box_blur, BoxBlur
-from .blur_pool import blur_pool2d, BlurPool2D, max_blur_pool2d, MaxBlurPool2D
+from .blur import BoxBlur, box_blur
+from .blur_pool import BlurPool2D, MaxBlurPool2D, blur_pool2d, max_blur_pool2d
from .canny import Canny, canny
from .filter import filter2d, filter2D, filter2d_separable, filter3d, filter3D
-from .gaussian import gaussian_blur2d, GaussianBlur2d
+from .gaussian import GaussianBlur2d, gaussian_blur2d
from .kernels import (
gaussian,
get_binary_kernel2d,
@@ -21,10 +21,10 @@ from .kernels import (
)
from .kernels_geometry import get_motion_kernel2d, get_motion_kernel3d
from .laplacian import Laplacian, laplacian
-from .median import median_blur, MedianBlur
-from .motion import motion_blur, motion_blur3d, MotionBlur, MotionBlur3D
-from .sobel import Sobel, sobel, spatial_gradient, spatial_gradient3d, SpatialGradient, SpatialGradient3d
-from .unsharp import unsharp_mask, UnsharpMask
+from .median import MedianBlur, median_blur
+from .motion import MotionBlur, MotionBlur3D, motion_blur, motion_blur3d
+from .sobel import Sobel, SpatialGradient, SpatialGradient3d, sobel, spatial_gradient, spatial_gradient3d
+from .unsharp import UnsharpMask, unsharp_mask
__all__ = [
"gaussian",
diff --git a/kornia/filters/kernels_geometry.py b/kornia/filters/kernels_geometry.py
index 6bca901d9..f67bf1258 100644
--- a/kornia/filters/kernels_geometry.py
+++ b/kornia/filters/kernels_geometry.py
@@ -1,4 +1,4 @@
-from typing import cast, Tuple, Union
+from typing import Tuple, Union, cast
import torch
diff --git a/kornia/geometry/boxes.py b/kornia/geometry/boxes.py
index 19b64d32e..7d2a77ad4 100644
--- a/kornia/geometry/boxes.py
+++ b/kornia/geometry/boxes.py
@@ -1,4 +1,4 @@
-from typing import cast, List, Optional, Tuple, Union
+from typing import List, Optional, Tuple, Union, cast
import torch
diff --git a/kornia/geometry/camera/__init__.py b/kornia/geometry/camera/__init__.py
index 5bc6495d5..54c33d0d5 100644
--- a/kornia/geometry/camera/__init__.py
+++ b/kornia/geometry/camera/__init__.py
@@ -1,5 +1,5 @@
from .perspective import project_points, unproject_points
-from .pinhole import cam2pixel, PinholeCamera, pixel2cam
+from .pinhole import PinholeCamera, cam2pixel, pixel2cam
from .stereo import StereoCamera
__all__ = [
diff --git a/kornia/geometry/depth.py b/kornia/geometry/depth.py
index da4d49fa1..c7a03cb1d 100644
--- a/kornia/geometry/depth.py
+++ b/kornia/geometry/depth.py
@@ -8,7 +8,7 @@ import torch.nn.functional as F
from kornia.filters.sobel import spatial_gradient
from kornia.utils import create_meshgrid
-from .camera import cam2pixel, PinholeCamera, pixel2cam, project_points, unproject_points
+from .camera import PinholeCamera, cam2pixel, pixel2cam, project_points, unproject_points
from .conversions import normalize_pixel_coordinates
from .linalg import compose_transformations, convert_points_to_homogeneous, inverse_transformation, transform_points
diff --git a/kornia/geometry/epipolar/__init__.py b/kornia/geometry/epipolar/__init__.py
index 515e39ef0..0984e3e3f 100644
--- a/kornia/geometry/epipolar/__init__.py
+++ b/kornia/geometry/epipolar/__init__.py
@@ -17,9 +17,9 @@ from .fundamental import (
)
from .numeric import cross_product_matrix
from .projection import (
+ KRt_from_projection,
depth_from_point,
intrinsics_like,
- KRt_from_projection,
projection_from_KRt,
projections_from_fundamental,
random_intrinsics,
diff --git a/kornia/geometry/subpix/__init__.py b/kornia/geometry/subpix/__init__.py
index 62ea4cdd9..98936e403 100644
--- a/kornia/geometry/subpix/__init__.py
+++ b/kornia/geometry/subpix/__init__.py
@@ -1,14 +1,14 @@
from .dsnt import render_gaussian2d, spatial_expectation2d, spatial_softmax2d
-from .nms import nms2d, nms3d, NonMaximaSuppression2d, NonMaximaSuppression3d
+from .nms import NonMaximaSuppression2d, NonMaximaSuppression3d, nms2d, nms3d
from .spatial_soft_argmax import (
- conv_quad_interp3d,
- conv_soft_argmax2d,
- conv_soft_argmax3d,
ConvQuadInterp3d,
ConvSoftArgmax2d,
ConvSoftArgmax3d,
- spatial_soft_argmax2d,
SpatialSoftArgmax2d,
+ conv_quad_interp3d,
+ conv_soft_argmax2d,
+ conv_soft_argmax3d,
+ spatial_soft_argmax2d,
)
__all__ = [
diff --git a/kornia/losses/__init__.py b/kornia/losses/__init__.py
index 7da3980e2..6fe6ef28f 100644
--- a/kornia/losses/__init__.py
+++ b/kornia/losses/__init__.py
@@ -1,12 +1,12 @@
-from .depth_smooth import inverse_depth_smoothness_loss, InverseDepthSmoothnessLoss
-from .dice import dice_loss, DiceLoss
+from .depth_smooth import InverseDepthSmoothnessLoss, inverse_depth_smoothness_loss
+from .dice import DiceLoss, dice_loss
from .divergence import js_div_loss_2d, kl_div_loss_2d
-from .focal import binary_focal_loss_with_logits, BinaryFocalLossWithLogits, focal_loss, FocalLoss
+from .focal import BinaryFocalLossWithLogits, FocalLoss, binary_focal_loss_with_logits, focal_loss
from .hausdorff import HausdorffERLoss, HausdorffERLoss3D
-from .psnr import psnr_loss, PSNRLoss
-from .ssim import ssim_loss, SSIMLoss
-from .total_variation import total_variation, TotalVariation
-from .tversky import tversky_loss, TverskyLoss
+from .psnr import PSNRLoss, psnr_loss
+from .ssim import SSIMLoss, ssim_loss
+from .total_variation import TotalVariation, total_variation
+from .tversky import TverskyLoss, tversky_loss
__all__ = [
"inverse_depth_smoothness_loss",
diff --git a/kornia/metrics/__init__.py b/kornia/metrics/__init__.py
index ac19c5d59..319acccd9 100644
--- a/kornia/metrics/__init__.py
+++ b/kornia/metrics/__init__.py
@@ -4,7 +4,7 @@ from .confusion_matrix import confusion_matrix
from .mean_average_precision import mean_average_precision
from .mean_iou import mean_iou, mean_iou_bbox
from .psnr import psnr
-from .ssim import ssim, SSIM
+from .ssim import SSIM, ssim
__all__ = [
"accuracy",
diff --git a/kornia/utils/__init__.py b/kornia/utils/__init__.py
index 8ce5304f5..79692785b 100644
--- a/kornia/utils/__init__.py
+++ b/kornia/utils/__init__.py
@@ -1,7 +1,7 @@
from .draw import draw_line, draw_rectangle
from .grid import create_meshgrid, create_meshgrid3d
from .helpers import _extract_device_dtype, safe_inverse_with_mask, safe_solve_with_mask
-from .image import image_list_to_tensor, image_to_tensor, ImageToTensor, tensor_to_image
+from .image import ImageToTensor, image_list_to_tensor, image_to_tensor, tensor_to_image
from .memory import batched_forward
from .misc import eye_like, vec_like
from .one_hot import one_hot
diff --git a/kornia/utils/image.py b/kornia/utils/image.py
index 3e71fcd51..39e504b04 100644
--- a/kornia/utils/image.py
+++ b/kornia/utils/image.py
@@ -1,5 +1,5 @@
from functools import wraps
-from typing import Callable, List, TYPE_CHECKING
+from typing import TYPE_CHECKING, Callable, List
import torch
import torch.nn as nn
diff --git a/pyproject.toml b/pyproject.toml
index b2bc7352d..1f2e3fb90 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -2,3 +2,18 @@
line-length = 120
skip-string-normalization = true
skip-magic-trailing-comma = true
+
+[tool.isort]
+multi_line_output=3
+include_trailing_comma = true
+line_length = 120
+profile = "black"
+known_first_party = [
+ "examples",
+ "kornia",
+ "tests",
+]
+skip_glob = []
+skip = [
+ "kornia/__init__.py"
+]
diff --git a/test/augmentation/test_augmentation.py b/test/augmentation/test_augmentation.py
index dc4eb126d..3acd56923 100644
--- a/test/augmentation/test_augmentation.py
+++ b/test/augmentation/test_augmentation.py
@@ -30,10 +30,10 @@ from kornia.augmentation import (
RandomThinPlateSpline,
RandomVerticalFlip,
)
-from kornia.augmentation.base import AugmentationBase2D
-from kornia.constants import pi, Resample
+from kornia.augmentation._2d.base import AugmentationBase2D
+from kornia.constants import Resample, pi
from kornia.geometry import transform_points
-from kornia.testing import assert_close, BaseTester, default_with_one_parameter_changed
+from kornia.testing import BaseTester, assert_close, default_with_one_parameter_changed
from kornia.utils import create_meshgrid
from kornia.utils.helpers import _torch_inverse_cast
@@ -144,13 +144,15 @@ class CommonTests(BaseTester):
expected_transformation_shape = torch.Size((generated_params['batch_prob'].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)
+ test_input[generated_params['batch_prob']], generated_params
+ )
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:
output = augmentation.apply_transform(
- test_input[generated_params['batch_prob']], generated_params, transformation)
+ test_input[generated_params['batch_prob']], generated_params, transformation
+ )
assert output.shape[0] == generated_params['batch_prob'].sum()
else:
# Re-generate parameters if 0 batch size
diff --git a/test/augmentation/test_base.py b/test/augmentation/test_base.py
index 8f4d397a1..cb8906abc 100644
--- a/test/augmentation/test_base.py
+++ b/test/augmentation/test_base.py
@@ -5,7 +5,8 @@ import torch
from torch.autograd import gradcheck
import kornia.testing as utils # test utils
-from kornia.augmentation.base import _BasicAugmentationBase, AugmentationBase2D
+from kornia.augmentation._2d.base import AugmentationBase2D
+from kornia.augmentation.base import _BasicAugmentationBase
from kornia.testing import assert_close
diff --git a/test/augmentation/test_container.py b/test/augmentation/test_container.py
index a2708861f..1c93d8140 100644
--- a/test/augmentation/test_container.py
+++ b/test/augmentation/test_container.py
@@ -3,7 +3,7 @@ import torch
import kornia
import kornia.augmentation as K
-from kornia.augmentation.base import MixAugmentationBase
+from kornia.augmentation._2d.mix.base import MixAugmentationBase
from kornia.constants import BorderType
from kornia.geometry.bbox import bbox_to_mask
from kornia.testing import assert_close
@@ -154,14 +154,12 @@ class TestVideoSequential:
class TestSequential:
-
@pytest.mark.parametrize('random_apply_weights', [None, [0.8, 0.9]])
def test_exception(self, random_apply_weights, device, dtype):
inp = torch.randn(1, 3, 30, 30, device=device, dtype=dtype)
with pytest.raises(Exception): # AssertError and NotImplementedError
K.ImageSequential(
- K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0),
- random_apply_weights=random_apply_weights
+ K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0), random_apply_weights=random_apply_weights
).inverse(inp)
@pytest.mark.parametrize('same_on_batch', [True, False, None])
@@ -305,12 +303,12 @@ class TestAugmentationSequential:
def test_random_crops(self, device, dtype):
input = torch.randn(3, 3, 3, 3, device=device, dtype=dtype)
bbox = torch.tensor(
- [[[1.0, 1.0, 2.0, 2.0], [0.0, 0.0, 1.0, 2.0], [0.0, 0.0, 2.0, 1.0]]],
- device=device, dtype=dtype).expand(3, -1, -1)
+ [[[1.0, 1.0, 2.0, 2.0], [0.0, 0.0, 1.0, 2.0], [0.0, 0.0, 2.0, 1.0]]], device=device, dtype=dtype
+ ).expand(3, -1, -1)
points = torch.tensor([[[0.0, 0.0], [1.0, 1.0]]], device=device, dtype=dtype).expand(3, -1, -1)
aug = K.AugmentationSequential(
K.RandomCrop((3, 3), padding=1, cropping_mode='resample', fill=0),
- data_keys=["input", "mask", "bbox", "keypoints"]
+ data_keys=["input", "mask", "bbox_xyxy", "keypoints"],
)
reproducibility_test((input, input, bbox, points), aug)
@@ -318,19 +316,27 @@ class TestAugmentationSequential:
_params = aug.forward_parameters(input.shape)
# specifying the crops allows us to compute by hand the expected outputs
_params[0].data['src'] = torch.tensor(
- [[[1., 2.], [3., 2.], [3., 4.], [1., 4.]],
- [[1., 1.], [3., 1.], [3., 3.], [1., 3.]],
- [[2., 0.], [4., 0.], [4., 2.], [2., 2.]]],
- device=_params[0].data['src'].device, dtype=_params[0].data['src'].dtype)
+ [
+ [[1.0, 2.0], [3.0, 2.0], [3.0, 4.0], [1.0, 4.0]],
+ [[1.0, 1.0], [3.0, 1.0], [3.0, 3.0], [1.0, 3.0]],
+ [[2.0, 0.0], [4.0, 0.0], [4.0, 2.0], [2.0, 2.0]],
+ ],
+ device=_params[0].data['src'].device,
+ dtype=_params[0].data['src'].dtype,
+ )
expected_out_bbox = torch.tensor(
- [[[1., 0., 2., 1.], [0., -1., 1., 1.], [0., -1., 2., 0.]],
- [[1., 1., 2., 2.], [0., 0., 1., 2.], [0., 0., 2., 1.]],
- [[0., 2., 1., 3.], [-1., 1., 0., 3.], [-1., 1., 1., 2.]]], device=device, dtype=dtype)
+ [
+ [[1.0, 0.0, 2.0, 1.0], [0.0, -1.0, 1.0, 1.0], [0.0, -1.0, 2.0, 0.0]],
+ [[1.0, 1.0, 2.0, 2.0], [0.0, 0.0, 1.0, 2.0], [0.0, 0.0, 2.0, 1.0]],
+ [[0.0, 2.0, 1.0, 3.0], [-1.0, 1.0, 0.0, 3.0], [-1.0, 1.0, 1.0, 2.0]],
+ ],
+ device=device,
+ dtype=dtype,
+ )
expected_out_points = torch.tensor(
- [[[0., -1.], [1., 0.]],
- [[0., 0.], [1., 1.]],
- [[-1., 1.], [0., 2.]]], device=device, dtype=dtype)
+ [[[0.0, -1.0], [1.0, 0.0]], [[0.0, 0.0], [1.0, 1.0]], [[-1.0, 1.0], [0.0, 2.0]]], device=device, dtype=dtype
+ )
out = aug(input, input, bbox, points, params=_params)
assert out[0].shape == (3, 3, 3, 3)
@@ -471,10 +477,11 @@ class TestAugmentationSequential:
bbox = torch.tensor([[[355, 10], [660, 10], [660, 250], [355, 250]]], device=device, dtype=dtype)
bbox_2 = [
# torch.tensor([[[355, 10], [660, 10], [660, 250], [355, 250]]], device=device, dtype=dtype),
- torch.tensor([
- [[355, 10], [660, 10], [660, 250], [355, 250]],
- [[355, 10], [660, 10], [660, 250], [355, 250]]
- ], device=device, dtype=dtype)
+ torch.tensor(
+ [[[355, 10], [660, 10], [660, 250], [355, 250]], [[355, 10], [660, 10], [660, 250], [355, 250]]],
+ device=device,
+ dtype=dtype,
+ )
]
bbox_wh = torch.tensor([[[30, 40, 100, 100]]], device=device, dtype=dtype)
bbox_wh_2 = [
diff --git a/test/augmentation/test_random_generator.py b/test/augmentation/test_random_generator.py
index 99d885fd0..a6f849ca8 100644
--- a/test/augmentation/test_random_generator.py
+++ b/test/augmentation/test_random_generator.py
@@ -3,7 +3,6 @@ import torch
from kornia.augmentation.random_generator import (
AffineGenerator,
- center_crop_generator,
ColorJitterGenerator,
CropGenerator,
MotionBlurGenerator,
@@ -11,10 +10,11 @@ from kornia.augmentation.random_generator import (
PlainUniformGenerator,
PosterizeGenerator,
ProbabilityGenerator,
- random_cutmix_generator,
- random_mixup_generator,
RectangleEraseGenerator,
ResizedCropGenerator,
+ center_crop_generator,
+ random_cutmix_generator,
+ random_mixup_generator,
)
from kornia.testing import assert_close
from kornia.utils._compat import torch_version_geq
diff --git a/test/color/test_hls.py b/test/color/test_hls.py
index 736ea57d3..ea8ce0901 100644
--- a/test/color/test_hls.py
+++ b/test/color/test_hls.py
@@ -6,7 +6,7 @@ import torch
from torch.autograd import gradcheck
import kornia
-from kornia.testing import assert_close, BaseTester
+from kornia.testing import BaseTester, assert_close
from packaging import version
diff --git a/test/color/test_hsv.py b/test/color/test_hsv.py
index 533e4b5c5..a897c34dc 100644
--- a/test/color/test_hsv.py
+++ b/test/color/test_hsv.py
@@ -5,7 +5,7 @@ import torch
from torch.autograd import gradcheck
import kornia
-from kornia.testing import assert_close, BaseTester
+from kornia.testing import BaseTester, assert_close
class TestRgbToHsv(BaseTester):
diff --git a/test/color/test_lab.py b/test/color/test_lab.py
index 28d190252..8dd368c63 100644
--- a/test/color/test_lab.py
+++ b/test/color/test_lab.py
@@ -4,7 +4,7 @@ from torch.autograd import gradcheck
import kornia
import kornia.testing as utils
-from kornia.testing import assert_close, BaseTester
+from kornia.testing import BaseTester, assert_close
class TestRgbToLab(BaseTester):
diff --git a/test/color/test_luv.py b/test/color/test_luv.py
index 76b761a51..607622b38 100644
--- a/test/color/test_luv.py
+++ b/test/color/test_luv.py
@@ -3,7 +3,7 @@ import torch
from torch.autograd import gradcheck
import kornia
-from kornia.testing import _get_precision, assert_close, BaseTester
+from kornia.testing import BaseTester, _get_precision, assert_close
class TestRgbToLuv(BaseTester):
diff --git a/test/color/test_rgb.py b/test/color/test_rgb.py
index b4440c820..adfff93fb 100644
--- a/test/color/test_rgb.py
+++ b/test/color/test_rgb.py
@@ -3,7 +3,7 @@ import torch
from torch.autograd import gradcheck
import kornia
-from kornia.testing import assert_close, BaseTester
+from kornia.testing import BaseTester, assert_close
class TestRgbToBgr(BaseTester):
diff --git a/test/color/test_xyz.py b/test/color/test_xyz.py
index 9e7a956e1..fdd27b9de 100644
--- a/test/color/test_xyz.py
+++ b/test/color/test_xyz.py
@@ -3,7 +3,7 @@ import torch
from torch.autograd import gradcheck
import kornia
-from kornia.testing import assert_close, BaseTester
+from kornia.testing import BaseTester, assert_close
class TestRgbToXyz(BaseTester):
diff --git a/test/color/test_ycbcr.py b/test/color/test_ycbcr.py
index 13d543aed..06ca5b4b2 100644
--- a/test/color/test_ycbcr.py
+++ b/test/color/test_ycbcr.py
@@ -3,7 +3,7 @@ import torch
from torch.autograd import gradcheck
import kornia
-from kornia.testing import assert_close, BaseTester
+from kornia.testing import BaseTester, assert_close
class TestRgbToYcbcr(BaseTester):
diff --git a/test/color/test_yuv.py b/test/color/test_yuv.py
index 8f0a87d90..907ae201a 100644
--- a/test/color/test_yuv.py
+++ b/test/color/test_yuv.py
@@ -3,7 +3,7 @@ import torch
from torch.autograd import gradcheck
import kornia
-from kornia.testing import assert_close, BaseTester
+from kornia.testing import BaseTester, assert_close
class TestRgbToYuv(BaseTester):
diff --git a/test/enhance/test_adjust.py b/test/enhance/test_adjust.py
index 2d4d850f6..d84d1b0fe 100644
--- a/test/enhance/test_adjust.py
+++ b/test/enhance/test_adjust.py
@@ -5,7 +5,7 @@ from torch.autograd import gradcheck
import kornia
import kornia.testing as utils
from kornia.constants import pi
-from kornia.testing import assert_close, BaseTester, tensor_to_gradcheck_var
+from kornia.testing import BaseTester, assert_close, tensor_to_gradcheck_var
class TestInvert:
diff --git a/test/enhance/test_equalization.py b/test/enhance/test_equalization.py
index 00291f984..19fbd5316 100644
--- a/test/enhance/test_equalization.py
+++ b/test/enhance/test_equalization.py
@@ -6,7 +6,7 @@ from torch.autograd import gradcheck
from kornia import enhance
from kornia.geometry import rotate
-from kornia.testing import assert_close, BaseTester, tensor_to_gradcheck_var
+from kornia.testing import BaseTester, assert_close, tensor_to_gradcheck_var
class TestEqualization(BaseTester):
diff --git a/test/enhance/test_normalize.py b/test/enhance/test_normalize.py
index ed3a80bad..211d3589f 100644
--- a/test/enhance/test_normalize.py
+++ b/test/enhance/test_normalize.py
@@ -4,7 +4,7 @@ from torch.autograd import gradcheck
import kornia
import kornia.testing as utils # test utils
-from kornia.testing import assert_close, BaseTester
+from kornia.testing import BaseTester, assert_close
class TestNormalize:
diff --git a/test/feature/test_integrated.py b/test/feature/test_integrated.py
index aea63d281..491dec40d 100644
--- a/test/feature/test_integrated.py
+++ b/test/feature/test_integrated.py
@@ -9,14 +9,14 @@ import kornia
import kornia.testing as utils # test utils
from kornia.feature import (
DescriptorMatcher,
- extract_patches_from_pyramid,
- get_laf_descriptors,
GFTTAffNetHardNet,
LAFDescriptor,
LocalFeature,
ScaleSpaceDetector,
SIFTDescriptor,
SIFTFeature,
+ extract_patches_from_pyramid,
+ get_laf_descriptors,
)
from kornia.feature.integrated import LocalFeatureMatcher
from kornia.geometry import RANSAC, resize, transform_points
diff --git a/test/feature/test_mkd.py b/test/feature/test_mkd.py
index 9b0cac8b2..ff6d2c5b3 100644
--- a/test/feature/test_mkd.py
+++ b/test/feature/test_mkd.py
@@ -9,14 +9,14 @@ from kornia.feature.mkd import (
COEFFS,
EmbedGradients,
ExplicitSpacialEncoding,
- get_grid_dict,
- get_kron_order,
MKDDescriptor,
MKDGradients,
SimpleKD,
- spatial_kernel_embedding,
VonMisesKernel,
Whitening,
+ get_grid_dict,
+ get_kron_order,
+ spatial_kernel_embedding,
)
from kornia.testing import assert_close
diff --git a/test/feature/test_siftdesc.py b/test/feature/test_siftdesc.py
index cd43d61fa..08b5b0950 100644
--- a/test/feature/test_siftdesc.py
+++ b/test/feature/test_siftdesc.py
@@ -3,7 +3,7 @@ import torch
from torch.autograd import gradcheck
import kornia.testing as utils # test utils
-from kornia.feature.siftdesc import get_sift_bin_ksize_stride_pad, get_sift_pooling_kernel, SIFTDescriptor
+from kornia.feature.siftdesc import SIFTDescriptor, get_sift_bin_ksize_stride_pad, get_sift_pooling_kernel
from kornia.testing import assert_close
diff --git a/test/test_contrib.py b/test/test_contrib.py
index b90b0ccc5..4716ef1b2 100644
--- a/test/test_contrib.py
+++ b/test/test_contrib.py
@@ -1,4 +1,4 @@
-from unittest.mock import patch, PropertyMock
+from unittest.mock import PropertyMock, patch
import pytest
import torch