Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Augmentation Base Refactor (#2117)

Jian Shi80164c7b6e3c
diff --git a/docs/source/augmentation.base.rst b/docs/source/augmentation.base.rst
index b52f42aef..8424cec7c 100644
--- a/docs/source/augmentation.base.rst
+++ b/docs/source/augmentation.base.rst
@@ -3,57 +3,136 @@ Base Classes
.. currentmodule:: kornia.augmentation
-This is the base class for creating a new transform using `kornia.augmentation`.
-The user only needs to override: `generate_parameters`, `apply_transform` and optionally, `compute_transformation`.
+This is the base class for creating a new transform on top the predefined routine of `kornia.augmentation`.
+Specifically, an any given augmentation can be recognized as either rigid (e.g. affine transformations that
+manipulate images with standard transformation matrice), or non-rigid (e.g. cut out a random area). At
+image-level, Kornia supports rigid transformation like `GeometricAugmentationBase2D` that modifies the geometric
+location of image pixels and `IntensityAugmentationBase2D` that preserves the pixel locations, as well as
+generic `AugmentationBase2D` that allows higher freedom for customized augmentation design.
+
+
+The Predefined Augmentation Routine
+-----------------------------------
+
+Kornia augmentation follows the simplest `sample-apply` routine for all the augmentations.
+
+- `sample`: Kornia aims at flexible tensor-level augmentations that augment all images in a tensor with
+ different augmentations and probabilities. The sampling operation firstly samples a suite of random
+ parameters. Then all the sampled augmentation state (parameters) is stored
+ inside `_param` of the augmentation, the users can hereby reproduce the same augmentation results.
+- `apply`: With generated or passed parameters, the augmentation will be performed accordingly.
+ Apart from performing image tensor operations, Kornia also supports inverse operations that
+ to revert the transform operations. Meanwhile, other data modalities (`datakeys` in Kornia) like
+ masks, keypoints, and bounding boxes. Such features are better supported with `AugmentationSequential`.
+ Notably, the augmentation pipeline for rigid operations are implemented already without further efforts.
+ For non-rigid operations, the user may implement customized inverse and data modality operations, e.g.
+ `apply_mask_transform` for applying transformations on mask tensors.
+
+
+Custom Augmentation Classes
+---------------------------
+
+For rigid transformations, `IntensityAugmentationBase2D` and `GeometricAugmentationBase2D` are sharing the exact same logic
+apart from the transformation matrix computations. Namely, the intensity augmentation always results in
+identity transformation matrices, without changing the geometric location for each pixel.
+
+If it is a rigid geometric operation, `compute_transformation` and `apply_transform` need to be implemented, as well as
+`compute_inverse_transformation` and `inverse_transform` to compute its inverse.
+
+.. autoclass:: GeometricAugmentationBase2D
+
+ .. automethod:: compute_transformation
+ .. automethod:: apply_transform
+ .. automethod:: compute_inverse_transformation
+ .. automethod:: inverse_transform
+
+
+For `IntensityAugmentationBase2D`, the user only needs to override `apply_transform`.
+
+.. autoclass:: IntensityAugmentationBase2D
+
+ .. automethod:: apply_transform
+
+A minimal example to create your own rigid geometric augmentations with the following snippet:
-Create your own transformations with the following snippet:
.. code-block:: python
import torch
import kornia as K
- from kornia.augmentation import AugmentationBase2D
+ from kornia.augmentation import GeometricAugmentationBase2D
+ from kornia.augmentation import random_generator as rg
- class MyRandomTransform(AugmentationBase2D):
- def __init__(self, return_transform: bool = False) -> None:
- super(MyRandomTransform, self).__init__(return_transform)
- def generate_parameters(self, input_shape: torch.Size):
- # generate the random parameters for your use case.
- angles_rad torch.Tensor = torch.rand(input_shape[0]) * K.pi
- angles_deg = kornia.rad2deg(angles_rad)
- return dict(angles=angles_deg)
+ class MyRandomTransform(GeometricAugmentationBase2D):
- def compute_transformation(self, input, params):
+ def __init__(
+ self,
+ factor=(0., 1.),
+ same_on_batch: bool = False,
+ p: float = 1.0,
+ keepdim: bool = False,
+ ) -> None:
+ super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)
+ self._param_generator = rg.PlainUniformGenerator((factor, "factor", None, None))
- B, _, H, W = input.shape
+ def compute_transformation(self, input, params):
+ # a simple identity transformation example
+ factor = params["factor"].to(input) * 0. + 1
+ return K.eyelike(input, 3) * factor
- # compute transformation
- angles: torch.Tensor = params['angles'].type_as(input)
- center = torch.tensor([[W / 2, H / 2]] * B).type_as(input)
- transform = K.get_rotation_matrix2d(
- center, angles, torch.ones_like(angles))
- return transform
+ def apply_transform(
+ self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
+ ) -> Tensor:
+ factor = params["factor"].to(input)
+ return input * factor
- def apply_transform(self, input, params):
- _, _, H, W = input.shape
- # compute transformation
- transform = self.compute_transformation(input, params)
+For non-rigid augmentations, the user may implement the `apply_transform*` and `apply_non_transform*` APIs
+to meet the needs. Specifically, `apply_transform*` applies to the elements of a tensor that need to be transformed,
+while `apply_non_transform*` applies to the elements of a tensor that are skipped from augmentation. For example,
+a crop operation may change the tensor size partially, while we need to resize the rest to maintain the whole tensor
+as an integrated one with the same size.
- # apply transformation and return
- output = K.warp_affine(input, transform, (H, W))
- return (output, transform)
.. autoclass:: AugmentationBase2D
- .. automethod:: generate_parameters
- .. automethod:: compute_transformation
.. automethod:: apply_transform
+ .. automethod:: apply_non_transform
+ .. automethod:: apply_transform_mask
+ .. automethod:: apply_non_transform_mask
+ .. automethod:: apply_transform_box
+ .. automethod:: apply_non_transform_box
+ .. automethod:: apply_transform_keypoint
+ .. automethod:: apply_non_transform_keypoint
+ .. automethod:: apply_transform_class
+ .. automethod:: apply_non_transform_class
-.. autoclass:: AugmentationBase3D
- .. automethod:: generate_parameters
- .. automethod:: compute_transformation
- .. automethod:: apply_transform
+The similar logic applies to 3D augmentations as well.
+
+
+Some Further Notes
+------------------
+
+Probabilities
+^^^^^^^^^^^^^
+Kornia supports two types of randomness for element-level randomness `p` and batch-level randomness `p_batch`,
+as in `_BasicAugmentationBase`. Under the hood, operations like `crop`, `resize` are implemented with a fixed
+element-level randomness of `p=1` that only maintains batch-level randomness.
+
+
+Random Generators
+^^^^^^^^^^^^^^^^^
+For automatically generating the corresponding ``__repr__`` with full customized parameters, you may need to
+implement ``_param_generator`` by inheriting ``RandomGeneratorBase`` for generating random parameters and
+put all static parameters inside ``self.flags``. You may take the advantage of ``PlainUniformGenerator`` to
+generate simple uniform parameters with less boilerplate code.
+
+
+Random Reproducibility
+^^^^^^^^^^^^^^^^^^^^^^
+Plain augmentation base class without the functionality of transformation matrix calculations.
+By default, the random computations will be happened on CPU with ``torch.get_default_dtype()``.
+To change this behaviour, please use ``set_rng_device_and_dtype``.
diff --git a/kornia/augmentation/_2d/base.py b/kornia/augmentation/_2d/base.py
index 0b3116c9a..a8f983902 100644
--- a/kornia/augmentation/_2d/base.py
+++ b/kornia/augmentation/_2d/base.py
@@ -1,15 +1,20 @@
+from typing import Any, Dict, Optional
+
from torch import Tensor, float16, float32, float64
-import kornia
from kornia.augmentation.base import _AugmentationBase
from kornia.augmentation.utils import _transform_input, _validate_input_dtype
+from kornia.geometry.boxes import Boxes
+from kornia.geometry.keypoints import Keypoints
+from kornia.utils import eye_like
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.
+ AugmentationBase2D aims at offering a generic base class for a greater level of customization.
+ If the subclass contains routined matrix-based transformations, `RigidAffineAugmentationBase2D`
+ might be a better fit.
Args:
p: probability for applying an augmentation. This param controls the augmentation probabilities
@@ -21,27 +26,104 @@ class AugmentationBase2D(_AugmentationBase):
form ``False``.
"""
- def __check_batching__(self, input: Tensor):
- 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 validate_tensor(self, input: Tensor) -> None:
+ """Check if the input tensor is formatted as expected."""
+ _validate_input_dtype(input, accepted_dtypes=[float16, float32, float64])
+ if len(input.shape) != 4:
+ raise RuntimeError(f"Expect (B, C, H, W). Got {input.shape}.")
def transform_tensor(self, input: Tensor) -> 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=[float16, float32, float64])
return _transform_input(input)
+
+class RigidAffineAugmentationBase2D(AugmentationBase2D):
+ r"""AugmentationBase2D base class for rigid/affine augmentation implementations.
+
+ RigidAffineAugmentationBase2D enables routined transformation with given transformation matrices
+ for different data types like masks, boxes, and keypoints.
+
+ 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.
+ 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``.
+ """
+
+ _transform_matrix: Optional[Tensor]
+
+ @property
+ def transform_matrix(self) -> Optional[Tensor]:
+ return self._transform_matrix
+
def identity_matrix(self, input) -> Tensor:
"""Return 3x3 identity matrix."""
- return kornia.eye_like(3, input)
+ return eye_like(3, input)
+
+ def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
+ raise NotImplementedError
+
+ def generate_transformation_matrix(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
+ """Generate transformation matrices with the given input and param settings."""
+ # Note about the explicit type conversions here:
+ # If this code is run in an autocast-enabled region, the transformation matrix or the output
+ # may be float16 even though the input was float32 (e.g. torch.mm produces float16 output),
+ # see also the documentation on autocasting: https://pytorch.org/docs/stable/amp.html.
+ # It may be unexpected for the user if the output type changes and it can also lead to errors
+ # for the index_put operation below (see also https://github.com/kornia/kornia/issues/1737)
+ # In case the type already matches the input type, the conversions are no-ops
+
+ to_apply = params['batch_prob']
+ in_tensor = self.transform_tensor(input)
+ if not to_apply.any():
+ trans_matrix = self.identity_matrix(in_tensor)
+ elif to_apply.all():
+ trans_matrix = self.compute_transformation(in_tensor, params=params, flags=flags).type(in_tensor.dtype)
+ else:
+ trans_matrix = self.identity_matrix(in_tensor)
+ trans_matrix = trans_matrix.index_put(
+ (to_apply,),
+ self.compute_transformation(in_tensor[to_apply], params=params, flags=flags).type(in_tensor.dtype),
+ )
+ return trans_matrix.type(in_tensor.dtype)
+
+ def inverse_inputs(
+ self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
+ ) -> Tensor:
+ raise NotImplementedError
+
+ def inverse_masks(
+ self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
+ ) -> Tensor:
+ raise NotImplementedError
+
+ def inverse_boxes(
+ self, input: Boxes, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
+ ) -> Boxes:
+ raise NotImplementedError
+
+ def inverse_keypoints(
+ self, input: Keypoints, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
+ ) -> Keypoints:
+ raise NotImplementedError
+
+ def inverse_classes(
+ self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
+ ) -> Tensor:
+ raise NotImplementedError
+
+ def apply_func(
+ self, in_tensor: Tensor, params: Dict[str, Tensor], flags: Optional[Dict[str, Any]] = None
+ ) -> Tensor:
+ if flags is None:
+ flags = self.flags
+
+ trans_matrix = self.generate_transformation_matrix(in_tensor, params, flags)
+ output = self.transform_inputs(in_tensor, params, flags, trans_matrix)
+ self._transform_matrix = trans_matrix
+
+ return output
diff --git a/kornia/augmentation/_2d/geometric/affine.py b/kornia/augmentation/_2d/geometric/affine.py
index bd169514a..9da954ee6 100644
--- a/kornia/augmentation/_2d/geometric/affine.py
+++ b/kornia/augmentation/_2d/geometric/affine.py
@@ -88,9 +88,8 @@ class RandomAffine(GeometricAugmentationBase2D):
padding_mode: Union[str, int, SamplePadding] = SamplePadding.ZEROS.name,
p: float = 0.5,
keepdim: bool = False,
- return_transform: Optional[bool] = None,
) -> None:
- super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
+ super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)
self._param_generator: 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
diff --git a/kornia/augmentation/_2d/geometric/base.py b/kornia/augmentation/_2d/geometric/base.py
index 1e42608d4..a4cd21cce 100644
--- a/kornia/augmentation/_2d/geometric/base.py
+++ b/kornia/augmentation/_2d/geometric/base.py
@@ -1,13 +1,15 @@
import warnings
from typing import Any, Dict, Optional, Tuple
-from kornia.augmentation._2d.base import AugmentationBase2D
-from kornia.augmentation.utils import override_parameters
+from kornia.augmentation._2d.base import RigidAffineAugmentationBase2D
+from kornia.constants import Resample
from kornia.core import Tensor, as_tensor
+from kornia.geometry.boxes import Boxes
+from kornia.geometry.keypoints import Keypoints
from kornia.utils.helpers import _torch_inverse_cast
-class GeometricAugmentationBase2D(AugmentationBase2D):
+class GeometricAugmentationBase2D(RigidAffineAugmentationBase2D):
r"""GeometricAugmentationBase2D base class for customized geometric augmentation implementations.
Args:
@@ -37,78 +39,247 @@ class GeometricAugmentationBase2D(AugmentationBase2D):
def get_transformation_matrix(
self, input: Tensor, params: Optional[Dict[str, Tensor]] = None, flags: Optional[Dict[str, Any]] = None
) -> Tensor:
+ """Obtain transformation matrices.
+
+ Return the current transformation matrix if existed. Generate a new one, otherwise.
+ """
flags = self.flags if flags is None else flags
if params is not None:
- transform = self.compute_transformation(input[params['batch_prob']], params=params, flags=flags)
-
+ transform = self.generate_transformation_matrix(input, params, flags)
elif self.transform_matrix is None:
params = self.forward_parameters(input.shape)
- transform = self.identity_matrix(input)
- transform[params['batch_prob']] = self.compute_transformation(
- input[params['batch_prob']], params=params, flags=flags
- )
+ transform = self.generate_transformation_matrix(input, params, flags)
else:
transform = self.transform_matrix
return as_tensor(transform, device=input.device, dtype=input.dtype)
- def inverse(
+ def apply_non_transform_mask(
+ self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
+ ) -> Tensor:
+ """Process masks corresponding to the inputs that are no transformation applied."""
+ return input
+
+ def apply_transform_mask(
+ self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
+ ) -> Tensor:
+ """Process masks corresponding to the inputs that are transformed.
+
+ Note:
+ Convert "resample" arguments to "nearest" by default.
+ """
+ resample_method: Optional[Resample]
+ if "resample" in flags:
+ resample_method = flags["resample"]
+ flags["resample"] = Resample.get("nearest")
+ output = self.apply_transform(input, params, flags, transform)
+ if resample_method is not None:
+ flags["resample"] = resample_method
+ return output
+
+ def apply_non_transform_box(
+ self, input: Boxes, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
+ ) -> Boxes:
+ """Process boxes corresponding to the inputs that are no transformation applied."""
+ return input
+
+ def apply_transform_box(
+ self, input: Boxes, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
+ ) -> Boxes:
+ """Process boxes corresponding to the inputs that are transformed."""
+ if transform is None:
+ if self.transform_matrix is None:
+ raise RuntimeError("No valid transformation matrix found. Please either pass one or forward one first.")
+ transform = self.transform_matrix
+ input = self.apply_non_transform_box(input, params, flags, transform)
+ return input.transform_boxes_(transform)
+
+ def apply_non_transform_keypoint(
+ self, input: Keypoints, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
+ ) -> Keypoints:
+ """Process keypoints corresponding to the inputs that are no transformation applied."""
+ return input
+
+ def apply_transform_keypoint(
+ self, input: Keypoints, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
+ ) -> Keypoints:
+ """Process keypoints corresponding to the inputs that are transformed."""
+ if transform is None:
+ if self.transform_matrix is None:
+ raise RuntimeError("No valid transformation matrix found. Please either pass one or forward one first.")
+ transform = self.transform_matrix
+ input = self.apply_non_transform_keypoint(input, params, flags, transform)
+ return input.transform_keypoints_(transform)
+
+ def apply_non_transform_class(
+ self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
+ ) -> Tensor:
+ """Process class tags corresponding to the inputs that are no transformation applied."""
+ return input
+
+ def apply_transform_class(
+ self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
+ ) -> Tensor:
+ """Process class tags corresponding to the inputs that are transformed."""
+ return input
+
+ def inverse_inputs(
self,
input: Tensor,
- params: Optional[Dict[str, Tensor]] = None,
- size: Optional[Tuple[int, int]] = None,
+ params: Dict[str, Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[Tensor] = None,
+ **kwargs,
+ ) -> Tensor:
+ in_tensor = self.transform_tensor(input)
+ output = in_tensor.clone()
+ to_apply = params['batch_prob']
+
+ params, flags = self._process_kwargs_to_params_and_flags(
+ self._params if params is None else params, flags, **kwargs
+ )
+
+ size = None
+ if "forward_input_shape" in params:
+ # Majorly for cropping functions
+ size = params['forward_input_shape'].numpy().tolist()
+ size = (size[-2], size[-1])
+
+ # if no augmentation needed
+ if not to_apply.any():
+ output = in_tensor
+ # if all data needs to be augmented
+ elif to_apply.all():
+ output = self.inverse_transform(in_tensor, flags=flags, transform=transform, size=size)
+ else:
+ output[to_apply] = self.inverse_transform(
+ in_tensor[to_apply],
+ transform=transform[to_apply] if transform is not None else transform,
+ size=size,
+ flags=flags,
+ )
+ return output
+
+ def inverse_masks(
+ self,
+ input: Tensor,
+ params: Dict[str, Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[Tensor] = None,
**kwargs,
) -> Tensor:
+ resample_method: Optional[Resample]
+ if "resample" in flags:
+ resample_method = flags["resample"]
+ flags["resample"] = Resample.get("nearest")
+ output = self.inverse_inputs(input, params, flags, transform, **kwargs)
+ if resample_method is not None:
+ flags["resample"] = resample_method
+ return output
+
+ def inverse_boxes(
+ self,
+ input: Boxes,
+ params: Dict[str, Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[Tensor] = None,
+ **kwargs,
+ ) -> Boxes:
+ output = input.clone()
+ to_apply = params['batch_prob']
+
+ if transform is None:
+ raise RuntimeError("transform matrix shall not be `None`.")
+
+ params, flags = self._process_kwargs_to_params_and_flags(
+ self._params if params is None else params, flags, **kwargs
+ )
+
+ # if no augmentation needed
+ if not to_apply.any():
+ output = input
+ # if all data needs to be augmented
+ elif to_apply.all():
+ output = input.transform_boxes_(transform)
+ else:
+ output[to_apply] = input[to_apply].transform_boxes_(transform[to_apply])
+
+ return output
+
+ def inverse_keypoints(
+ self,
+ input: Keypoints,
+ params: Dict[str, Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[Tensor] = None,
+ **kwargs,
+ ) -> Keypoints:
+ """Inverse the transformation on keypoints.
+
+ Args:
+ input: input keypoints tensor or object.
+ params: the corresponding parameters for an operation.
+ flags: static parameters.
+ transform: the inverse tansformation matrix
+ """
+ output = input.clone()
+ to_apply = params['batch_prob']
+
+ if transform is None:
+ raise RuntimeError("transform matrix shall not be `None`.")
+
+ params, flags = self._process_kwargs_to_params_and_flags(
+ self._params if params is None else params, flags, **kwargs
+ )
+
+ # if no augmentation needed
+ if not to_apply.any():
+ output = input
+ # if all data needs to be augmented
+ elif to_apply.all():
+ output = input.transform_keypoints_(transform)
+ else:
+ output[to_apply] = input[to_apply].transform_keypoints_(transform[to_apply])
+
+ return output
+
+ def inverse_classes(
+ self,
+ input: Tensor,
+ params: Dict[str, Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[Tensor] = None,
+ **kwargs,
+ ) -> Tensor:
+ return input
+
+ def inverse(self, input: Tensor, params: Optional[Dict[str, Tensor]] = None, **kwargs) -> Tensor:
"""Perform inverse operations.
Args:
input: the input tensor.
params: the corresponding parameters for an operation.
If None, a new parameter suite will be generated.
- size: input size during the forward step to restore the original shape.
**kwargs: key-value pairs to override the parameters and flags.
"""
input_shape = input.shape
in_tensor = self.transform_tensor(input)
batch_shape = input.shape
- if len(kwargs.keys()) != 0:
- _src_params = self._params if params is None else params
- params = override_parameters(_src_params, kwargs, in_place=False)
- flags = override_parameters(self.flags, kwargs, in_place=False)
- else:
- flags = self.flags
+ params, flags = self._process_kwargs_to_params_and_flags(
+ self._params if params is None else params, self.flags, **kwargs
+ )
- if params is not None:
- transform = self.identity_matrix(in_tensor)
- transform[params['batch_prob']] = self.compute_transformation(
- in_tensor[params['batch_prob']], params=params, flags=flags
- )
- else:
- # Avoid recompute.
- transform = self.get_transformation_matrix(in_tensor, params=params, flags=flags)
+ if params is None:
params = self._params
+ transform = self.get_transformation_matrix(in_tensor, params=params, flags=flags)
- 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'] = as_tensor([True] * batch_shape[0])
warnings.warn("`batch_prob` is not found in params. Will assume applying on all data.")
- output = in_tensor.clone()
- to_apply = params['batch_prob']
- # if no augmentation needed
- if not to_apply.any():
- output = in_tensor
- # if all data needs to be augmented
- elif to_apply.all():
- transform = self.compute_inverse_transformation(transform)
- output = self.inverse_transform(in_tensor, flags=flags, transform=transform, size=size)
- else:
- transform[to_apply] = self.compute_inverse_transformation(transform[to_apply])
- output[to_apply] = self.inverse_transform(
- in_tensor[to_apply], transform=transform[to_apply], size=size, flags=flags
- )
+
+ transform = self.compute_inverse_transformation(transform)
+ output = self.inverse_inputs(in_tensor, params, flags, transform)
+
if self.keepdim:
return self.transform_output_tensor(output, input_shape)
diff --git a/kornia/augmentation/_2d/geometric/center_crop.py b/kornia/augmentation/_2d/geometric/center_crop.py
index df8848bf1..6b30186fe 100644
--- a/kornia/augmentation/_2d/geometric/center_crop.py
+++ b/kornia/augmentation/_2d/geometric/center_crop.py
@@ -70,11 +70,10 @@ class CenterCrop(GeometricAugmentationBase2D):
p: float = 1.0,
keepdim: bool = False,
cropping_mode: str = "slice",
- return_transform: Optional[bool] = None,
) -> 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)
+ super().__init__(p=1.0, same_on_batch=True, p_batch=p, keepdim=keepdim)
if isinstance(size, tuple):
self.size = (size[0], size[1])
elif isinstance(size, int):
diff --git a/kornia/augmentation/_2d/geometric/crop.py b/kornia/augmentation/_2d/geometric/crop.py
index 4e5a1f252..560156bc9 100644
--- a/kornia/augmentation/_2d/geometric/crop.py
+++ b/kornia/augmentation/_2d/geometric/crop.py
@@ -4,9 +4,10 @@ import torch
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
-from kornia.augmentation.utils import _transform_input, _transform_output_shape, override_parameters
from kornia.constants import Resample
from kornia.core import Tensor, pad, tensor
+from kornia.geometry.boxes import Boxes
+from kornia.geometry.keypoints import Keypoints
from kornia.geometry.transform import crop_by_indices, crop_by_transform_mat, get_perspective_transform
@@ -84,12 +85,9 @@ class RandomCrop(GeometricAugmentationBase2D):
p: float = 1.0,
keepdim: bool = False,
cropping_mode: str = "slice",
- return_transform: Optional[bool] = None,
) -> 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
- )
+ super().__init__(p=1.0, same_on_batch=same_on_batch, p_batch=p, keepdim=keepdim)
self._param_generator = rg.CropGenerator(size)
self.flags = dict(
size=size,
@@ -152,9 +150,32 @@ class RandomCrop(GeometricAugmentationBase2D):
return transform
raise NotImplementedError(f"Not supported type: {flags['cropping_mode']}.")
+ def apply_transform_keypoint(
+ self, input: Keypoints, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
+ ) -> Keypoints:
+ """Process keypoints corresponding to the inputs that are no transformation applied."""
+ # For pad the keypoints properly.
+ padding_size = params["padding_size"]
+ input = input.pad(padding_size)
+ return super().apply_transform_keypoint(input=input, params=params, flags=flags, transform=transform)
+
+ def apply_transform_box(
+ self, input: Boxes, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
+ ) -> Boxes:
+ """Process keypoints corresponding to the inputs that are no transformation applied."""
+ # For pad the boxes properly.
+ padding_size = params["padding_size"]
+ input = input.pad(padding_size)
+ return super().apply_transform_box(input=input, params=params, flags=flags, transform=transform)
+
def apply_transform(
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
) -> Tensor:
+ padding_size: Optional[List[int]] = None
+ if "padding_size" in params and isinstance(params["padding_size"], Tensor):
+ padding_size = params["padding_size"].unique(dim=0).cpu().squeeze().numpy().tolist()
+ input = self.precrop_padding(input, padding_size, flags)
+
flags = self.flags if flags is None else flags
if flags["cropping_mode"] == "resample": # uses bilinear interpolation to crop
transform = cast(Tensor, transform)
@@ -211,24 +232,63 @@ class RandomCrop(GeometricAugmentationBase2D):
align_corners=flags["align_corners"],
)
- def inverse(
+ def inverse_inputs(
self,
input: Tensor,
- params: Optional[Dict[str, Tensor]] = None,
- size: Optional[Tuple[int, int]] = None,
+ params: Dict[str, Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[Tensor] = None,
**kwargs,
) -> 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]
+ if flags["cropping_mode"] != "resample":
+ raise NotImplementedError(
+ f"`inverse` is only applicable for resample cropping mode. Got {flags['cropping_mode']}."
+ )
+ out = super().inverse_inputs(input, params, flags, transform, **kwargs)
+ if not params["batch_prob"].all():
+ return out
+ 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]]
return self.precrop_padding(out, padding_size)
- def forward_parameters_precrop(self, batch_shape) -> Dict[str, Tensor]:
+ def inverse_boxes(
+ self,
+ input: Boxes,
+ params: Dict[str, Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[Tensor] = None,
+ **kwargs,
+ ) -> Boxes:
+ if flags["cropping_mode"] != "resample":
+ raise NotImplementedError(
+ f"`inverse` is only applicable for resample cropping mode. Got {flags['cropping_mode']}."
+ )
+ output = super().inverse_boxes(input, params, flags, transform, **kwargs)
+ if not params["batch_prob"].all():
+ return output
+
+ return output.unpad(params["padding_size"])
+
+ def inverse_keypoints(
+ self,
+ input: Keypoints,
+ params: Dict[str, Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[Tensor] = None,
+ **kwargs,
+ ) -> Keypoints:
+ if flags["cropping_mode"] != "resample":
+ raise NotImplementedError(
+ f"`inverse` is only applicable for resample cropping mode. Got {flags['cropping_mode']}."
+ )
+ output = super().inverse_keypoints(input, params, flags, transform, **kwargs)
+ if not params["batch_prob"].all():
+ return output
+
+ return output.unpad(params["padding_size"])
+
+ # Override parameters for precrop
+ def forward_parameters(self, batch_shape) -> Dict[str, Tensor]:
input_pad = self.compute_padding(batch_shape)
batch_shape_new = (
*batch_shape[:2],
@@ -239,44 +299,3 @@ class RandomCrop(GeometricAugmentationBase2D):
_params = super().forward_parameters(batch_shape_new)
_params.update({"padding_size": padding_size})
return _params
-
- def forward(self, input: Tensor, params: Optional[Dict[str, Tensor]] = None, **kwargs) -> Tensor:
- 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
-
- flags = override_parameters(self.flags, kwargs, in_place=False)
-
- if isinstance(input, (tuple, list)):
- ori_shape = input[0].shape
- input_temp = _transform_input(input[0])
- input_pad = self.compute_padding(input[0].shape, flags) if input_pad is None else input_pad
- _input = (self.precrop_padding(input_temp, input_pad, flags), input[1])
- _input = _transform_output_shape(_input, ori_shape) if self.keepdim else _input
- else:
- ori_shape = input.shape
- input_temp = _transform_input(input)
- input_pad = self.compute_padding(input_temp.shape, flags) if input_pad is None else input_pad
- _input = self.precrop_padding(input_temp, input_pad, flags)
- _input = _transform_output_shape(_input, ori_shape) if self.keepdim else _input
- if params is not None:
- params, flags = self._process_kwargs_to_params_and_flags(params, self.flags, **kwargs)
- out = super().forward(_input, params, **kwargs)
-
- # Update the actual input size for inverse
- if "padding_size" not in self._params:
- _padding_size = 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
index b491ab836..4bb102b10 100644
--- a/kornia/augmentation/_2d/geometric/elastic_transform.py
+++ b/kornia/augmentation/_2d/geometric/elastic_transform.py
@@ -3,12 +3,13 @@ from typing import Any, Dict, Optional, Tuple, Union
import torch
from torch import Tensor
-from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
+from kornia.augmentation._2d.base import AugmentationBase2D
from kornia.constants import Resample
+from kornia.geometry.boxes import Boxes
from kornia.geometry.transform import elastic_transform2d
-class RandomElasticTransform(GeometricAugmentationBase2D):
+class RandomElasticTransform(AugmentationBase2D):
r"""Add random elastic transformation to a tensor image.
.. image:: _static/img/RandomElasticTransform.png
@@ -57,11 +58,8 @@ class RandomElasticTransform(GeometricAugmentationBase2D):
same_on_batch: bool = False,
p: float = 0.5,
keepdim: bool = False,
- return_transform: Optional[bool] = None,
) -> None:
- super().__init__(
- p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim
- )
+ super().__init__(p=p, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim)
self.flags = dict(
kernel_size=kernel_size,
@@ -80,10 +78,6 @@ class RandomElasticTransform(GeometricAugmentationBase2D):
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: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
- return self.identity_matrix(input)
-
def apply_transform(
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
) -> Tensor:
@@ -97,3 +91,22 @@ class RandomElasticTransform(GeometricAugmentationBase2D):
flags["resample"].name.lower(),
flags["padding_mode"],
)
+
+ def apply_transform_mask(
+ self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
+ ) -> Tensor:
+ """Process masks corresponding to the inputs that are transformed."""
+ return self.apply_transform(input, params=params, flags=flags, transform=transform)
+
+ def apply_transform_box(
+ self, input: Boxes, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
+ ) -> Boxes:
+ """Process masks corresponding to the inputs that are transformed."""
+ # We assume that boxes may not be affected too much by the deformation.
+ return input
+
+ def apply_transform_class(
+ self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
+ ) -> Tensor:
+ """Process class tags corresponding to the inputs that are transformed."""
+ return input
diff --git a/kornia/augmentation/_2d/geometric/fisheye.py b/kornia/augmentation/_2d/geometric/fisheye.py
index b655e6300..4fd1c5c4a 100644
--- a/kornia/augmentation/_2d/geometric/fisheye.py
+++ b/kornia/augmentation/_2d/geometric/fisheye.py
@@ -1,13 +1,13 @@
from typing import Any, Dict, Optional
from kornia.augmentation import random_generator as rg
-from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
+from kornia.augmentation._2d.base import AugmentationBase2D
from kornia.core import Tensor
from kornia.geometry.transform import remap
from kornia.utils import create_meshgrid
-class RandomFisheye(GeometricAugmentationBase2D):
+class RandomFisheye(AugmentationBase2D):
r"""Add random camera radial distortion.
.. image:: _static/img/RandomFisheye.png
@@ -46,11 +46,8 @@ class RandomFisheye(GeometricAugmentationBase2D):
same_on_batch: bool = False,
p: float = 0.5,
keepdim: bool = False,
- return_transform: Optional[bool] = None,
) -> None:
- super().__init__(
- p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim
- )
+ super().__init__(p=p, 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)
@@ -67,10 +64,6 @@ class RandomFisheye(GeometricAugmentationBase2D):
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: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
- return self.identity_matrix(input)
-
def apply_transform(
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
) -> Tensor:
diff --git a/kornia/augmentation/_2d/geometric/pad.py b/kornia/augmentation/_2d/geometric/pad.py
index 3468985c7..79d93f767 100644
--- a/kornia/augmentation/_2d/geometric/pad.py
+++ b/kornia/augmentation/_2d/geometric/pad.py
@@ -46,14 +46,9 @@ class PadTo(GeometricAugmentationBase2D):
"""
def __init__(
- self,
- size: Tuple[int, int],
- pad_mode: str = "constant",
- pad_value: Union[int, float] = 0,
- keepdim: bool = False,
- return_transform: Optional[bool] = None,
+ self, size: Tuple[int, int], pad_mode: str = "constant", pad_value: Union[int, float] = 0, keepdim: bool = False
) -> None:
- super().__init__(p=1.0, return_transform=return_transform, same_on_batch=True, p_batch=1.0, keepdim=keepdim)
+ super().__init__(p=1.0, 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
diff --git a/kornia/augmentation/_2d/geometric/perspective.py b/kornia/augmentation/_2d/geometric/perspective.py
index 9f442cf70..b7399d010 100644
--- a/kornia/augmentation/_2d/geometric/perspective.py
+++ b/kornia/augmentation/_2d/geometric/perspective.py
@@ -64,9 +64,8 @@ class RandomPerspective(GeometricAugmentationBase2D):
p: float = 0.5,
keepdim: bool = False,
sampling_method: str = "basic",
- return_transform: Optional[bool] = None,
) -> None:
- super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
+ super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)
self._param_generator = rg.PerspectiveGenerator(distortion_scale, sampling_method=sampling_method)
self.flags: Dict[str, Any] = dict(align_corners=align_corners, resample=Resample.get(resample))
diff --git a/kornia/augmentation/_2d/geometric/resize.py b/kornia/augmentation/_2d/geometric/resize.py
index eb6bb059c..ae4050a17 100644
--- a/kornia/augmentation/_2d/geometric/resize.py
+++ b/kornia/augmentation/_2d/geometric/resize.py
@@ -31,10 +31,9 @@ class Resize(GeometricAugmentationBase2D):
align_corners: bool = True,
antialias: bool = False,
p: float = 1.0,
- return_transform: Optional[bool] = None,
keepdim: bool = False,
) -> None:
- super().__init__(p=1.0, return_transform=return_transform, same_on_batch=True, p_batch=p, keepdim=keepdim)
+ super().__init__(p=1.0, same_on_batch=True, p_batch=p, keepdim=keepdim)
self._param_generator = rg.ResizeGenerator(resize_to=size, side=side)
self.flags = dict(
size=size, side=side, resample=Resample.get(resample), align_corners=align_corners, antialias=antialias
@@ -44,7 +43,9 @@ class Resize(GeometricAugmentationBase2D):
if params["output_size"] == input.shape[-2:]:
return eye_like(3, input)
- transform: Tensor = get_perspective_transform(params["src"], params["dst"])
+ transform: Tensor = torch.as_tensor(
+ get_perspective_transform(params["src"], params["dst"]), dtype=input.dtype, device=input.device
+ )
transform = transform.expand(input.shape[0], -1, -1)
return transform
@@ -102,17 +103,9 @@ class LongestMaxSize(Resize):
resample: Union[str, int, Resample] = Resample.BILINEAR.name,
align_corners: bool = True,
p: float = 1.0,
- return_transform: Optional[bool] = None,
) -> None:
# TODO: Support max_size list input to randomly select from
- super().__init__(
- size=max_size,
- side="long",
- resample=resample,
- return_transform=return_transform,
- align_corners=align_corners,
- p=p,
- )
+ super().__init__(size=max_size, side="long", resample=resample, align_corners=align_corners, p=p)
class SmallestMaxSize(Resize):
@@ -128,14 +121,6 @@ class SmallestMaxSize(Resize):
resample: Union[str, int, Resample] = Resample.BILINEAR.name,
align_corners: bool = True,
p: float = 1.0,
- return_transform: Optional[bool] = None,
) -> None:
# TODO: Support max_size list input to randomly select from
- super().__init__(
- size=max_size,
- side="short",
- resample=resample,
- return_transform=return_transform,
- align_corners=align_corners,
- p=p,
- )
+ super().__init__(size=max_size, side="short", resample=resample, align_corners=align_corners, p=p)
diff --git a/kornia/augmentation/_2d/geometric/resized_crop.py b/kornia/augmentation/_2d/geometric/resized_crop.py
index d7f3f42d6..ebd4b64db 100644
--- a/kornia/augmentation/_2d/geometric/resized_crop.py
+++ b/kornia/augmentation/_2d/geometric/resized_crop.py
@@ -18,9 +18,6 @@ class RandomResizedCrop(GeometricAugmentationBase2D):
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
@@ -73,12 +70,9 @@ class RandomResizedCrop(GeometricAugmentationBase2D):
p: float = 1.0,
keepdim: bool = False,
cropping_mode: str = "slice",
- return_transform: Optional[bool] = None,
) -> 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
- )
+ super().__init__(p=1.0, same_on_batch=same_on_batch, p_batch=p, keepdim=keepdim)
self._param_generator = rg.ResizedCropGenerator(size, scale, ratio)
self.flags = dict(
size=size,
diff --git a/kornia/augmentation/_2d/geometric/rotation.py b/kornia/augmentation/_2d/geometric/rotation.py
index f9a8f5805..94196f307 100644
--- a/kornia/augmentation/_2d/geometric/rotation.py
+++ b/kornia/augmentation/_2d/geometric/rotation.py
@@ -67,9 +67,8 @@ class RandomRotation(GeometricAugmentationBase2D):
align_corners: bool = True,
p: float = 0.5,
keepdim: bool = False,
- return_transform: Optional[bool] = None,
) -> None:
- super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
+ super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)
self._param_generator = rg.PlainUniformGenerator((degrees, "degrees", 0.0, (-360.0, 360.0)))
self.flags = dict(resample=Resample.get(resample), align_corners=align_corners)
diff --git a/kornia/augmentation/_2d/geometric/thin_plate_spline.py b/kornia/augmentation/_2d/geometric/thin_plate_spline.py
index 7bb82df92..bb7073127 100644
--- a/kornia/augmentation/_2d/geometric/thin_plate_spline.py
+++ b/kornia/augmentation/_2d/geometric/thin_plate_spline.py
@@ -3,11 +3,11 @@ from typing import Any, Dict, Optional
import torch
from torch import Tensor
-from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
+from kornia.augmentation._2d.base import AugmentationBase2D
from kornia.geometry.transform import get_tps_transform, warp_image_tps
-class RandomThinPlateSpline(GeometricAugmentationBase2D):
+class RandomThinPlateSpline(AugmentationBase2D):
r"""Add random noise to the Thin Plate Spline algorithm.
.. image:: _static/img/RandomThinPlateSpline.png
@@ -43,11 +43,8 @@ class RandomThinPlateSpline(GeometricAugmentationBase2D):
same_on_batch: bool = False,
p: float = 0.5,
keepdim: bool = False,
- return_transform: Optional[bool] = None,
) -> None:
- super().__init__(
- p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim
- )
+ super().__init__(p=p, 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)
@@ -57,10 +54,6 @@ class RandomThinPlateSpline(GeometricAugmentationBase2D):
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: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
- return self.identity_matrix(input)
-
def apply_transform(
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
) -> Tensor:
diff --git a/kornia/augmentation/_2d/intensity/base.py b/kornia/augmentation/_2d/intensity/base.py
index 995d0f8ce..d4906e365 100644
--- a/kornia/augmentation/_2d/intensity/base.py
+++ b/kornia/augmentation/_2d/intensity/base.py
@@ -1,16 +1,15 @@
-from typing import Any, Dict
+from typing import Any, Dict, Optional
from torch import Tensor
-from kornia.augmentation._2d.base import AugmentationBase2D
+from kornia.augmentation._2d.base import RigidAffineAugmentationBase2D
+from kornia.geometry.boxes import Boxes
+from kornia.geometry.keypoints import Keypoints
-class IntensityAugmentationBase2D(AugmentationBase2D):
+class IntensityAugmentationBase2D(RigidAffineAugmentationBase2D):
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.
@@ -23,3 +22,49 @@ class IntensityAugmentationBase2D(AugmentationBase2D):
def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
return self.identity_matrix(input)
+
+ def apply_non_transform(
+ self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
+ ) -> Tensor:
+ # For the images where batch_prob == False.
+ return input
+
+ def apply_non_transform_mask(
+ self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
+ ) -> Tensor:
+ return input
+
+ def apply_transform_mask(
+ self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
+ ) -> Tensor:
+ return input
+
+ def apply_non_transform_boxes(
+ self, input: Boxes, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
+ ) -> Boxes:
+ return input
+
+ def apply_transform_boxes(
+ self, input: Boxes, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
+ ) -> Boxes:
+ return input
+
+ def apply_non_transform_keypoint(
+ self, input: Keypoints, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
+ ) -> Keypoints:
+ return input
+
+ def apply_transform_keypoint(
+ self, input: Keypoints, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
+ ) -> Keypoints:
+ return input
+
+ def apply_non_transform_class(
+ self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
+ ) -> Tensor:
+ return input
+
+ def apply_transform_class(
+ self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
+ ) -> Tensor:
+ return input
diff --git a/kornia/augmentation/_2d/intensity/box_blur.py b/kornia/augmentation/_2d/intensity/box_blur.py
index 995daeda9..dddab9cd3 100644
--- a/kornia/augmentation/_2d/intensity/box_blur.py
+++ b/kornia/augmentation/_2d/intensity/box_blur.py
@@ -44,16 +44,10 @@ class RandomBoxBlur(IntensityAugmentationBase2D):
same_on_batch: bool = False,
p: float = 0.5,
keepdim: bool = False,
- return_transform: Optional[bool] = None,
) -> None:
- super().__init__(
- p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim
- )
+ super().__init__(p=p, 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: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
- return self.identity_matrix(input)
-
def apply_transform(
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
) -> Tensor:
diff --git a/kornia/augmentation/_2d/intensity/brightness.py b/kornia/augmentation/_2d/intensity/brightness.py
index 824964944..844d24673 100644
--- a/kornia/augmentation/_2d/intensity/brightness.py
+++ b/kornia/augmentation/_2d/intensity/brightness.py
@@ -61,9 +61,8 @@ class RandomBrightness(IntensityAugmentationBase2D):
same_on_batch: bool = False,
p: float = 1.0,
keepdim: bool = False,
- return_transform: Optional[bool] = None,
) -> None:
- super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
+ super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)
self.brightness: Tensor = _range_bound(brightness, 'brightness', center=1.0, bounds=(0.0, 2.0))
self._param_generator = rg.PlainUniformGenerator((self.brightness, "brightness_factor", None, None))
diff --git a/kornia/augmentation/_2d/intensity/channel_shuffle.py b/kornia/augmentation/_2d/intensity/channel_shuffle.py
index 96b6ea353..ad69ae850 100644
--- a/kornia/augmentation/_2d/intensity/channel_shuffle.py
+++ b/kornia/augmentation/_2d/intensity/channel_shuffle.py
@@ -34,16 +34,8 @@ class RandomChannelShuffle(IntensityAugmentationBase2D):
tensor(True)
"""
- def __init__(
- self,
- same_on_batch: bool = False,
- p: float = 0.5,
- keepdim: bool = False,
- return_transform: Optional[bool] = None,
- ) -> None:
- super().__init__(
- p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim
- )
+ def __init__(self, same_on_batch: bool = False, p: float = 0.5, keepdim: bool = False) -> None:
+ super().__init__(p=p, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim)
def generate_parameters(self, shape: torch.Size) -> Dict[str, Tensor]:
B, C, _, _ = shape
diff --git a/kornia/augmentation/_2d/intensity/color_jiggle.py b/kornia/augmentation/_2d/intensity/color_jiggle.py
index 68c8b0fb4..7f770ea91 100644
--- a/kornia/augmentation/_2d/intensity/color_jiggle.py
+++ b/kornia/augmentation/_2d/intensity/color_jiggle.py
@@ -63,9 +63,8 @@ class ColorJiggle(IntensityAugmentationBase2D):
same_on_batch: bool = False,
p: float = 1.0,
keepdim: bool = False,
- return_transform: Optional[bool] = None,
) -> None:
- super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
+ super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)
self.brightness = brightness
self.contrast = contrast
self.saturation = saturation
diff --git a/kornia/augmentation/_2d/intensity/color_jitter.py b/kornia/augmentation/_2d/intensity/color_jitter.py
index 5f50219f9..b1c816df1 100644
--- a/kornia/augmentation/_2d/intensity/color_jitter.py
+++ b/kornia/augmentation/_2d/intensity/color_jitter.py
@@ -1,4 +1,3 @@
-import warnings
from typing import Any, Dict, List, Optional, Tuple, Union
from kornia.augmentation import random_generator as rg
@@ -76,17 +75,8 @@ class ColorJitter(IntensityAugmentationBase2D):
same_on_batch: bool = False,
p: float = 1.0,
keepdim: bool = False,
- return_transform: Optional[bool] = None,
- silence_instantiation_warning: bool = False,
) -> None:
- super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
-
- if not silence_instantiation_warning:
- warnings.warn(
- "`ColorJitter` is now following Torchvision implementation. Old "
- "behavior can be retrieved by instantiating `ColorJiggle`.",
- category=DeprecationWarning,
- )
+ super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)
self.brightness = brightness
self.contrast = contrast
diff --git a/kornia/augmentation/_2d/intensity/contrast.py b/kornia/augmentation/_2d/intensity/contrast.py
index c811f9bdf..863e525d5 100644
--- a/kornia/augmentation/_2d/intensity/contrast.py
+++ b/kornia/augmentation/_2d/intensity/contrast.py
@@ -61,9 +61,8 @@ class RandomContrast(IntensityAugmentationBase2D):
same_on_batch: bool = False,
p: float = 1.0,
keepdim: bool = False,
- return_transform: Optional[bool] = None,
) -> None:
- super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
+ super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)
self.contrast: Tensor = _range_bound(contrast, 'contrast', center=1.0)
self._param_generator = rg.PlainUniformGenerator((self.contrast, "contrast_factor", None, None))
diff --git a/kornia/augmentation/_2d/intensity/denormalize.py b/kornia/augmentation/_2d/intensity/denormalize.py
index b85e4e7d4..323b83e8c 100644
--- a/kornia/augmentation/_2d/intensity/denormalize.py
+++ b/kornia/augmentation/_2d/intensity/denormalize.py
@@ -44,9 +44,8 @@ class Denormalize(IntensityAugmentationBase2D):
std: Union[Tensor, Tuple[float], List[float], float],
p: float = 1.0,
keepdim: bool = False,
- return_transform: Optional[bool] = None,
) -> None:
- super().__init__(p=p, return_transform=return_transform, same_on_batch=True, keepdim=keepdim)
+ super().__init__(p=p, same_on_batch=True, keepdim=keepdim)
if isinstance(mean, float):
mean = torch.tensor([mean])
diff --git a/kornia/augmentation/_2d/intensity/equalize.py b/kornia/augmentation/_2d/intensity/equalize.py
index d11eb4941..ea4eec9e6 100644
--- a/kornia/augmentation/_2d/intensity/equalize.py
+++ b/kornia/augmentation/_2d/intensity/equalize.py
@@ -42,14 +42,8 @@ class RandomEqualize(IntensityAugmentationBase2D):
tensor(True)
"""
- def __init__(
- self,
- same_on_batch: bool = False,
- p: float = 0.5,
- keepdim: bool = False,
- return_transform: Optional[bool] = None,
- ) -> None:
- super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
+ def __init__(self, same_on_batch: bool = False, p: float = 0.5, keepdim: bool = False) -> None:
+ super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)
def apply_transform(
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
diff --git a/kornia/augmentation/_2d/intensity/erasing.py b/kornia/augmentation/_2d/intensity/erasing.py
index bfe39c61d..5d9b08ce4 100644
--- a/kornia/augmentation/_2d/intensity/erasing.py
+++ b/kornia/augmentation/_2d/intensity/erasing.py
@@ -61,12 +61,10 @@ class RandomErasing(IntensityAugmentationBase2D):
same_on_batch: bool = False,
p: float = 0.5,
keepdim: bool = False,
- return_transform: Optional[bool] = None,
) -> None:
- super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
+ super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)
self.scale = scale
self.ratio = ratio
- self.value: float = float(value)
self._param_generator = rg.RectangleEraseGenerator(scale, ratio, float(value))
def apply_transform(
@@ -80,3 +78,18 @@ class RandomErasing(IntensityAugmentationBase2D):
mask = mask.unsqueeze(1).repeat(1, c, 1, 1).to(input) # Transform to B, c, H, W
transformed = where(mask == 1.0, values, input)
return transformed
+
+ def apply_transform_mask(
+ self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
+ ) -> Tensor:
+ _, c, h, w = input.size()
+
+ values = params["values"][..., None, None, None].repeat(1, *input.shape[1:]).to(input)
+ # Erase the corresponding areas on masks.
+ values = values.zero_()
+
+ 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 = where(mask == 1.0, values, input)
+ return transformed
diff --git a/kornia/augmentation/_2d/intensity/gamma.py b/kornia/augmentation/_2d/intensity/gamma.py
index e7621f893..f830f95d8 100644
--- a/kornia/augmentation/_2d/intensity/gamma.py
+++ b/kornia/augmentation/_2d/intensity/gamma.py
@@ -59,9 +59,8 @@ class RandomGamma(IntensityAugmentationBase2D):
same_on_batch: bool = False,
p: float = 1.0,
keepdim: bool = False,
- return_transform: Optional[bool] = None,
) -> None:
- super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
+ super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)
self._param_generator = rg.PlainUniformGenerator(
(gamma, "gamma_factor", None, None), (gain, "gain_factor", None, None)
)
diff --git a/kornia/augmentation/_2d/intensity/gaussian_blur.py b/kornia/augmentation/_2d/intensity/gaussian_blur.py
index a2ba68c3c..c62212670 100644
--- a/kornia/augmentation/_2d/intensity/gaussian_blur.py
+++ b/kornia/augmentation/_2d/intensity/gaussian_blur.py
@@ -61,12 +61,9 @@ class RandomGaussianBlur(IntensityAugmentationBase2D):
same_on_batch: bool = False,
p: float = 0.5,
keepdim: bool = False,
- return_transform: Optional[bool] = None,
silence_instantiation_warning: bool = False,
) -> None:
- super().__init__(
- p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim
- )
+ super().__init__(p=p, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim)
if not silence_instantiation_warning:
warnings.warn(
diff --git a/kornia/augmentation/_2d/intensity/gaussian_noise.py b/kornia/augmentation/_2d/intensity/gaussian_noise.py
index b9db66ba1..433bada9e 100644
--- a/kornia/augmentation/_2d/intensity/gaussian_noise.py
+++ b/kornia/augmentation/_2d/intensity/gaussian_noise.py
@@ -42,17 +42,9 @@ class RandomGaussianNoise(IntensityAugmentationBase2D):
"""
def __init__(
- self,
- mean: float = 0.0,
- std: float = 1.0,
- same_on_batch: bool = False,
- p: float = 0.5,
- keepdim: bool = False,
- return_transform: Optional[bool] = None,
+ self, mean: float = 0.0, std: float = 1.0, 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
- )
+ super().__init__(p=p, 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, Tensor]:
diff --git a/kornia/augmentation/_2d/intensity/grayscale.py b/kornia/augmentation/_2d/intensity/grayscale.py
index f3ca2f37c..76ce01f38 100644
--- a/kornia/augmentation/_2d/intensity/grayscale.py
+++ b/kornia/augmentation/_2d/intensity/grayscale.py
@@ -51,14 +51,8 @@ class RandomGrayscale(IntensityAugmentationBase2D):
tensor(True)
"""
- def __init__(
- self,
- same_on_batch: bool = False,
- p: float = 0.1,
- keepdim: bool = False,
- return_transform: Optional[bool] = None,
- ) -> None:
- super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
+ def __init__(self, same_on_batch: bool = False, p: float = 0.1, keepdim: bool = False) -> None:
+ super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)
def apply_transform(
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
diff --git a/kornia/augmentation/_2d/intensity/hue.py b/kornia/augmentation/_2d/intensity/hue.py
index 8852374f1..726c79541 100644
--- a/kornia/augmentation/_2d/intensity/hue.py
+++ b/kornia/augmentation/_2d/intensity/hue.py
@@ -55,14 +55,9 @@ class RandomHue(IntensityAugmentationBase2D):
"""
def __init__(
- self,
- hue: Tuple[float, float] = (0.0, 0.0),
- same_on_batch: bool = False,
- p: float = 1.0,
- keepdim: bool = False,
- return_transform: Optional[bool] = None,
+ self, hue: Tuple[float, float] = (0.0, 0.0), 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)
+ super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)
self.hue: Tensor = _range_bound(hue, 'hue', bounds=(-0.5, 0.5))
self._param_generator = rg.PlainUniformGenerator((self.hue, "hue_factor", None, None))
diff --git a/kornia/augmentation/_2d/intensity/invert.py b/kornia/augmentation/_2d/intensity/invert.py
index 4edc1298c..229e5c43b 100644
--- a/kornia/augmentation/_2d/intensity/invert.py
+++ b/kornia/augmentation/_2d/intensity/invert.py
@@ -46,11 +46,8 @@ class RandomInvert(IntensityAugmentationBase2D):
same_on_batch: bool = False,
p: float = 0.5,
keepdim: bool = False,
- return_transform: Optional[bool] = None,
) -> None:
- super().__init__(
- p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim
- )
+ super().__init__(p=p, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim)
self.flags = dict(max_val=max_val)
def apply_transform(
diff --git a/kornia/augmentation/_2d/intensity/motion_blur.py b/kornia/augmentation/_2d/intensity/motion_blur.py
index 0fd12f85a..91d554637 100644
--- a/kornia/augmentation/_2d/intensity/motion_blur.py
+++ b/kornia/augmentation/_2d/intensity/motion_blur.py
@@ -75,9 +75,8 @@ class RandomMotionBlur(IntensityAugmentationBase2D):
same_on_batch: bool = False,
p: float = 0.5,
keepdim: bool = False,
- return_transform: Optional[bool] = None,
) -> None:
- super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
+ super().__init__(p=p, 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))
diff --git a/kornia/augmentation/_2d/intensity/normalize.py b/kornia/augmentation/_2d/intensity/normalize.py
index 964c69fe1..28baab177 100644
--- a/kornia/augmentation/_2d/intensity/normalize.py
+++ b/kornia/augmentation/_2d/intensity/normalize.py
@@ -43,9 +43,8 @@ class Normalize(IntensityAugmentationBase2D):
std: Union[Tensor, Tuple[float], List[float], float],
p: float = 1.0,
keepdim: bool = False,
- return_transform: Optional[bool] = None,
) -> None:
- super().__init__(p=p, return_transform=return_transform, same_on_batch=True, keepdim=keepdim)
+ super().__init__(p=p, same_on_batch=True, keepdim=keepdim)
if isinstance(mean, float):
mean = torch.tensor([mean])
diff --git a/kornia/augmentation/_2d/intensity/planckian_jitter.py b/kornia/augmentation/_2d/intensity/planckian_jitter.py
index dc798a8f3..26a35d0dd 100644
--- a/kornia/augmentation/_2d/intensity/planckian_jitter.py
+++ b/kornia/augmentation/_2d/intensity/planckian_jitter.py
@@ -157,9 +157,8 @@ class RandomPlanckianJitter(IntensityAugmentationBase2D):
same_on_batch: bool = False,
p: float = 0.5,
keepdim: bool = False,
- return_transform: Optional[bool] = None,
) -> None:
- super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
+ super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)
if isinstance(select_from, int):
select_from = [select_from]
diff --git a/kornia/augmentation/_2d/intensity/plasma.py b/kornia/augmentation/_2d/intensity/plasma.py
index d7bf83fc0..b36f3b2f5 100644
--- a/kornia/augmentation/_2d/intensity/plasma.py
+++ b/kornia/augmentation/_2d/intensity/plasma.py
@@ -41,11 +41,8 @@ class RandomPlasmaBrightness(IntensityAugmentationBase2D):
same_on_batch: bool = False,
p: float = 0.5,
keepdim: bool = False,
- return_transform: Optional[bool] = None,
) -> None:
- super().__init__(
- p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim
- )
+ super().__init__(p=p, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim)
self._param_generator = rg.PlainUniformGenerator(
(roughness, "roughness", None, None), (intensity, "intensity", None, None)
)
@@ -94,11 +91,8 @@ class RandomPlasmaContrast(IntensityAugmentationBase2D):
same_on_batch: bool = False,
p: float = 0.5,
keepdim: bool = False,
- return_transform: Optional[bool] = None,
) -> None:
- super().__init__(
- p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim
- )
+ super().__init__(p=p, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim)
self._param_generator = rg.PlainUniformGenerator((roughness, "roughness", None, None))
def apply_transform(
@@ -147,11 +141,8 @@ class RandomPlasmaShadow(IntensityAugmentationBase2D):
same_on_batch: bool = False,
p: float = 0.5,
keepdim: bool = False,
- return_transform: Optional[bool] = None,
) -> None:
- super().__init__(
- p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim
- )
+ super().__init__(p=p, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim)
self._param_generator = rg.PlainUniformGenerator(
(roughness, "roughness", None, None),
(shade_intensity, "shade_intensity", None, None),
diff --git a/kornia/augmentation/_2d/intensity/posterize.py b/kornia/augmentation/_2d/intensity/posterize.py
index 934465d0f..9a1c04c12 100644
--- a/kornia/augmentation/_2d/intensity/posterize.py
+++ b/kornia/augmentation/_2d/intensity/posterize.py
@@ -51,9 +51,8 @@ class RandomPosterize(IntensityAugmentationBase2D):
same_on_batch: bool = False,
p: float = 0.5,
keepdim: bool = False,
- return_transform: Optional[bool] = None,
) -> None:
- super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
+ super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)
# TODO: the generator should receive the device
self._param_generator = rg.PosterizeGenerator(bits)
diff --git a/kornia/augmentation/_2d/intensity/random_rgb_shift.py b/kornia/augmentation/_2d/intensity/random_rgb_shift.py
index 59490b2a8..dbf8a5ad6 100644
--- a/kornia/augmentation/_2d/intensity/random_rgb_shift.py
+++ b/kornia/augmentation/_2d/intensity/random_rgb_shift.py
@@ -81,9 +81,8 @@ class RandomRGBShift(IntensityAugmentationBase2D):
same_on_batch: bool = False,
p: float = 0.5,
keepdim: bool = False,
- return_transform: Optional[bool] = None,
) -> None:
- super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
+ super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)
self._param_generator = rg.PlainUniformGenerator(
(r_shift_limit, "r_shift", 0, (-r_shift_limit, r_shift_limit)),
(g_shift_limit, "g_shift", 0, (-g_shift_limit, g_shift_limit)),
diff --git a/kornia/augmentation/_2d/intensity/saturation.py b/kornia/augmentation/_2d/intensity/saturation.py
index 7513a763c..14d65e22b 100644
--- a/kornia/augmentation/_2d/intensity/saturation.py
+++ b/kornia/augmentation/_2d/intensity/saturation.py
@@ -59,9 +59,8 @@ class RandomSaturation(IntensityAugmentationBase2D):
same_on_batch: bool = False,
p: float = 1.0,
keepdim: bool = False,
- return_transform: Optional[bool] = None,
) -> None:
- super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
+ super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)
self.saturation: Tensor = _range_bound(saturation, 'saturation', center=1.0)
self._param_generator = rg.PlainUniformGenerator((self.saturation, "saturation_factor", None, None))
diff --git a/kornia/augmentation/_2d/intensity/sharpness.py b/kornia/augmentation/_2d/intensity/sharpness.py
index bd994c56e..e672667e8 100644
--- a/kornia/augmentation/_2d/intensity/sharpness.py
+++ b/kornia/augmentation/_2d/intensity/sharpness.py
@@ -49,9 +49,8 @@ class RandomSharpness(IntensityAugmentationBase2D):
same_on_batch: bool = False,
p: float = 0.5,
keepdim: bool = False,
- return_transform: Optional[bool] = None,
) -> None:
- super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
+ super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)
self._param_generator = rg.PlainUniformGenerator((sharpness, "sharpness", 0.0, (0, float("inf"))))
def apply_transform(
diff --git a/kornia/augmentation/_2d/intensity/solarize.py b/kornia/augmentation/_2d/intensity/solarize.py
index f5ef8a1c1..4ab6773a3 100644
--- a/kornia/augmentation/_2d/intensity/solarize.py
+++ b/kornia/augmentation/_2d/intensity/solarize.py
@@ -55,9 +55,8 @@ class RandomSolarize(IntensityAugmentationBase2D):
same_on_batch: bool = False,
p: float = 0.5,
keepdim: bool = False,
- return_transform: Optional[bool] = None,
) -> None:
- super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
+ super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)
self._param_generator = rg.PlainUniformGenerator(
(thresholds, "thresholds", 0.5, (0.0, 1.0)), (additions, "additions", 0.0, (-0.5, 0.5))
)
diff --git a/kornia/augmentation/_3d/base.py b/kornia/augmentation/_3d/base.py
index 3e03d62d8..1a7a2ee4e 100644
--- a/kornia/augmentation/_3d/base.py
+++ b/kornia/augmentation/_3d/base.py
@@ -1,16 +1,18 @@
-from torch import Tensor, float16, float32, float64
+from typing import Any, Dict, Optional
+
+from torch import float16, float32, float64
import kornia
from kornia.augmentation.base import _AugmentationBase
from kornia.augmentation.utils import _transform_input3d, _validate_input_dtype
+from kornia.core import Tensor
+from kornia.geometry.boxes import Boxes3D
+from kornia.geometry.keypoints import Keypoints3D
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.
@@ -19,21 +21,11 @@ class AugmentationBase3D(_AugmentationBase):
same_on_batch: apply the same transformation across the batch.
"""
- def __check_batching__(self, input: Tensor):
- 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 validate_tensor(self, input: Tensor) -> None:
+ """Check if the input tensor is formatted as expected."""
+ _validate_input_dtype(input, accepted_dtypes=[float16, float32, float64])
+ if len(input.shape) != 5:
+ raise RuntimeError(f"Expect (B, C, D, H, W). Got {input.shape}.")
def transform_tensor(self, input: Tensor) -> Tensor:
"""Convert any incoming (D, H, W), (C, D, H, W) and (B, C, D, H, W) into (B, C, D, H, W)."""
@@ -43,3 +35,81 @@ class AugmentationBase3D(_AugmentationBase):
def identity_matrix(self, input) -> Tensor:
"""Return 4x4 identity matrix."""
return kornia.eye_like(4, input)
+
+
+class RigidAffineAugmentationBase3D(AugmentationBase3D):
+ r"""AugmentationBase2D base class for rigid/affine augmentation implementations.
+
+ RigidAffineAugmentationBase2D enables routined transformation with given transformation matrices
+ for different data types like masks, boxes, and keypoints.
+
+ 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.
+ 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``.
+ """
+
+ _transform_matrix: Optional[Tensor]
+
+ @property
+ def transform_matrix(self) -> Optional[Tensor]:
+ return self._transform_matrix
+
+ def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
+ raise NotImplementedError
+
+ def generate_transformation_matrix(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
+ """Generate transformation matrices with the given input and param settings."""
+ to_apply = params['batch_prob']
+ in_tensor = self.transform_tensor(input)
+ if not to_apply.any():
+ trans_matrix = self.identity_matrix(in_tensor)
+ elif to_apply.all():
+ trans_matrix = self.compute_transformation(in_tensor, params=params, flags=flags)
+ else:
+ trans_matrix = self.identity_matrix(in_tensor)
+ trans_matrix = trans_matrix.index_put(
+ (to_apply,), self.compute_transformation(in_tensor[to_apply], params=params, flags=flags)
+ )
+ return trans_matrix
+
+ def inverse_inputs(
+ self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
+ ) -> Tensor:
+ raise NotImplementedError
+
+ def inverse_masks(
+ self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
+ ) -> Tensor:
+ raise NotImplementedError
+
+ def inverse_boxes(
+ self, input: Boxes3D, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
+ ) -> Boxes3D:
+ raise NotImplementedError
+
+ def inverse_keypoints(
+ self, input: Keypoints3D, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
+ ) -> Keypoints3D:
+ raise NotImplementedError
+
+ def inverse_classes(
+ self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
+ ) -> Tensor:
+ raise NotImplementedError
+
+ def apply_func(
+ self, in_tensor: Tensor, params: Dict[str, Tensor], flags: Optional[Dict[str, Any]] = None
+ ) -> Tensor:
+ if flags is None:
+ flags = self.flags
+
+ trans_matrix = self.generate_transformation_matrix(in_tensor, params, flags)
+ output = self.transform_inputs(in_tensor, params, flags, trans_matrix)
+ self._transform_matrix = trans_matrix
+
+ return output
diff --git a/kornia/augmentation/_3d/geometric/affine.py b/kornia/augmentation/_3d/geometric/affine.py
index 53da12a1f..88e959825 100644
--- a/kornia/augmentation/_3d/geometric/affine.py
+++ b/kornia/augmentation/_3d/geometric/affine.py
@@ -1,13 +1,13 @@
from typing import Any, Dict, Optional, Tuple, Union
from kornia.augmentation import random_generator as rg
-from kornia.augmentation._3d.base import AugmentationBase3D
+from kornia.augmentation._3d.geometric.base import GeometricAugmentationBase3D
from kornia.constants import Resample
from kornia.core import Tensor
from kornia.geometry import deg2rad, get_affine_matrix3d, warp_affine3d
-class RandomAffine3D(AugmentationBase3D):
+class RandomAffine3D(GeometricAugmentationBase3D):
r"""Apply affine transformation 3D volumes (5D tensor).
The transformation is computed so that the center is kept invariant.
@@ -39,8 +39,6 @@ class RandomAffine3D(AugmentationBase3D):
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: resample mode from "nearest" (0) or "bilinear" (1).
- 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
@@ -116,9 +114,8 @@ class RandomAffine3D(AugmentationBase3D):
align_corners: bool = False,
p: float = 0.5,
keepdim: bool = False,
- return_transform: Optional[bool] = None,
) -> None:
- super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
+ super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)
self.degrees = degrees
self.shears = shears
self.translate = translate
diff --git a/kornia/augmentation/_3d/geometric/base.py b/kornia/augmentation/_3d/geometric/base.py
new file mode 100644
index 000000000..b9a72f9d3
--- /dev/null
+++ b/kornia/augmentation/_3d/geometric/base.py
@@ -0,0 +1,5 @@
+from kornia.augmentation._3d.base import RigidAffineAugmentationBase3D
+
+
+class GeometricAugmentationBase3D(RigidAffineAugmentationBase3D):
+ pass
diff --git a/kornia/augmentation/_3d/geometric/center_crop.py b/kornia/augmentation/_3d/geometric/center_crop.py
index 29305257c..fe8b63008 100644
--- a/kornia/augmentation/_3d/geometric/center_crop.py
+++ b/kornia/augmentation/_3d/geometric/center_crop.py
@@ -3,12 +3,12 @@ from typing import Any, Dict, Optional, Tuple, Union, cast
from torch import Size, Tensor
from kornia.augmentation import random_generator as rg
-from kornia.augmentation._3d.base import AugmentationBase3D
+from kornia.augmentation._3d.geometric.base import GeometricAugmentationBase3D
from kornia.constants import Resample
from kornia.geometry import crop_by_transform_mat3d, get_perspective_transform3d
-class CenterCrop3D(AugmentationBase3D):
+class CenterCrop3D(GeometricAugmentationBase3D):
r"""Apply center crop on 3D volumes (5D tensor).
Args:
@@ -17,8 +17,6 @@ class CenterCrop3D(AugmentationBase3D):
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: resample mode from "nearest" (0) or "bilinear" (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.
align_corners: interpolation flag.
keepdim: whether to keep the output shape the same as input (True) or broadcast it
to the batch form (False).
@@ -68,11 +66,10 @@ class CenterCrop3D(AugmentationBase3D):
resample: Union[str, int, Resample] = Resample.BILINEAR.name,
p: float = 1.0,
keepdim: bool = False,
- return_transform: Optional[bool] = None,
) -> 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)
+ super().__init__(p=1.0, same_on_batch=True, p_batch=p, keepdim=keepdim)
if isinstance(size, tuple):
self.size = (size[0], size[1], size[2])
elif isinstance(size, int):
diff --git a/kornia/augmentation/_3d/geometric/crop.py b/kornia/augmentation/_3d/geometric/crop.py
index b3f588bcb..3def111b4 100644
--- a/kornia/augmentation/_3d/geometric/crop.py
+++ b/kornia/augmentation/_3d/geometric/crop.py
@@ -1,13 +1,13 @@
from typing import Any, Dict, Optional, Tuple, Union
from kornia.augmentation import random_generator as rg
-from kornia.augmentation._3d.base import AugmentationBase3D
+from kornia.augmentation._3d.geometric.base import GeometricAugmentationBase3D
from kornia.constants import Resample
from kornia.core import Tensor, pad
from kornia.geometry import crop_by_transform_mat3d, get_perspective_transform3d
-class RandomCrop3D(AugmentationBase3D):
+class RandomCrop3D(GeometricAugmentationBase3D):
r"""Apply random crop on 3D volumes (5D tensor).
Crops random sub-volumes on a given size.
@@ -29,8 +29,6 @@ class RandomCrop3D(AugmentationBase3D):
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: resample mode from "nearest" (0) or "bilinear" (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: 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
@@ -72,16 +70,13 @@ class RandomCrop3D(AugmentationBase3D):
fill: int = 0,
padding_mode: str = "constant",
resample: Union[str, int, Resample] = Resample.BILINEAR.name,
- return_transform: Optional[bool] = None,
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
- )
+ super().__init__(p=1.0, same_on_batch=same_on_batch, p_batch=p, keepdim=keepdim)
self.flags = dict(
size=size,
padding=padding,
diff --git a/kornia/augmentation/_3d/geometric/depthical_flip.py b/kornia/augmentation/_3d/geometric/depthical_flip.py
index a704985b0..85866afb0 100644
--- a/kornia/augmentation/_3d/geometric/depthical_flip.py
+++ b/kornia/augmentation/_3d/geometric/depthical_flip.py
@@ -3,10 +3,10 @@ from typing import Any, Dict, Optional
import torch
from torch import Tensor
-from kornia.augmentation._3d.base import AugmentationBase3D
+from kornia.augmentation._3d.geometric.base import GeometricAugmentationBase3D
-class RandomDepthicalFlip3D(AugmentationBase3D):
+class RandomDepthicalFlip3D(GeometricAugmentationBase3D):
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)`.
@@ -57,14 +57,8 @@ class RandomDepthicalFlip3D(AugmentationBase3D):
tensor(True)
"""
- def __init__(
- self,
- return_transform: Optional[bool] = None,
- 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 __init__(self, same_on_batch: bool = False, p: float = 0.5, keepdim: bool = False) -> None:
+ super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)
def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
d: int = input.shape[-3]
diff --git a/kornia/augmentation/_3d/geometric/horizontal_flip.py b/kornia/augmentation/_3d/geometric/horizontal_flip.py
index 480032c11..5fcc9836e 100644
--- a/kornia/augmentation/_3d/geometric/horizontal_flip.py
+++ b/kornia/augmentation/_3d/geometric/horizontal_flip.py
@@ -3,10 +3,10 @@ from typing import Any, Dict, Optional
import torch
from torch import Tensor
-from kornia.augmentation._3d.base import AugmentationBase3D
+from kornia.augmentation._3d.geometric.base import GeometricAugmentationBase3D
-class RandomHorizontalFlip3D(AugmentationBase3D):
+class RandomHorizontalFlip3D(GeometricAugmentationBase3D):
r"""Apply random horizontal flip to 3D volumes (5D tensor).
Args:
@@ -51,14 +51,8 @@ class RandomHorizontalFlip3D(AugmentationBase3D):
tensor(True)
"""
- def __init__(
- self,
- same_on_batch: bool = False,
- p: float = 0.5,
- keepdim: bool = False,
- return_transform: Optional[bool] = None,
- ) -> None:
- super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
+ def __init__(self, same_on_batch: bool = False, p: float = 0.5, keepdim: bool = False) -> None:
+ super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)
def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
w: int = input.shape[-1]
diff --git a/kornia/augmentation/_3d/geometric/perspective.py b/kornia/augmentation/_3d/geometric/perspective.py
index 47b418545..975f791c5 100644
--- a/kornia/augmentation/_3d/geometric/perspective.py
+++ b/kornia/augmentation/_3d/geometric/perspective.py
@@ -1,13 +1,13 @@
from typing import Any, Dict, Optional, Union
from kornia.augmentation import random_generator as rg
-from kornia.augmentation._3d.base import AugmentationBase3D
+from kornia.augmentation._3d.geometric.base import GeometricAugmentationBase3D
from kornia.constants import Resample
from kornia.core import Tensor
from kornia.geometry import get_perspective_transform3d, warp_perspective3d
-class RandomPerspective3D(AugmentationBase3D):
+class RandomPerspective3D(GeometricAugmentationBase3D):
r"""Apply andom perspective transformation to 3D volumes (5D tensor).
Args:
@@ -71,9 +71,8 @@ class RandomPerspective3D(AugmentationBase3D):
align_corners: bool = False,
p: float = 0.5,
keepdim: bool = False,
- return_transform: Optional[bool] = None,
) -> None:
- super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
+ super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)
self.flags = dict(resample=Resample.get(resample), align_corners=align_corners)
self._param_generator = rg.PerspectiveGenerator3D(distortion_scale)
diff --git a/kornia/augmentation/_3d/geometric/rotation.py b/kornia/augmentation/_3d/geometric/rotation.py
index 7e7601112..d4a868cda 100644
--- a/kornia/augmentation/_3d/geometric/rotation.py
+++ b/kornia/augmentation/_3d/geometric/rotation.py
@@ -2,14 +2,14 @@ from typing import Any, Dict, Optional, Tuple, Union
import kornia
from kornia.augmentation import random_generator as rg
-from kornia.augmentation._3d.base import AugmentationBase3D
+from kornia.augmentation._3d.geometric.base import GeometricAugmentationBase3D
from kornia.constants import Resample
from kornia.core import Tensor
from kornia.geometry import affine3d
from kornia.geometry.transform.affwarp import _compute_rotation_matrix3d, _compute_tensor_center3d
-class RandomRotation3D(AugmentationBase3D):
+class RandomRotation3D(GeometricAugmentationBase3D):
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)`.
@@ -83,9 +83,8 @@ class RandomRotation3D(AugmentationBase3D):
align_corners: bool = False,
p: float = 0.5,
keepdim: bool = False,
- return_transform: Optional[bool] = None,
) -> None:
- super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
+ super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)
self.flags = dict(resample=Resample.get(resample), align_corners=align_corners)
self._param_generator = rg.RotationGenerator3D(degrees)
diff --git a/kornia/augmentation/_3d/geometric/vertical_flip.py b/kornia/augmentation/_3d/geometric/vertical_flip.py
index 3b09d5873..fa130e099 100644
--- a/kornia/augmentation/_3d/geometric/vertical_flip.py
+++ b/kornia/augmentation/_3d/geometric/vertical_flip.py
@@ -3,10 +3,10 @@ from typing import Any, Dict, Optional
import torch
from torch import Tensor
-from kornia.augmentation._3d.base import AugmentationBase3D
+from kornia.augmentation._3d.geometric.base import GeometricAugmentationBase3D
-class RandomVerticalFlip3D(AugmentationBase3D):
+class RandomVerticalFlip3D(GeometricAugmentationBase3D):
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)`.
@@ -57,14 +57,8 @@ class RandomVerticalFlip3D(AugmentationBase3D):
tensor(True)
"""
- def __init__(
- self,
- same_on_batch: bool = False,
- p: float = 0.5,
- keepdim: bool = False,
- return_transform: Optional[bool] = None,
- ) -> None:
- super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
+ def __init__(self, same_on_batch: bool = False, p: float = 0.5, keepdim: bool = False) -> None:
+ super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)
def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
h: int = input.shape[-2]
diff --git a/kornia/augmentation/_3d/intensity/base.py b/kornia/augmentation/_3d/intensity/base.py
new file mode 100644
index 000000000..47bc62f05
--- /dev/null
+++ b/kornia/augmentation/_3d/intensity/base.py
@@ -0,0 +1,5 @@
+from kornia.augmentation._3d.base import RigidAffineAugmentationBase3D
+
+
+class IntensityAugmentationBase3D(RigidAffineAugmentationBase3D):
+ pass
diff --git a/kornia/augmentation/_3d/intensity/equalize.py b/kornia/augmentation/_3d/intensity/equalize.py
index e38b742c0..e37ca4374 100644
--- a/kornia/augmentation/_3d/intensity/equalize.py
+++ b/kornia/augmentation/_3d/intensity/equalize.py
@@ -2,11 +2,11 @@ from typing import Any, Dict, Optional
from torch import Tensor
-from kornia.augmentation._3d.base import AugmentationBase3D
+from kornia.augmentation._3d.intensity.base import IntensityAugmentationBase3D
from kornia.enhance import equalize3d
-class RandomEqualize3D(AugmentationBase3D):
+class RandomEqualize3D(IntensityAugmentationBase3D):
r"""Apply random equalization to 3D volumes (5D tensor).
Args:
@@ -49,14 +49,8 @@ class RandomEqualize3D(AugmentationBase3D):
tensor(True)
"""
- def __init__(
- self,
- p: float = 0.5,
- same_on_batch: bool = False,
- keepdim: bool = False,
- return_transform: Optional[bool] = None,
- ) -> None:
- super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
+ def __init__(self, p: float = 0.5, same_on_batch: bool = False, keepdim: bool = False) -> None:
+ super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)
def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
return self.identity_matrix(input)
diff --git a/kornia/augmentation/_3d/intensity/motion_blur.py b/kornia/augmentation/_3d/intensity/motion_blur.py
index 07cbf9ce6..db07de5ed 100644
--- a/kornia/augmentation/_3d/intensity/motion_blur.py
+++ b/kornia/augmentation/_3d/intensity/motion_blur.py
@@ -1,13 +1,13 @@
from typing import Any, Dict, Optional, Tuple, Union
from kornia.augmentation import random_generator as rg
-from kornia.augmentation._3d.base import AugmentationBase3D
+from kornia.augmentation._3d.intensity.base import IntensityAugmentationBase3D
from kornia.constants import BorderType, Resample
from kornia.core import Tensor
from kornia.filters import motion_blur3d
-class RandomMotionBlur3D(AugmentationBase3D):
+class RandomMotionBlur3D(IntensityAugmentationBase3D):
r"""Apply random motion blur on 3D volumes (5D tensor).
Args:
@@ -89,11 +89,8 @@ class RandomMotionBlur3D(AugmentationBase3D):
same_on_batch: bool = False,
p: float = 0.5,
keepdim: bool = False,
- return_transform: Optional[bool] = None,
) -> None:
- super().__init__(
- p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim
- )
+ super().__init__(p=p, 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 = rg.MotionBlurGenerator3D(kernel_size, angle, direction)
diff --git a/kornia/augmentation/__init__.py b/kornia/augmentation/__init__.py
index 1a3733f98..36a48677e 100644
--- a/kornia/augmentation/__init__.py
+++ b/kornia/augmentation/__init__.py
@@ -45,7 +45,7 @@ from kornia.augmentation._2d import (
Resize,
SmallestMaxSize,
)
-from kornia.augmentation._2d.base import AugmentationBase2D
+from kornia.augmentation._2d.base import AugmentationBase2D, RigidAffineAugmentationBase2D
from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
from kornia.augmentation._2d.mix.base import MixAugmentationBaseV2
@@ -61,7 +61,9 @@ from kornia.augmentation._3d import (
RandomRotation3D,
RandomVerticalFlip3D,
)
-from kornia.augmentation._3d.base import AugmentationBase3D
+from kornia.augmentation._3d.base import AugmentationBase3D, RigidAffineAugmentationBase3D
+from kornia.augmentation._3d.geometric.base import GeometricAugmentationBase3D
+from kornia.augmentation._3d.intensity.base import IntensityAugmentationBase3D
from kornia.augmentation.container import (
AugmentationSequential,
ImageSequential,
@@ -73,6 +75,7 @@ from kornia.augmentation.container import (
__all__ = [
"AugmentationBase2D",
+ "RigidAffineAugmentationBase2D",
"GeometricAugmentationBase2D",
"IntensityAugmentationBase2D",
"MixAugmentationBaseV2",
@@ -122,6 +125,9 @@ __all__ = [
"Resize",
"SmallestMaxSize",
"AugmentationBase3D",
+ "RigidAffineAugmentationBase3D",
+ "GeometricAugmentationBase3D",
+ "IntensityAugmentationBase3D",
"CenterCrop3D",
"RandomAffine3D",
"RandomCrop3D",
diff --git a/kornia/augmentation/base.py b/kornia/augmentation/base.py
index 3794faf5e..3d1e0ba0d 100644
--- a/kornia/augmentation/base.py
+++ b/kornia/augmentation/base.py
@@ -7,6 +7,8 @@ from torch.distributions import Bernoulli
from kornia.augmentation.random_generator import RandomGeneratorBase
from kornia.augmentation.utils import _adapted_sampling, _transform_output_shape, override_parameters
from kornia.core import Module, Tensor, tensor
+from kornia.geometry.boxes import Boxes
+from kornia.geometry.keypoints import Keypoints
TensorWithTransformMat = Union[Tensor, Tuple[Tensor, Tensor]]
@@ -81,6 +83,10 @@ class _BasicAugmentationBase(Module):
"""Standardize input tensors."""
raise NotImplementedError
+ def validate_tensor(self, input: Tensor) -> None:
+ """Check if the input tensor is formatted as expected."""
+ raise NotImplementedError
+
def transform_output_tensor(self, output: Tensor, output_shape: Tuple[int, ...]) -> Tensor:
"""Standardize output tensors."""
return _transform_output_shape(output, output_shape) if self.keepdim else output
@@ -126,12 +132,15 @@ class _BasicAugmentationBase(Module):
return batch_prob
def _process_kwargs_to_params_and_flags(
- self, params: Dict[str, Tensor], flags: Dict[str, Any], **kwargs
+ self, params: Optional[Dict[str, Tensor]] = None, flags: Optional[Dict[str, Any]] = None, **kwargs
) -> Tuple[Dict[str, Tensor], Dict[str, Any]]:
# NOTE: determine how to save self._params
save_kwargs = kwargs["save_kwargs"] if "save_kwargs" in kwargs else False
+ params = self._params if params is None else params
+ flags = self.flags if flags is None else flags
+
if save_kwargs:
params = override_parameters(params, kwargs, in_place=True)
self._params = params
@@ -139,7 +148,7 @@ class _BasicAugmentationBase(Module):
self._params = params
params = override_parameters(params, kwargs, in_place=False)
- flags = override_parameters(self.flags, kwargs, in_place=False)
+ flags = override_parameters(flags, kwargs, in_place=False)
return params, flags
def forward_parameters(self, batch_shape) -> Dict[str, Tensor]:
@@ -202,41 +211,210 @@ class _AugmentationBase(_BasicAugmentationBase):
to the batch form ``False``.
"""
- def __init__(
+ def apply_transform(
+ self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
+ ) -> Tensor:
+ # apply transform for the input image tensor
+ raise NotImplementedError
+
+ def apply_non_transform(
+ self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
+ ) -> Tensor:
+ # apply additional transform for the images that are skipped from transformation
+ # where batch_prob == False.
+ return input
+
+ def transform_inputs(
self,
- return_transform: Optional[bool] = None,
- same_on_batch: bool = False,
- p: float = 0.5,
- p_batch: float = 1.0,
- keepdim: bool = False,
- ) -> None:
- super().__init__(p, p_batch=p_batch, same_on_batch=same_on_batch, keepdim=keepdim)
- self.p = p
- self.p_batch = p_batch
- self.return_transform = return_transform
- self._transform_matrix: Tensor
- if return_transform is not None:
- raise ValueError(
- "`return_transform` is deprecated. Please access the transformation matrix with "
- "`.transform_matrix`. For chained matrices, please use `AugmentationSequential`."
+ input: Tensor,
+ params: Dict[str, Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[Tensor] = None,
+ **kwargs,
+ ) -> Tensor:
+ self.validate_tensor(input)
+
+ params, flags = self._process_kwargs_to_params_and_flags(
+ self._params if params is None else params, flags, **kwargs
+ )
+
+ to_apply = params['batch_prob']
+ ori_shape = input.shape
+ in_tensor = self.transform_tensor(input)
+ if to_apply.all():
+ output = self.apply_transform(in_tensor, params, flags, transform=transform)
+ elif not to_apply.any():
+ output = self.apply_non_transform(in_tensor, params, flags, transform=transform)
+ else: # If any tensor needs to be transformed.
+ output = self.apply_non_transform(in_tensor, params, flags, transform=transform)
+ applied = self.apply_transform(
+ in_tensor[to_apply], params, flags, transform=transform if transform is None else transform[to_apply]
)
+ output = output.index_put((to_apply,), applied)
+ output = _transform_output_shape(output, ori_shape) if self.keepdim else output
+ return output
- @property
- def transform_matrix(self) -> Tensor:
- return self._transform_matrix
+ def transform_masks(
+ self,
+ input: Tensor,
+ params: Dict[str, Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[Tensor] = None,
+ **kwargs,
+ ) -> Tensor:
+ self.validate_tensor(input)
- def __repr__(self) -> str:
- return self.__class__.__name__ + f"({super().__repr__()})"
+ params, flags = self._process_kwargs_to_params_and_flags(
+ self._params if params is None else params, flags, **kwargs
+ )
+
+ to_apply = params['batch_prob']
+ ori_shape = input.shape
+ in_tensor = self.transform_tensor(input)
+ if to_apply.all():
+ output = self.apply_transform_mask(in_tensor, params, flags, transform=transform)
+ elif not to_apply.any():
+ output = self.apply_non_transform_mask(in_tensor, params, flags, transform=transform)
+ else: # If any tensor needs to be transformed.
+ output = self.apply_non_transform_mask(in_tensor, params, flags, transform=transform)
+ applied = self.apply_transform_mask(
+ in_tensor[to_apply], params, flags, transform=transform if transform is None else transform[to_apply]
+ )
+ output = output.index_put((to_apply,), applied)
+ output = _transform_output_shape(output, ori_shape) if self.keepdim else output
+ return output
+
+ def transform_boxes(
+ self,
+ input: Boxes,
+ params: Dict[str, Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[Tensor] = None,
+ **kwargs,
+ ) -> Boxes:
+
+ if not isinstance(input, Boxes):
+ raise RuntimeError(f"Only `Boxes` is supported. Got {type(input)}.")
+
+ params, flags = self._process_kwargs_to_params_and_flags(
+ self._params if params is None else params, flags, **kwargs
+ )
+
+ to_apply = params['batch_prob']
+ output: Boxes
+ if to_apply.all():
+ output = self.apply_transform_box(input, params, flags, transform=transform)
+ elif not to_apply.any():
+ output = self.apply_non_transform_box(input, params, flags, transform=transform)
+ else: # If any tensor needs to be transformed.
+ output = self.apply_non_transform_box(input, params, flags, transform=transform)
+ applied = self.apply_transform_box(
+ input[to_apply], params, flags, transform=transform if transform is None else transform[to_apply]
+ )
+ output = output.index_put((to_apply,), applied)
+ return output
+
+ def transform_keypoints(
+ self,
+ input: Keypoints,
+ params: Dict[str, Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[Tensor] = None,
+ **kwargs,
+ ) -> Keypoints:
- def identity_matrix(self, input: Tensor) -> Tensor:
+ if not isinstance(input, Keypoints):
+ raise RuntimeError(f"Only `Keypoints` is supported. Got {type(input)}.")
+
+ params, flags = self._process_kwargs_to_params_and_flags(
+ self._params if params is None else params, flags, **kwargs
+ )
+
+ to_apply = params['batch_prob']
+ if to_apply.all():
+ output = self.apply_transform_keypoint(input, params, flags, transform=transform)
+ elif not to_apply.any():
+ output = self.apply_non_transform_keypoint(input, params, flags, transform=transform)
+ else: # If any tensor needs to be transformed.
+ output = self.apply_non_transform_keypoint(input, params, flags, transform=transform)
+ applied = self.apply_transform_keypoint(
+ input[to_apply], params, flags, transform=transform if transform is None else transform[to_apply]
+ )
+ output = output.index_put((to_apply,), applied)
+ return output
+
+ def transform_classes(
+ self,
+ input: Tensor,
+ params: Dict[str, Tensor],
+ flags: Dict[str, Any],
+ transform: Optional[Tensor] = None,
+ **kwargs,
+ ) -> Tensor:
+
+ params, flags = self._process_kwargs_to_params_and_flags(
+ self._params if params is None else params, flags, **kwargs
+ )
+
+ to_apply = params['batch_prob']
+ if to_apply.all():
+ output = self.apply_transform_class(input, params, flags, transform=transform)
+ elif not to_apply.any():
+ output = self.apply_non_transform_class(input, params, flags, transform=transform)
+ else: # If any tensor needs to be transformed.
+ output = self.apply_non_transform_class(input, params, flags, transform=transform)
+ applied = self.apply_transform_class(
+ input[to_apply], params, flags, transform=transform if transform is None else transform[to_apply]
+ )
+ output = output.index_put((to_apply,), applied)
+ return output
+
+ def apply_non_transform_mask(
+ self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
+ ) -> Tensor:
+ """Process masks corresponding to the inputs that are no transformation applied."""
raise NotImplementedError
- def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
+ def apply_transform_mask(
+ self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
+ ) -> Tensor:
+ """Process masks corresponding to the inputs that are transformed."""
raise NotImplementedError
- def apply_transform(
+ def apply_non_transform_box(
+ self, input: Boxes, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
+ ) -> Boxes:
+ """Process boxes corresponding to the inputs that are no transformation applied."""
+ return input
+
+ def apply_transform_box(
+ self, input: Boxes, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
+ ) -> Boxes:
+ """Process boxes corresponding to the inputs that are transformed."""
+ raise NotImplementedError
+
+ def apply_non_transform_keypoint(
+ self, input: Keypoints, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
+ ) -> Keypoints:
+ """Process keypoints corresponding to the inputs that are no transformation applied."""
+ return input
+
+ def apply_transform_keypoint(
+ self, input: Keypoints, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
+ ) -> Keypoints:
+ """Process keypoints corresponding to the inputs that are transformed."""
+ raise NotImplementedError
+
+ def apply_non_transform_class(
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
) -> Tensor:
+ """Process class tags corresponding to the inputs that are no transformation applied."""
+ return input
+
+ def apply_transform_class(
+ self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
+ ) -> Tensor:
+ """Process class tags corresponding to the inputs that are transformed."""
raise NotImplementedError
def apply_func(
@@ -244,38 +422,7 @@ class _AugmentationBase(_BasicAugmentationBase):
) -> Tensor:
if flags is None:
flags = self.flags
- to_apply = params['batch_prob']
-
- # Note about the explicit type conversions here:
- # If this code is run in an autocast-enabled region, the transformation matrix or the output
- # may be float16 even though the input was float32 (e.g. torch.mm produces float16 output),
- # see also the documentation on autocasting: https://pytorch.org/docs/stable/amp.html.
- # It may be unexpected for the user if the output type changes and it can also lead to errors
- # for the index_put operation below (see also https://github.com/kornia/kornia/issues/1737)
- # In case the type already matches the input type, the conversions are no-ops
-
- # if no augmentation needed
- if not to_apply.any():
- output = in_tensor
- trans_matrix = self.identity_matrix(in_tensor)
- # if all data needs to be augmented
- elif to_apply.all():
- trans_matrix = self.compute_transformation(in_tensor, params=params, flags=flags)
- output = self.apply_transform(in_tensor, params=params, flags=flags, transform=trans_matrix)
- else:
- output = in_tensor.clone()
- trans_matrix = self.identity_matrix(in_tensor)
- trans_matrix = trans_matrix.index_put(
- (to_apply,),
- self.compute_transformation(in_tensor[to_apply], params=params, flags=flags).type(in_tensor.dtype),
- )
- output = output.index_put(
- (to_apply,),
- self.apply_transform(
- in_tensor[to_apply], params=params, flags=flags, transform=trans_matrix[to_apply]
- ).type(in_tensor.dtype),
- )
- self._transform_matrix = trans_matrix.type(in_tensor.dtype)
+ output = self.transform_inputs(in_tensor, params, flags)
return output.type(in_tensor.dtype)
diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.py
index e0d28756b..e4c0786dd 100644
--- a/kornia/augmentation/container/augment.py
+++ b/kornia/augmentation/container/augment.py
@@ -1,24 +1,16 @@
import warnings
-from itertools import zip_longest
-from typing import Any, Dict, List, Optional, Tuple, Union
-
-from kornia.augmentation import (
- AugmentationBase3D,
- GeometricAugmentationBase2D,
- IntensityAugmentationBase2D,
- RandomErasing,
-)
-from kornia.augmentation._2d.mix.base import MixAugmentationBaseV2
+from typing import Any, Dict, List, Optional, Tuple, Union, cast
+
+from kornia.augmentation import AugmentationBase3D, RigidAffineAugmentationBase2D, RigidAffineAugmentationBase3D
from kornia.augmentation.base import _AugmentationBase
-from kornia.augmentation.container.base import SequentialBase
from kornia.augmentation.container.image import ImageSequential, ParamItem
+from kornia.augmentation.container.ops import AugmentationSequentialOps, DataType
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, Resample
-from kornia.core import Tensor
-from kornia.geometry.boxes import Boxes
-from kornia.testing import KORNIA_CHECK_IS_LIST_OF_TENSOR
+from kornia.core import Module, Tensor
+from kornia.geometry.boxes import Boxes, VideoBoxes
+from kornia.geometry.keypoints import Keypoints, VideoKeypoints
from kornia.utils import eye_like
__all__ = ["AugmentationSequential"]
@@ -47,6 +39,13 @@ class AugmentationSequential(ImageSequential):
If (a, b), x number of transformations (a <= x <= b) will be selected.
If True, the whole list of args will be processed as a sequence in a random order.
If False, the whole list of args will be processed as a sequence in original order.
+ transformation_matrix: computation mode for the chained transformation matrix,
+ via `.transform_matrix` attribute.
+ If `silence`, transformation matrix will be computed silently and the non-rigid modules
+ will be ignored as identity transformations.
+ If `rigid`, transformation matrix will be computed silently and the non-rigid modules
+ will trigger errors.
+ If `skip`, transformation matrix will be totally ignored.
extra_args: to control the behaviour for each datakeys. By default, masks are handled
by nearest interpolation strategies.
@@ -67,7 +66,7 @@ class AugmentationSequential(ImageSequential):
... [2., 1.],
... [2., 2.],
... [1., 2.],
- ... ]]).expand(2, -1, -1)
+ ... ]]).expand(2, 1, -1, -1)
>>> points = torch.tensor([[[1., 1.]]]).expand(2, -1, -1)
>>> aug_list = AugmentationSequential(
... kornia.augmentation.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0),
@@ -78,7 +77,7 @@ class AugmentationSequential(ImageSequential):
... )
>>> out = aug_list(input, mask, bbox, points)
>>> [o.shape for o in out]
- [torch.Size([2, 3, 5, 6]), torch.Size([2, 3, 5, 6]), torch.Size([2, 4, 2]), torch.Size([2, 1, 2])]
+ [torch.Size([2, 3, 5, 6]), torch.Size([2, 3, 5, 6]), torch.Size([2, 1, 4, 2]), torch.Size([2, 1, 2])]
>>> # apply the exact augmentation again.
>>> out_rep = aug_list(input, mask, bbox, points, params=aug_list._params)
>>> [(o == o_rep).all() for o, o_rep in zip(out, out_rep)]
@@ -86,7 +85,7 @@ class AugmentationSequential(ImageSequential):
>>> # inverse the augmentations
>>> out_inv = aug_list.inverse(*out)
>>> [o.shape for o in out_inv]
- [torch.Size([2, 3, 5, 6]), torch.Size([2, 3, 5, 6]), torch.Size([2, 4, 2]), torch.Size([2, 1, 2])]
+ [torch.Size([2, 3, 5, 6]), torch.Size([2, 3, 5, 6]), torch.Size([2, 1, 4, 2]), torch.Size([2, 1, 2])]
This example demonstrates the integration of VideoSequential and AugmentationSequential.
@@ -98,7 +97,7 @@ class AugmentationSequential(ImageSequential):
... [2., 1.],
... [2., 2.],
... [1., 2.],
- ... ]]).expand(2, -1, -1)[None]
+ ... ]]).expand(2, 1, -1, -1)[None]
>>> points = torch.tensor([[[1., 1.]]]).expand(2, -1, -1)[None]
>>> aug_list = AugmentationSequential(
... VideoSequential(
@@ -108,10 +107,11 @@ class AugmentationSequential(ImageSequential):
... data_keys=["input", "mask", "bbox", "keypoints"]
... )
>>> out = aug_list(input, mask, bbox, points)
- >>> [o.shape for o in out]
- [torch.Size([1, 2, 3, 5, 6]), torch.Size([1, 2, 3, 5, 6]), torch.Size([1, 2, 4, 2]), torch.Size([1, 2, 1, 2])]
+ >>> [o.shape for o in out] # doctest: +ELLIPSIS
+ [torch.Size([1, 2, 3, 5, 6]), torch.Size([1, 2, 3, 5, 6]), ...([1, 2, 1, 4, 2]), torch.Size([1, 2, 1, 2])]
- Perform ``OneOf`` transformation with ``random_apply=1`` and ``random_apply_weights`` in ``AugmentationSequential``.
+ Perform ``OneOf`` transformation with ``random_apply=1`` and ``random_apply_weights``
+ in ``AugmentationSequential``.
>>> import kornia
>>> input = torch.randn(2, 3, 5, 6)[None]
@@ -121,7 +121,7 @@ class AugmentationSequential(ImageSequential):
... [2., 1.],
... [2., 2.],
... [1., 2.],
- ... ]]).expand(2, -1, -1)[None]
+ ... ]]).expand(2, 1, -1, -1)[None]
>>> points = torch.tensor([[[1., 1.]]]).expand(2, -1, -1)[None]
>>> aug_list = AugmentationSequential(
... VideoSequential(
@@ -135,10 +135,13 @@ class AugmentationSequential(ImageSequential):
... random_apply_weights=[0.5, 0.3]
... )
>>> out = aug_list(input, mask, bbox, points)
- >>> [o.shape for o in out]
- [torch.Size([1, 2, 3, 5, 6]), torch.Size([1, 2, 3, 5, 6]), torch.Size([1, 2, 4, 2]), torch.Size([1, 2, 1, 2])]
+ >>> [o.shape for o in out] # doctest: +ELLIPSIS
+ [torch.Size([1, 2, 3, 5, 6]), torch.Size([1, 2, 3, 5, 6]), ...([1, 2, 1, 4, 2]), torch.Size([1, 2, 1, 2])]
"""
+ _transform_matrix: Optional[Tensor]
+ _transform_matrices: List[Tensor] = []
+
def __init__(
self,
*args: Union[_AugmentationBase, ImageSequential],
@@ -147,6 +150,7 @@ class AugmentationSequential(ImageSequential):
keepdim: Optional[bool] = None,
random_apply: Union[int, bool, Tuple[int, int]] = False,
random_apply_weights: Optional[List[float]] = None,
+ transformation_matrix: str = "silence",
extra_args: Dict[DataKey, Dict[str, Any]] = {DataKey.MASK: dict(resample=Resample.NEAREST, align_corners=True)},
) -> None:
super().__init__(
@@ -160,11 +164,21 @@ class AugmentationSequential(ImageSequential):
self.data_keys = [DataKey.get(inp) for inp in data_keys]
if not all(in_type in DataKey for in_type in self.data_keys):
- raise AssertionError(f"`data_keys` must be in {DataKey}. Got {data_keys}.")
+ raise AssertionError(f"`data_keys` must be in {DataKey}. Got {self.data_keys}.")
if self.data_keys[0] != DataKey.INPUT:
raise NotImplementedError(f"The first input must be {DataKey.INPUT}.")
+ self.transform_op = AugmentationSequentialOps(self.data_keys)
+
+ _valid_transformation_matrix_args = ["silence", "rigid", "skip"]
+ if transformation_matrix not in _valid_transformation_matrix_args:
+ raise ValueError(
+ f"`transformation_matrix` has to be one of {_valid_transformation_matrix_args}. "
+ f"Got {transformation_matrix}."
+ )
+ self._transformation_matrix_arg = transformation_matrix
+
self.contains_video_sequential: bool = False
self.contains_3d_augmentation: bool = False
for arg in args:
@@ -178,6 +192,39 @@ class AugmentationSequential(ImageSequential):
self._transform_matrix: Optional[Tensor] = None
self.extra_args = extra_args
+ def clear_state(self) -> None:
+ self._transform_matrix = None
+ self._transform_matrices = []
+ return super().clear_state()
+
+ @property
+ def transform_matrix(self) -> Optional[Tensor]:
+ # In AugmentationSequential, the parent class is accessed first.
+ # So that it was None in the beginning. We hereby use lazy computation here.
+ if self._transform_matrix is None and len(self._transform_matrices) != 0:
+ self._transform_matrix = self._transform_matrices[0]
+ for mat in self._transform_matrices[1:]:
+ self._update_transform_matrix(mat)
+ return self._transform_matrix
+
+ def _update_transform_matrix_by_module(self, module: Module) -> None:
+ if self._transformation_matrix_arg == "skip":
+ return
+ if isinstance(module, (RigidAffineAugmentationBase2D, RigidAffineAugmentationBase3D, AugmentationSequential)):
+ # Passed in pointer, allows lazy transformation matrix computation
+ self._transform_matrices.append(module.transform_matrix) # type: ignore
+ elif self._transformation_matrix_arg == "rigid":
+ raise RuntimeError(
+ f"Non-rigid module `{module}` is not supported under `rigid` computation mode. "
+ "Please either update the module or change the `transformation_matrix` argument."
+ )
+
+ def _update_transform_matrix(self, transform_matrix: Tensor) -> None:
+ if self._transform_matrix is None:
+ self._transform_matrix = transform_matrix
+ else:
+ self._transform_matrix = transform_matrix @ self._transform_matrix
+
def identity_matrix(self, input: Tensor) -> Tensor:
"""Return identity matrix."""
if self.contains_3d_augmentation:
@@ -185,29 +232,22 @@ class AugmentationSequential(ImageSequential):
else:
return eye_like(3, input)
- @property
- def transform_matrix(self) -> Optional[Tensor]:
- return self._transform_matrix
-
def inverse( # type: ignore[override]
self,
- *args: Tensor,
+ *args: DataType,
params: Optional[List[ParamItem]] = None,
data_keys: Optional[List[Union[str, int, DataKey]]] = None,
- ) -> Union[Tensor, List[Tensor], List[Union[Tensor, List[Tensor]]]]:
+ ) -> Union[DataType, List[DataType]]:
"""Reverse the transformation applied.
Number of input tensors must align with the number of``data_keys``. If ``data_keys`` is not set, use
``self.data_keys`` by default.
"""
- if data_keys is None:
- _data_keys = self.data_keys
- else:
- _data_keys = [DataKey.get(inp) for inp in data_keys]
+ self.transform_op.data_keys = self.transform_op.preproc_datakeys(data_keys)
- self._validate_args_datakeys(*args, data_keys=_data_keys)
+ self._validate_args_datakeys(*args, data_keys=self.transform_op.data_keys)
- args = self._arguments_preproc(*args, data_keys=_data_keys)
+ in_args = self._arguments_preproc(*args, data_keys=self.transform_op.data_keys)
if params is None:
if self._params is None:
@@ -217,147 +257,83 @@ class AugmentationSequential(ImageSequential):
)
params = self._params
- outputs: List[Optional[Tensor]] = [None] * len(_data_keys)
- for idx, (arg, dcate) in enumerate(zip(args, _data_keys)):
-
- if dcate in self.extra_args:
- extra_args = self.extra_args[dcate]
- else:
- extra_args = {}
-
- if dcate == DataKey.INPUT and isinstance(arg, (tuple, list)):
- input, _ = arg # ignore the transformation matrix whilst inverse
- # Using tensors straight-away
- elif isinstance(arg, (Boxes,)):
- input = arg.data # all boxes are in (B, N, 4, 2) format now.
- else:
- input = arg
- for (name, module), _param in zip_longest(list(self.get_forward_sequence(params))[::-1], params[::-1]):
- if isinstance(module, (_AugmentationBase, ImageSequential)):
- _mb = [p for p in params if name in p]
- if len(_mb) > 0:
- param = _mb[0]
- elif isinstance(_param, ParamItem):
- param = _param
- else:
- param = None
- else:
- param = None
-
- if (
- isinstance(module, IntensityAugmentationBase2D)
- and dcate in DataKey
- and not isinstance(module, RandomErasing)
- ):
- pass # Do nothing
- elif isinstance(module, ImageSequential) and module.is_intensity_only() and dcate in DataKey:
- pass # Do nothing
- elif isinstance(module, VideoSequential) and dcate not in [DataKey.INPUT, DataKey.MASK]:
- batch_size: int = input.size(0)
- input = input.view(-1, *input.shape[2:])
- input = ApplyInverse.inverse_by_key(input, module, param, dcate, extra_args=extra_args)
- input = input.view(batch_size, -1, *input.shape[1:])
- elif isinstance(module, PatchSequential):
- raise NotImplementedError("Geometric involved PatchSequential is not supported.")
- elif isinstance(module, (AugmentationSequential)) and dcate in DataKey:
- # AugmentationSequential shall not take the extra_args arguments.
- input = ApplyInverse.inverse_by_key(input, module, param, dcate)
- elif (
- isinstance(module, (GeometricAugmentationBase2D, ImageSequential, RandomErasing))
- and dcate in DataKey
- ):
- input = ApplyInverse.inverse_by_key(input, module, param, dcate, extra_args=extra_args)
- elif isinstance(module, (SequentialBase,)):
- raise ValueError(f"Unsupported Sequential {module}.")
- else:
- raise NotImplementedError(f"data_key {dcate} is not implemented for {module}.")
- if isinstance(arg, (Boxes,)):
- arg._data = input
- outputs[idx] = arg.to_tensor()
- else:
- outputs[idx] = input
-
- _outputs = [i for i in outputs if isinstance(i, Tensor) or KORNIA_CHECK_IS_LIST_OF_TENSOR(i)]
-
- if len(_outputs) == 1 and isinstance(_outputs, list):
- return _outputs[0]
-
- return _outputs
-
- def __packup_output__( # type: ignore[override]
- self, output: List[Union[Tensor, List[Tensor]]], label: Optional[Tensor] = None
- ) -> Union[
- Tensor,
- List[Tensor],
- List[Union[Tensor, List[Tensor]]],
- Tuple[Union[Tensor, List[Tensor], List[Union[Tensor, List[Tensor]]]], Optional[Tensor]],
- ]:
-
- _out: Union[Tensor, List[Tensor], List[Union[Tensor, List[Tensor]]]]
+ outputs: List[DataType] = in_args
+ for param in params[::-1]:
+ module = self.get_submodule(param.name)
+ outputs = self.transform_op.inverse( # type: ignore
+ *outputs, module=module, param=param, extra_args=self.extra_args
+ )
+ if not isinstance(outputs, (list, tuple)):
+ # Make sure we are unpacking a list whilst post-proc
+ outputs = [outputs]
- if len(output) == 1 and isinstance(output, list):
- _out = output[0]
- else:
- _out = output
+ outputs = self._arguments_postproc(args, outputs, data_keys=self.transform_op.data_keys) # type: ignore
- if self.return_label:
- return _out, label
+ if len(outputs) == 1 and isinstance(outputs, list):
+ return outputs[0]
- return _out
+ return outputs
- def _validate_args_datakeys(self, *args: Tensor, data_keys: List[DataKey]):
+ def _validate_args_datakeys(self, *args: DataType, data_keys: List[DataKey]):
if len(args) != len(data_keys):
raise AssertionError(
f"The number of inputs must align with the number of data_keys. Got {len(args)} and {len(data_keys)}."
)
# TODO: validate args batching, and its consistency
- def _arguments_preproc(self, *args: Tensor, data_keys: List[DataKey]):
- inp: List[Any] = []
+ def _arguments_preproc(self, *args: DataType, data_keys: List[DataKey]) -> List[DataType]:
+ inp: List[DataType] = []
for arg, dcate in zip(args, data_keys):
- if DataKey.get(dcate) in [DataKey.INPUT, DataKey.MASK, DataKey.KEYPOINTS]:
+ if DataKey.get(dcate) in [DataKey.INPUT, DataKey.MASK]:
inp.append(arg)
+ elif DataKey.get(dcate) in [DataKey.KEYPOINTS]:
+ inp.append(self._preproc_keypoints(arg, dcate))
elif DataKey.get(dcate) in [DataKey.BBOX, DataKey.BBOX_XYXY, DataKey.BBOX_XYWH]:
- if DataKey.get(dcate) in [DataKey.BBOX]:
- mode = "vertices_plus"
- elif DataKey.get(dcate) in [DataKey.BBOX_XYXY]:
- mode = "xyxy"
- elif DataKey.get(dcate) in [DataKey.BBOX_XYWH]:
- mode = "xywh"
- else:
- raise ValueError(f"Unsupported mode `{DataKey.get(dcate).name}`.")
- inp.append(Boxes.from_tensor(arg, mode=mode))
+ inp.append(self._preproc_boxes(arg, dcate))
else:
raise NotImplementedError(f"input type of {dcate} is not implemented.")
return inp
+ def _arguments_postproc(
+ self, in_args: List[DataType], out_args: List[DataType], data_keys: List[DataKey]
+ ) -> List[DataType]:
+ out: List[DataType] = []
+ for in_arg, out_arg, dcate in zip(in_args, out_args, data_keys):
+ if DataKey.get(dcate) in [DataKey.INPUT]:
+ # It is tensor type already.
+ out.append(out_arg)
+ elif DataKey.get(dcate) in [DataKey.MASK]:
+ # TODO: may add the float to integer, etc.
+ out.append(out_arg)
+ elif DataKey.get(dcate) in [DataKey.KEYPOINTS]:
+ out.append(self._postproc_keypoint(in_arg, cast(Keypoints, out_arg), dcate))
+ elif DataKey.get(dcate) in [DataKey.BBOX, DataKey.BBOX_XYXY, DataKey.BBOX_XYWH]:
+ out.append(self._postproc_boxes(in_arg, cast(Boxes, out_arg), dcate))
+ else:
+ raise NotImplementedError(f"input type of {dcate} is not implemented.")
+
+ return out
+
def forward( # type: ignore[override]
self,
- *args: Tensor,
- label: Optional[Tensor] = None,
+ *args: DataType,
params: Optional[List[ParamItem]] = None,
data_keys: Optional[List[Union[str, int, DataKey]]] = None,
- ) -> Union[
- Tensor,
- List[Tensor],
- List[Union[Tensor, List[Tensor]]],
- Tuple[Union[Tensor, List[Tensor], List[Union[Tensor, List[Tensor]]]], Optional[Tensor]],
- ]:
+ ) -> Union[DataType, List[DataType]]:
"""Compute multiple tensors simultaneously according to ``self.data_keys``."""
- if data_keys is None:
- _data_keys = self.data_keys
- else:
- _data_keys = [DataKey.get(inp) for inp in data_keys]
+ self.clear_state()
+
+ self.transform_op.data_keys = self.transform_op.preproc_datakeys(data_keys)
- self._validate_args_datakeys(*args, data_keys=_data_keys)
+ self._validate_args_datakeys(*args, data_keys=self.transform_op.data_keys)
- args = self._arguments_preproc(*args, data_keys=_data_keys)
+ in_args = self._arguments_preproc(*args, data_keys=self.transform_op.data_keys)
if params is None:
# image data must exist if params is not provided.
- if DataKey.INPUT in _data_keys:
- inp = args[_data_keys.index(DataKey.INPUT)]
- if isinstance(inp, (tuple, list)):
+ if DataKey.INPUT in self.transform_op.data_keys:
+ inp = in_args[self.transform_op.data_keys.index(DataKey.INPUT)]
+ if not isinstance(inp, (Tensor,)):
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 or self.contains_3d_augmentation:
@@ -368,74 +344,78 @@ class AugmentationSequential(ImageSequential):
else:
raise ValueError("`params` must be provided whilst INPUT is not in data_keys.")
- outputs: List[Optional[Tensor]] = [None] * len(_data_keys)
-
- self.return_label = self.return_label or label is not None or self.contains_label_operations(params)
-
- for idx, (arg, dcate) in enumerate(zip(args, _data_keys)):
- # Forward the param to all input data keys
- if dcate in self.extra_args:
- extra_args = self.extra_args[dcate]
- else:
- extra_args = {}
-
- if dcate == DataKey.INPUT:
- _inp = args[idx]
-
- _out = super().forward(_inp, label, params=params, extra_args=extra_args)
- self._transform_matrix = self.get_transformation_matrix(_inp, params=params)
+ outputs: Union[Tensor, List[DataType]] = in_args
+ for param in params:
+ module = self.get_submodule(param.name)
+ outputs = self.transform_op.transform( # type: ignore
+ *outputs, module=module, param=param, extra_args=self.extra_args
+ )
+ if not isinstance(outputs, (list, tuple)):
+ # Make sure we are unpacking a list whilst post-proc
+ outputs = [outputs]
+ self._update_transform_matrix_by_module(module)
- if self.return_label and isinstance(_out, tuple):
- _input, label = _out
- elif isinstance(_out, Tensor):
- _input = _out
+ outputs = self._arguments_postproc(args, outputs, data_keys=self.transform_op.data_keys) # type: ignore
+ # Restore it back
+ self.transform_op.data_keys = self.data_keys
- outputs[idx] = _input
- # NOTE: Skip the rest here.
- continue
+ self._params = params
- # Using tensors straight-away
- if isinstance(arg, (Boxes,)):
- input = arg.data # all boxes are in (B, N, 4, 2) format now.
- else:
- input = arg
-
- for param in params:
- module = self.get_submodule(param.name)
- if (
- isinstance(module, IntensityAugmentationBase2D)
- and dcate in DataKey
- and not isinstance(module, RandomErasing)
- ):
- pass # Do nothing
- elif isinstance(module, ImageSequential) and module.is_intensity_only() and dcate in DataKey:
- pass # Do nothing
- elif isinstance(module, VideoSequential) and dcate not in [DataKey.INPUT, DataKey.MASK]:
- batch_size: int = input.size(0)
- input = input.view(-1, *input.shape[2:])
- input, label = ApplyInverse.apply_by_key(input, label, module, param, dcate, extra_args=extra_args)
- 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, RandomErasing))
- and dcate in DataKey
- ):
- input, label = ApplyInverse.apply_by_key(input, label, module, param, dcate, extra_args=extra_args)
- elif isinstance(module, MixAugmentationBaseV2):
- if dcate in [DataKey.BBOX_XYXY, DataKey.BBOX_XYWH]:
- dcate = DataKey.BBOX
- input = module(input, params=param.data, data_keys=[dcate])
- elif isinstance(module, (SequentialBase,)):
- raise ValueError(f"Unsupported Sequential {module}.")
- else:
- raise NotImplementedError(f"data_key {dcate} is not implemented for {module}.")
+ if len(outputs) == 1 and isinstance(outputs, list):
+ return outputs[0]
- if isinstance(arg, (Boxes,)):
- arg._data = input
- outputs[idx] = arg.to_tensor()
- else:
- outputs[idx] = input
- _outputs = [i for i in outputs if isinstance(i, Tensor) or KORNIA_CHECK_IS_LIST_OF_TENSOR(i)]
+ return outputs
- return self.__packup_output__(_outputs, label)
+ def _preproc_boxes(self, arg: DataType, dcate: DataKey) -> Boxes:
+ if DataKey.get(dcate) in [DataKey.BBOX]:
+ mode = "vertices_plus"
+ elif DataKey.get(dcate) in [DataKey.BBOX_XYXY]:
+ mode = "xyxy_plus"
+ elif DataKey.get(dcate) in [DataKey.BBOX_XYWH]:
+ mode = "xywh"
+ else:
+ raise ValueError(f"Unsupported mode `{DataKey.get(dcate).name}`.")
+ if isinstance(arg, (Boxes,)):
+ return arg
+ elif self.contains_video_sequential:
+ arg = cast(Tensor, arg)
+ return VideoBoxes.from_tensor(arg)
+ elif self.contains_3d_augmentation:
+ raise NotImplementedError("3D box handlers are not yet supported.")
+ else:
+ arg = cast(Tensor, arg)
+ return Boxes.from_tensor(arg, mode=mode)
+
+ def _postproc_boxes(self, in_arg: DataType, out_arg: Boxes, dcate: DataKey) -> Union[Tensor, List[Tensor], Boxes]:
+ if DataKey.get(dcate) in [DataKey.BBOX]:
+ mode = "vertices_plus"
+ elif DataKey.get(dcate) in [DataKey.BBOX_XYXY]:
+ mode = "xyxy_plus"
+ elif DataKey.get(dcate) in [DataKey.BBOX_XYWH]:
+ mode = "xywh"
+ else:
+ raise ValueError(f"Unsupported mode `{DataKey.get(dcate).name}`.")
+ # TODO: handle 3d scenarios
+ if isinstance(in_arg, (Boxes,)):
+ return out_arg
+ else:
+ return out_arg.to_tensor(mode=mode)
+
+ def _preproc_keypoints(self, arg: DataType, dcate: DataKey) -> Keypoints:
+ if self.contains_video_sequential:
+ arg = cast(Union[Tensor, List[Tensor]], arg)
+ return VideoKeypoints.from_tensor(arg)
+ elif self.contains_3d_augmentation:
+ raise NotImplementedError("3D keypoint handlers are not yet supported.")
+ else:
+ arg = cast(Tensor, arg)
+ # TODO: Add List[Tensor] in the future.
+ return Keypoints.from_tensor(arg)
+
+ def _postproc_keypoint(
+ self, in_arg: DataType, out_arg: Keypoints, dcate: DataKey
+ ) -> Union[Tensor, List[Tensor], Keypoints]:
+ if isinstance(in_arg, (Keypoints,)):
+ return out_arg
+ else:
+ return out_arg.to_tensor()
diff --git a/kornia/augmentation/container/base.py b/kornia/augmentation/container/base.py
index 9da40480a..e5c91b4b0 100644
--- a/kornia/augmentation/container/base.py
+++ b/kornia/augmentation/container/base.py
@@ -1,5 +1,5 @@
from collections import OrderedDict
-from typing import Any, Dict, Iterator, List, NamedTuple, Optional, Tuple, Union
+from typing import Dict, Iterator, List, NamedTuple, Optional, Tuple, Union
import torch
import torch.nn as nn
@@ -56,9 +56,6 @@ class SequentialBase(nn.Sequential):
mod.same_on_batch = same_on_batch
if keepdim is not None:
mod.keepdim = keepdim
- if isinstance(mod, _AugmentationBase):
- if return_transform is not None:
- mod.return_transform = return_transform
if isinstance(mod, SequentialBase):
mod.update_attribute(same_on_batch, return_transform, keepdim)
@@ -122,13 +119,6 @@ class SequentialBase(nn.Sequential):
"""Reset self._params state to None."""
self._params = None
- def update_params(self, param: Any) -> None:
- """Update self._params state."""
- if self._params is None:
- self._params = [param]
- else:
- self._params.append(param)
-
# TODO: Implement this for all submodules.
def forward_parameters(self, batch_shape: torch.Size) -> List[ParamItem]:
raise NotImplementedError
@@ -149,9 +139,6 @@ class SequentialBase(nn.Sequential):
for name, _ in named_modules:
yield ParamItem(name, None)
- def contains_label_operations(self, params: List[ParamItem]) -> bool:
- raise NotImplementedError
-
def autofill_dim(self, input: Tensor, dim_range: Tuple[int, int] = (2, 4)) -> Tuple[torch.Size, torch.Size]:
"""Fill tensor dim to the upper bound of dim_range.
diff --git a/kornia/augmentation/container/image.py b/kornia/augmentation/container/image.py
index cd1c6dbd7..f689c4672 100644
--- a/kornia/augmentation/container/image.py
+++ b/kornia/augmentation/container/image.py
@@ -1,20 +1,22 @@
from itertools import zip_longest
-from typing import Any, Dict, Iterator, List, Optional, Tuple, Type, Union, cast
+from typing import Any, Dict, Iterator, List, Optional, Tuple, Union, cast
import torch
import kornia
-from kornia.augmentation import (
- GeometricAugmentationBase2D,
- IntensityAugmentationBase2D,
- MixAugmentationBaseV2,
- RandomCrop,
-)
+from kornia.augmentation import GeometricAugmentationBase2D, IntensityAugmentationBase2D, MixAugmentationBaseV2
from kornia.augmentation.base import _AugmentationBase
from kornia.augmentation.container.base import ParamItem, SequentialBase
-from kornia.augmentation.container.utils import ApplyInverseInterface, InputApplyInverse
+from kornia.augmentation.container.ops import (
+ BoxSequentialOps,
+ InputSequentialOps,
+ KeypointSequentialOps,
+ MaskSequentialOps,
+)
from kornia.augmentation.utils import override_parameters
from kornia.core import Module, Tensor, as_tensor
+from kornia.geometry.boxes import Boxes
+from kornia.geometry.keypoints import Keypoints
__all__ = ["ImageSequential"]
@@ -45,7 +47,7 @@ class ImageSequential(SequentialBase):
Examples:
>>> _ = torch.manual_seed(77)
>>> import kornia
- >>> input, label = torch.randn(2, 3, 5, 6), torch.tensor([0, 1])
+ >>> input = torch.randn(2, 3, 5, 6)
>>> aug_list = ImageSequential(
... kornia.color.BgrToRgb(),
... kornia.augmentation.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0),
@@ -56,16 +58,14 @@ class ImageSequential(SequentialBase):
... same_on_batch=True,
... random_apply=10,
... )
- >>> out, lab = aug_list(input, label=label)
- >>> lab
- tensor([0, 1])
+ >>> out = aug_list(input)
>>> out.shape
torch.Size([2, 3, 5, 6])
Reproduce with provided params.
- >>> out2, lab2 = aug_list(input, label=label, params=aug_list._params)
- >>> torch.equal(out, out2), torch.equal(lab, lab2)
- (True, True)
+ >>> out2 = aug_list(input, params=aug_list._params)
+ >>> torch.equal(out, out2)
+ True
Perform ``OneOf`` transformation with ``random_apply=1`` and ``random_apply_weights`` in ``ImageSequential``.
@@ -102,8 +102,6 @@ class ImageSequential(SequentialBase):
f"Got {len(random_apply_weights)} and {len(self)}."
)
self.random_apply_weights = as_tensor(random_apply_weights or torch.ones((len(self),)))
- self.return_label: Optional[bool] = None
- self.apply_inverse_func: Type[ApplyInverseInterface] = InputApplyInverse
self.if_unsupported_ops = if_unsupported_ops
def _read_random_apply(
@@ -139,6 +137,9 @@ class ImageSequential(SequentialBase):
def get_random_forward_sequence(self, with_mix: bool = True) -> Tuple[Iterator[Tuple[str, Module]], bool]:
"""Get a forward sequence when random apply is in need.
+ Args:
+ with_mix: if to require a mix augmentation for the sequence.
+
Note:
Mix augmentations (e.g. RandomMixUp) will be only applied once even in a random forward.
"""
@@ -188,35 +189,20 @@ class ImageSequential(SequentialBase):
if len(mix_indices) > 1:
raise ValueError(
"Multiple mix augmentation is prohibited without enabling random_apply."
- f"Detected {len(mix_indices)}."
+ f"Detected {len(mix_indices)} mix augmentations."
)
return self.named_children()
return self.get_children_by_params(params)
- def apply_to_input(
- self,
- input: Tensor,
- label: Optional[Tensor],
- module: Optional[Module],
- param: ParamItem,
- extra_args: Dict[str, Any],
- ) -> Tuple[Tensor, Optional[Tensor]]:
- if module is None:
- module = self.get_submodule(param.name)
- return self.apply_inverse_func.apply_trans(input, label, module, param, extra_args)
-
def forward_parameters(self, batch_shape: torch.Size) -> List[ParamItem]:
named_modules: Iterator[Tuple[str, Module]] = self.get_forward_sequence()
params: List[ParamItem] = []
mod_param: Union[Dict[str, Tensor], List[ParamItem]]
for name, module in named_modules:
- if isinstance(module, RandomCrop):
- mod_param = module.forward_parameters_precrop(batch_shape)
- param = ParamItem(name, mod_param)
- elif isinstance(module, (_AugmentationBase, MixAugmentationBaseV2, ImageSequential)):
+ if isinstance(module, (_AugmentationBase, MixAugmentationBaseV2, ImageSequential)):
mod_param = module.forward_parameters(batch_shape)
param = ParamItem(name, mod_param)
else:
@@ -225,21 +211,6 @@ class ImageSequential(SequentialBase):
params.append(param)
return params
- def contains_label_operations(self, params: List[ParamItem]) -> bool:
- """Check if current sequential contains label-involved operations like MixUp."""
- for param in params:
- if param.name.startswith("RandomMixUp_") or param.name.startswith("RandomCutMix_"):
- return True
- return False
-
- def __packup_output__(
- self, output: Tensor, label: Optional[Tensor] = None
- ) -> Union[Tensor, Tuple[Tensor, Optional[Tensor]]]:
- if self.return_label:
- # Implicitly indicating the label cannot be optional since there is a mix aug
- return output, label
- return output
-
def identity_matrix(self, input) -> Tensor:
"""Return identity matrix."""
return kornia.eye_like(3, input)
@@ -266,11 +237,7 @@ class ImageSequential(SequentialBase):
# Define as 1 for broadcasting
res_mat: Optional[Tensor] = None
for (_, module), param in zip(named_modules, params if params is not None else []):
- if (
- isinstance(module, (_AugmentationBase,))
- and not isinstance(module, MixAugmentationBaseV2)
- and isinstance(param.data, dict)
- ):
+ if isinstance(module, (GeometricAugmentationBase2D,)) and isinstance(param.data, dict):
to_apply = param.data['batch_prob']
ori_shape = input.shape
try:
@@ -302,6 +269,7 @@ class ImageSequential(SequentialBase):
res_mat = mat if res_mat is None else mat @ res_mat
return res_mat
+ # TODO: Make this as a class property to avoid running every time.
def is_intensity_only(self, strict: bool = True) -> bool:
"""Check if all transformations are intensity-based.
@@ -325,6 +293,54 @@ class ImageSequential(SequentialBase):
return False
return True
+ def transform_inputs(self, input: Tensor, params: List[ParamItem], extra_args: Dict[str, Any] = {}) -> Tensor:
+ for param in params:
+ module = self.get_submodule(param.name)
+ input = InputSequentialOps.transform(input, module=module, param=param, extra_args=extra_args)
+ return input
+
+ def inverse_inputs(self, input: Tensor, params: List[ParamItem], extra_args: Dict[str, Any] = {}) -> Tensor:
+ for (name, module), param in zip_longest(list(self.get_forward_sequence(params))[::-1], params[::-1]):
+ input = InputSequentialOps.inverse(input, module=module, param=param, extra_args=extra_args)
+ return input
+
+ def transform_masks(self, input: Tensor, params: List[ParamItem], extra_args: Dict[str, Any] = {}) -> Tensor:
+ for param in params:
+ module = self.get_submodule(param.name)
+ input = MaskSequentialOps.transform(input, module=module, param=param, extra_args=extra_args)
+ return input
+
+ def inverse_masks(self, input: Tensor, params: List[ParamItem], extra_args: Dict[str, Any] = {}) -> Tensor:
+ for (name, module), param in zip_longest(list(self.get_forward_sequence(params))[::-1], params[::-1]):
+ input = MaskSequentialOps.inverse(input, module=module, param=param, extra_args=extra_args)
+ return input
+
+ def transform_boxes(self, input: Boxes, params: List[ParamItem], extra_args: Dict[str, Any] = {}) -> Boxes:
+ for param in params:
+ module = self.get_submodule(param.name)
+ input = BoxSequentialOps.transform(input, module=module, param=param, extra_args=extra_args)
+ return input
+
+ def inverse_boxes(self, input: Boxes, params: List[ParamItem], extra_args: Dict[str, Any] = {}) -> Boxes:
+ for (name, module), param in zip_longest(list(self.get_forward_sequence(params))[::-1], params[::-1]):
+ input = BoxSequentialOps.inverse(input, module=module, param=param, extra_args=extra_args)
+ return input
+
+ def transform_keypoints(
+ self, input: Keypoints, params: List[ParamItem], extra_args: Dict[str, Any] = {}
+ ) -> Keypoints:
+ for param in params:
+ module = self.get_submodule(param.name)
+ input = KeypointSequentialOps.transform(input, module=module, param=param, extra_args=extra_args)
+ return input
+
+ def inverse_keypoints(
+ self, input: Keypoints, params: List[ParamItem], extra_args: Dict[str, Any] = {}
+ ) -> Keypoints:
+ for (name, module), param in zip_longest(list(self.get_forward_sequence(params))[::-1], params[::-1]):
+ input = KeypointSequentialOps.inverse(input, module=module, param=param, extra_args=extra_args)
+ return input
+
def inverse(
self, input: Tensor, params: Optional[List[ParamItem]] = None, extra_args: Dict[str, Any] = {}
) -> Tensor:
@@ -341,48 +357,26 @@ class ImageSequential(SequentialBase):
)
params = self._params
- for (name, module), param in zip_longest(list(self.get_forward_sequence(params))[::-1], params[::-1]):
- if isinstance(module, (_AugmentationBase, ImageSequential)):
- _mb: List[ParamItem] = [p for p in params if name in p]
- maybe_param = _mb if len(_mb) > 0 else [param]
-
- if isinstance(module, IntensityAugmentationBase2D):
- pass # Do nothing
- elif isinstance(module, ImageSequential) and module.is_intensity_only():
- pass # Do nothing
- elif isinstance(module, ImageSequential) and isinstance(maybe_param, ParamItem):
- input = module.inverse(input, maybe_param, extra_args=extra_args)
- elif isinstance(module, (GeometricAugmentationBase2D,)):
- input = self.apply_inverse_func.inverse(input, module, param, extra_args=extra_args)
- else:
- pass
- # raise NotImplementedError(f"`inverse` is not implemented for {module}.")
+ input = self.inverse_inputs(input, params, extra_args=extra_args)
return input
def forward(
- self,
- input: Tensor,
- label: Optional[Tensor] = None,
- params: Optional[List[ParamItem]] = None,
- extra_args: Dict[str, Any] = {},
- ) -> Union[Tensor, Tuple[Tensor, Optional[Tensor]]]:
+ self, input: Tensor, params: Optional[List[ParamItem]] = None, extra_args: Dict[str, Any] = {}
+ ) -> Tensor:
+
self.clear_state()
+
if params is None:
inp = input
_, out_shape = self.autofill_dim(inp, dim_range=(2, 4))
params = self.forward_parameters(out_shape)
- if self.return_label is None:
- self.return_label = label is not None or self.contains_label_operations(params)
for param in params:
module = self.get_submodule(param.name)
- input, label = self.apply_to_input(input, label, module, param=param, extra_args=extra_args)
- if isinstance(module, (_AugmentationBase, MixAugmentationBaseV2, SequentialBase)):
- param = ParamItem(param.name, module._params)
- else:
- param = ParamItem(param.name, None)
- self.update_params(param)
- return self.__packup_output__(input, label)
+ input = InputSequentialOps.transform(input, module=module, param=param, extra_args=extra_args)
+
+ self._params = params
+ return input
def _get_new_batch_shape(param: ParamItem, batch_shape: torch.Size) -> torch.Size:
diff --git a/kornia/augmentation/container/ops.py b/kornia/augmentation/container/ops.py
new file mode 100644
index 000000000..3fa230ee8
--- /dev/null
+++ b/kornia/augmentation/container/ops.py
@@ -0,0 +1,390 @@
+from abc import ABCMeta, abstractmethod
+from typing import Any, Callable, Dict, Generic, List, Optional, Type, TypeVar, Union
+
+import kornia
+from kornia.augmentation import GeometricAugmentationBase2D, GeometricAugmentationBase3D, MixAugmentationBaseV2
+from kornia.augmentation.base import _AugmentationBase
+from kornia.augmentation.container.base import ParamItem
+from kornia.constants import DataKey
+from kornia.core import Module, Tensor
+from kornia.geometry.boxes import Boxes
+from kornia.geometry.keypoints import Keypoints
+
+DataType = Union[Tensor, List[Tensor], Boxes, Keypoints]
+
+T = TypeVar('T')
+
+
+class SequentialOpsInterface(Generic[T], metaclass=ABCMeta):
+ """Abstract interface for applying and inversing transformations."""
+
+ @classmethod
+ def get_instance_module_param(cls, param: ParamItem) -> Dict[str, Tensor]:
+ if isinstance(param, ParamItem) and isinstance(param.data, dict):
+ _params = param.data
+ else:
+ raise TypeError(f'Expected param (ParamItem.data) be a dictionary. Gotcha {param}.')
+ return _params
+
+ @classmethod
+ def get_sequential_module_param(cls, param: ParamItem) -> List[ParamItem]:
+ if isinstance(param, ParamItem) and isinstance(param.data, list):
+ _params = param.data
+ else:
+ raise TypeError(f'Expected param (ParamItem.data) be a list. Gotcha {param}.')
+ return _params
+
+ @classmethod
+ @abstractmethod
+ def transform(cls, input: T, module: Module, param: ParamItem, extra_args: Dict[str, Any] = {}) -> T:
+ """Apply a transformation with respect to the parameters.
+
+ Args:
+ input: the input tensor.
+ module: any torch Module but only kornia augmentation modules will count
+ to apply transformations.
+ param: the corresponding parameters to the module.
+ """
+ raise NotImplementedError
+
+ @classmethod
+ @abstractmethod
+ def inverse(cls, input: T, module: Module, param: ParamItem, extra_args: Dict[str, Any] = {}) -> T:
+ """Inverse a transformation with respect to the parameters.
+
+ Args:
+ input: the input tensor.
+ module: any torch Module but only kornia augmentation modules will count
+ to apply transformations.
+ param: the corresponding parameters to the module.
+ """
+ raise NotImplementedError
+
+
+class AugmentationSequentialOps:
+ def __init__(self, data_keys: List[DataKey]) -> None:
+ self._data_keys = data_keys
+
+ @property
+ def data_keys(self) -> List[DataKey]:
+ return self._data_keys
+
+ @data_keys.setter
+ def data_keys(self, data_keys: List[DataKey]) -> None:
+ self._data_keys = [DataKey.get(inp) for inp in data_keys]
+
+ def preproc_datakeys(self, data_keys: Optional[List[Union[str, int, DataKey]]] = None) -> List[DataKey]:
+ if data_keys is None:
+ return self.data_keys
+ else:
+ return [DataKey.get(inp) for inp in data_keys]
+
+ def _get_op(self, data_key: DataKey) -> Type[SequentialOpsInterface[Any]]:
+ """Return the corresponding operation given a data key."""
+ if data_key == DataKey.INPUT:
+ return InputSequentialOps
+ if data_key == DataKey.MASK:
+ return MaskSequentialOps
+ if data_key == DataKey.BBOX or data_key == DataKey.BBOX_XYWH or data_key == DataKey.BBOX_XYXY:
+ return BoxSequentialOps
+ if data_key == DataKey.KEYPOINTS:
+ return KeypointSequentialOps
+ raise RuntimeError(f"Operation for `{data_key.name}` is not found.")
+
+ def transform(
+ self,
+ *arg: DataType,
+ module: Module,
+ param: ParamItem,
+ extra_args: Dict[DataKey, Dict[str, Any]],
+ data_keys: Optional[List[Union[str, int, DataKey]]] = None,
+ ) -> Union[DataType, List[DataType]]:
+ _data_keys = self.preproc_datakeys(data_keys)
+ outputs = []
+ for inp, dcate in zip(arg, _data_keys):
+ op = self._get_op(dcate)
+ extra_arg = extra_args[dcate] if dcate in extra_args else {}
+ outputs.append(op.transform(inp, module, param=param, extra_args=extra_arg))
+ if len(outputs) == 1 and isinstance(outputs, (list, tuple)):
+ return outputs[0]
+ return outputs
+
+ def inverse(
+ self,
+ *arg: DataType,
+ module: Module,
+ param: ParamItem,
+ extra_args: Dict[DataKey, Dict[str, Any]],
+ data_keys: Optional[List[Union[str, int, DataKey]]] = None,
+ ) -> Union[DataType, List[DataType]]:
+ _data_keys = self.preproc_datakeys(data_keys)
+ outputs = []
+ for inp, dcate in zip(arg, _data_keys):
+ op = self._get_op(dcate)
+ extra_arg = extra_args[dcate] if dcate in extra_args else {}
+ outputs.append(op.inverse(inp, module, param=param, extra_args=extra_arg))
+ if len(outputs) == 1 and isinstance(outputs, (list, tuple)):
+ return outputs[0]
+ return outputs
+
+
+def make_input_only_sequential(module: 'kornia.augmentation.ImageSequential') -> Callable[..., Tensor]:
+ """Disable all other additional inputs (e.g. ) for ImageSequential."""
+
+ def f(*args, **kwargs):
+ out = module(*args, **kwargs)
+ return out
+
+ return f
+
+
+def get_geometric_only_param(module: 'kornia.augmentation.ImageSequential', param: List[ParamItem]) -> List[ParamItem]:
+ named_modules = module.get_forward_sequence(param)
+
+ res: List[ParamItem] = []
+ for (_, mod), p in zip(named_modules, param):
+ if isinstance(mod, (GeometricAugmentationBase2D, GeometricAugmentationBase3D)):
+ res.append(p)
+ return res
+
+
+class InputSequentialOps(SequentialOpsInterface[Tensor]):
+ @classmethod
+ def transform(cls, input: Tensor, module: Module, param: ParamItem, extra_args: Dict[str, Any] = {}) -> Tensor:
+ if isinstance(module, (_AugmentationBase, MixAugmentationBaseV2)):
+ input = module(input, params=cls.get_instance_module_param(param), **extra_args)
+ elif isinstance(module, kornia.augmentation.ImageSequential):
+ input = module.transform_inputs(input, params=cls.get_sequential_module_param(param), extra_args=extra_args)
+ else:
+ if param.data is not None:
+ raise AssertionError(f"Non-augmentaion operation {param.name} require empty parameters. Got {param}.")
+ input = module(input)
+ return input
+
+ @classmethod
+ def inverse(cls, input: Tensor, module: Module, param: ParamItem, extra_args: Dict[str, Any] = {}) -> Tensor:
+ if isinstance(module, GeometricAugmentationBase2D):
+ input = module.inverse(input, params=cls.get_instance_module_param(param), **extra_args)
+ elif isinstance(module, (GeometricAugmentationBase3D,)):
+ raise NotImplementedError(
+ "The support for 3d inverse operations are not yet supported. "
+ "You are welcome to file a PR in our repo."
+ )
+ elif isinstance(module, kornia.augmentation.ImageSequential) and not module.is_intensity_only():
+ input = module.inverse_inputs(input, params=cls.get_sequential_module_param(param), extra_args=extra_args)
+ return input
+
+
+class MaskSequentialOps(SequentialOpsInterface[Tensor]):
+ """Apply and inverse transformations for mask tensors."""
+
+ @classmethod
+ def transform(cls, input: Tensor, module: Module, param: ParamItem, extra_args: Dict[str, Any] = {}) -> Tensor:
+ """Apply a transformation with respect to the parameters.
+
+ Args:
+ input: the input tensor.
+ module: any torch Module but only kornia augmentation modules will count
+ to apply transformations.
+ param: the corresponding parameters to the module.
+ """
+ if isinstance(module, (GeometricAugmentationBase2D,)):
+ input = module.transform_masks(
+ input,
+ params=cls.get_instance_module_param(param),
+ flags=module.flags,
+ transform=module.transform_matrix,
+ **extra_args,
+ )
+
+ elif isinstance(module, (GeometricAugmentationBase3D,)):
+ raise NotImplementedError(
+ "The support for 3d mask operations are not yet supported. You are welcome to file a PR in our repo."
+ )
+
+ elif isinstance(module, (_AugmentationBase)):
+ input = module.transform_masks(
+ input, params=cls.get_instance_module_param(param), flags=module.flags, **extra_args
+ )
+
+ elif isinstance(module, kornia.augmentation.ImageSequential) and not module.is_intensity_only():
+ input = module.transform_masks(input, params=cls.get_sequential_module_param(param), extra_args=extra_args)
+ return input
+
+ @classmethod
+ def inverse(cls, input: Tensor, module: Module, param: ParamItem, extra_args: Dict[str, Any] = {}) -> Tensor:
+ """Inverse a transformation with respect to the parameters.
+
+ Args:
+ input: the input tensor.
+ module: any torch Module but only kornia augmentation modules will count
+ to apply transformations.
+ param: the corresponding parameters to the module.
+ """
+
+ if isinstance(module, (GeometricAugmentationBase2D,)):
+ if module.transform_matrix is None:
+ raise ValueError(f"No valid transformation matrix found in {module.__class__}.")
+ transform = module.compute_inverse_transformation(module.transform_matrix)
+ input = module.inverse_masks(
+ input,
+ params=cls.get_instance_module_param(param),
+ flags=module.flags,
+ transform=transform,
+ **extra_args,
+ )
+
+ elif isinstance(module, (GeometricAugmentationBase3D,)):
+ raise NotImplementedError(
+ "The support for 3d mask operations are not yet supported. You are welcome to file a PR in our repo."
+ )
+
+ elif isinstance(module, kornia.augmentation.ImageSequential):
+ input = module.inverse_masks(input, params=cls.get_sequential_module_param(param), extra_args=extra_args)
+
+ return input
+
+
+class BoxSequentialOps(SequentialOpsInterface[Boxes]):
+ """Apply and inverse transformations for bounding box tensors.
+
+ This is for transform boxes in the format (B, N, 4, 2).
+ """
+
+ @classmethod
+ def transform(cls, input: Boxes, module: Module, param: ParamItem, extra_args: Dict[str, Any] = {}) -> Boxes:
+ """Apply a transformation with respect to the parameters.
+
+ Args:
+ input: the input tensor, (B, N, 4, 2) or (B, 4, 2).
+ module: any torch Module but only kornia augmentation modules will count
+ to apply transformations.
+ param: the corresponding parameters to the module.
+ """
+ _input = input.clone()
+
+ if isinstance(module, (GeometricAugmentationBase2D,)):
+ _input = module.transform_boxes(
+ _input,
+ cls.get_instance_module_param(param),
+ module.flags,
+ transform=module.transform_matrix,
+ **extra_args,
+ )
+
+ elif isinstance(module, (GeometricAugmentationBase3D,)):
+ raise NotImplementedError(
+ "The support for 3d box operations are not yet supported. You are welcome to file a PR in our repo."
+ )
+
+ elif isinstance(module, kornia.augmentation.ImageSequential) and not module.is_intensity_only():
+ _input = module.transform_boxes(
+ _input, params=cls.get_sequential_module_param(param), extra_args=extra_args
+ )
+
+ return _input
+
+ @classmethod
+ def inverse(cls, input: Boxes, module: Module, param: ParamItem, extra_args: Dict[str, Any] = {}) -> Boxes:
+ """Inverse a transformation with respect to the parameters.
+
+ Args:
+ input: the input tensor.
+ module: any torch Module but only kornia augmentation modules will count
+ to apply transformations.
+ param: the corresponding parameters to the module.
+ """
+ _input = input.clone()
+
+ if isinstance(module, (GeometricAugmentationBase2D,)):
+ if module.transform_matrix is None:
+ raise ValueError(f"No valid transformation matrix found in {module.__class__}.")
+ transform = module.compute_inverse_transformation(module.transform_matrix)
+ _input = module.inverse_boxes(
+ _input, param.data, module.flags, transform=transform, **extra_args # type: ignore
+ )
+
+ elif isinstance(module, (GeometricAugmentationBase3D,)):
+ raise NotImplementedError(
+ "The support for 3d box operations are not yet supported. You are welcome to file a PR in our repo."
+ )
+
+ elif isinstance(module, kornia.augmentation.ImageSequential) and not module.is_intensity_only():
+ _input = module.inverse_boxes(_input, params=cls.get_sequential_module_param(param), extra_args=extra_args)
+ return _input
+
+
+class KeypointSequentialOps(SequentialOpsInterface[Keypoints]):
+ """Apply and inverse transformations for keypoints tensors.
+
+ This is for transform keypoints in the format (B, N, 2).
+ """
+
+ @classmethod
+ def transform(
+ cls, input: Keypoints, module: Module, param: ParamItem, extra_args: Dict[str, Any] = {}
+ ) -> Keypoints:
+ """Apply a transformation with respect to the parameters.
+
+ Args:
+ input: the input tensor, (B, N, 4, 2) or (B, 4, 2).
+ module: any torch Module but only kornia augmentation modules will count
+ to apply transformations.
+ param: the corresponding parameters to the module.
+ """
+ _input = input.clone()
+
+ if isinstance(module, (GeometricAugmentationBase2D,)):
+ _input = module.transform_keypoints(
+ _input,
+ cls.get_instance_module_param(param),
+ module.flags,
+ transform=module.transform_matrix,
+ **extra_args,
+ )
+
+ elif isinstance(module, (GeometricAugmentationBase3D,)):
+ raise NotImplementedError(
+ "The support for 3d keypoint operations are not yet supported. "
+ "You are welcome to file a PR in our repo."
+ )
+
+ elif isinstance(module, kornia.augmentation.ImageSequential) and not module.is_intensity_only():
+ _input = module.transform_keypoints(
+ _input, params=cls.get_sequential_module_param(param), extra_args=extra_args
+ )
+
+ return _input
+
+ @classmethod
+ def inverse(cls, input: Keypoints, module: Module, param: ParamItem, extra_args: Dict[str, Any] = {}) -> Keypoints:
+ """Inverse a transformation with respect to the parameters.
+
+ Args:
+ input: the input tensor.
+ module: any torch Module but only kornia augmentation modules will count
+ to apply transformations.
+ param: the corresponding parameters to the module.
+ """
+ _input = input.clone()
+
+ if isinstance(module, (GeometricAugmentationBase2D,)):
+ if module.transform_matrix is None:
+ raise ValueError(f"No valid transformation matrix found in {module.__class__}.")
+ transform = module.compute_inverse_transformation(module.transform_matrix)
+ _input = module.inverse_keypoints(
+ _input, cls.get_instance_module_param(param), module.flags, transform=transform, **extra_args
+ )
+
+ elif isinstance(module, (GeometricAugmentationBase3D,)):
+ raise NotImplementedError(
+ "The support for 3d keypoint operations are not yet supported. "
+ "You are welcome to file a PR in our repo."
+ )
+
+ elif isinstance(module, kornia.augmentation.ImageSequential) and not module.is_intensity_only():
+ _input = module.inverse_keypoints(
+ _input, params=cls.get_sequential_module_param(param), extra_args=extra_args
+ )
+
+ return _input
diff --git a/kornia/augmentation/container/patch.py b/kornia/augmentation/container/patch.py
index 5b365cde4..47d8724c5 100644
--- a/kornia/augmentation/container/patch.py
+++ b/kornia/augmentation/container/patch.py
@@ -7,9 +7,12 @@ from kornia.augmentation import MixAugmentationBaseV2
from kornia.augmentation.base import _AugmentationBase
from kornia.augmentation.container.base import SequentialBase
from kornia.augmentation.container.image import ImageSequential, ParamItem
+from kornia.augmentation.container.ops import InputSequentialOps
from kornia.contrib.extract_patches import extract_tensor_patches
from kornia.core import Module, Tensor, concatenate
from kornia.core import pad as fpad
+from kornia.geometry.boxes import Boxes
+from kornia.geometry.keypoints import Keypoints
__all__ = ["PatchSequential"]
@@ -150,12 +153,7 @@ class PatchSequential(ImageSequential):
self.grid_size = grid_size
self.padding = padding
self.patchwise_apply = patchwise_apply
-
- def contains_label_operations(self, params: List[PatchParamItem]) -> bool: # type: ignore[override]
- for param in params:
- if param.param.name.startswith("RandomMixUp") or param.param.name.startswith("RandomCutMix"):
- return True
- return False
+ self._params: Optional[List[PatchParamItem]] # type: ignore[assignment]
def compute_padding(
self, input: Tensor, padding: str, grid_size: Optional[Tuple[int, int]] = None
@@ -303,81 +301,87 @@ class PatchSequential(ImageSequential):
else:
yield ParamItem(s[0], None), i
- def apply_by_param(
- self, input: Tensor, label: Optional[Tensor], params: PatchParamItem
- ) -> Tuple[Tensor, Optional[Tensor], PatchParamItem]:
- _input: Tensor
+ def forward_by_params(self, input: Tensor, params: List[PatchParamItem]) -> Tensor:
in_shape = input.shape
- _input = input[params.indices]
+ input = input.reshape(-1, *in_shape[-3:])
- _label: Optional[Tensor]
- if label is not None:
- _label = label[params.indices]
- else:
- _label = label
+ for patch_param in params:
+ # input, out_param = self.apply_by_param(input, params=patch_param)
+ module = self.get_submodule(patch_param.param.name)
+ _input = input[patch_param.indices]
+ output = InputSequentialOps.transform(_input, module, patch_param.param, extra_args={})
+ input[patch_param.indices] = output
- module = self.get_submodule(params.param.name)
- output, out_label = self.apply_to_input(_input, _label, module, params.param, extra_args={})
+ return input.reshape(in_shape)
- if isinstance(module, (_AugmentationBase, SequentialBase, MixAugmentationBaseV2)):
- out_param = ParamItem(params.param.name, module._params)
- else:
- out_param = ParamItem(params.param.name, None)
-
- if isinstance(output, (tuple,)) and isinstance(input, (tuple,)):
- input[0][params.indices] = output[0]
- input[1][params.indices] = output[1]
- elif isinstance(output, (tuple,)) and not isinstance(input, (tuple,)):
- input[params.indices] = output[0]
- input = (input, output[1])
- elif not isinstance(output, (tuple,)) and isinstance(input, (tuple,)):
- input[0][params.indices] = output
- elif not isinstance(output, (tuple,)) and not isinstance(input, (tuple,)):
- input[params.indices] = output
-
- # TODO: this label handling is naive that may not be able to handle complex cases.
- _label = None
- if label is not None and out_label is not None:
- if len(out_label.shape) == 1:
- # Weird the mypy error though it is as same as in the next block
- _label = torch.ones(in_shape[0] * in_shape[1], device=out_label.device, dtype=out_label.dtype) * -1
- _label = label
- else:
- _label = (
- torch.ones(in_shape[0], *out_label.shape[1:], device=out_label.device, dtype=out_label.dtype) * -1
- )
- _label[:, 0] = label
- _label[params.indices] = out_label
- elif label is None and out_label is not None:
- if len(out_label.shape) == 1:
- _label = torch.ones(in_shape[0] * in_shape[1], device=out_label.device, dtype=out_label.dtype) * -1
- else:
- _label = (
- torch.ones(in_shape[0], *out_label.shape[1:], device=out_label.device, dtype=out_label.dtype) * -1
- )
- _label[params.indices] = out_label
+ def transform_inputs( # type: ignore[override]
+ self, input: Tensor, params: List[PatchParamItem], extra_args: Dict[str, Any] = {}
+ ) -> Tensor:
+ pad = self.compute_padding(input, self.padding)
+ input = self.extract_patches(input, self.grid_size, pad)
+ input = self.forward_by_params(input, params)
+ input = self.restore_from_patches(input, self.grid_size, pad=pad)
- return input, _label, PatchParamItem(params.indices, param=out_param)
+ return input
- def forward_by_params(
- self, input: Tensor, label: Optional[Tensor], params: List[PatchParamItem]
- ) -> Union[Tensor, Tuple[Tensor, Optional[Tensor]]]:
- _input: Tensor
- in_shape = input.shape
- _input = input.reshape(-1, *in_shape[-3:])
+ def inverse_inputs( # type: ignore[override]
+ self, input: Tensor, params: List[PatchParamItem], extra_args: Dict[str, Any] = {}
+ ) -> Tensor:
+ if self.is_intensity_only():
+ return input
- if label is not None:
- label = concatenate([label] * in_shape[1], 0)
+ raise NotImplementedError("PatchSequential inverse cannot be used with geometric transformations.")
- self.clear_state()
- for patch_param in params:
- _input, label, out_param = self.apply_by_param(_input, label, params=patch_param)
- self.update_params(out_param)
- _input = _input.reshape(in_shape)
- return _input, label
+ def transform_masks( # type: ignore[override]
+ self, input: Tensor, params: List[PatchParamItem], extra_args: Dict[str, Any] = {}
+ ) -> Tensor:
+ if self.is_intensity_only():
+ return input
- def inverse(
- self, input: Tensor, params: Optional[List[ParamItem]] = None, extra_args: Dict[str, Any] = {}
+ raise NotImplementedError("PatchSequential for boxes cannot be used with geometric transformations.")
+
+ def inverse_masks( # type: ignore[override]
+ self, input: Tensor, params: List[PatchParamItem], extra_args: Dict[str, Any] = {}
+ ) -> Tensor:
+ if self.is_intensity_only():
+ return input
+
+ raise NotImplementedError("PatchSequential inverse cannot be used with geometric transformations.")
+
+ def transform_boxes( # type: ignore[override]
+ self, input: Boxes, params: List[PatchParamItem], extra_args: Dict[str, Any] = {}
+ ) -> Boxes:
+ if self.is_intensity_only():
+ return input
+
+ raise NotImplementedError("PatchSequential for boxes cannot be used with geometric transformations.")
+
+ def inverse_boxes( # type: ignore[override]
+ self, input: Boxes, params: List[PatchParamItem], extra_args: Dict[str, Any] = {}
+ ) -> Boxes:
+ if self.is_intensity_only():
+ return input
+
+ raise NotImplementedError("PatchSequential inverse cannot be used with geometric transformations.")
+
+ def transform_keypoints( # type: ignore[override]
+ self, input: Keypoints, params: List[PatchParamItem], extra_args: Dict[str, Any] = {}
+ ) -> Keypoints:
+ if self.is_intensity_only():
+ return input
+
+ raise NotImplementedError("PatchSequential for keypoints cannot be used with geometric transformations.")
+
+ def inverse_keypoints( # type: ignore[override]
+ self, input: Keypoints, params: List[PatchParamItem], extra_args: Dict[str, Any] = {}
+ ) -> Keypoints:
+ if self.is_intensity_only():
+ return input
+
+ raise NotImplementedError("PatchSequential inverse cannot be used with geometric transformations.")
+
+ def inverse( # type: ignore[override]
+ self, input: Tensor, params: Optional[List[PatchParamItem]] = None, extra_args: Dict[str, Any] = {}
) -> Tensor:
"""Inverse transformation.
@@ -389,25 +393,17 @@ class PatchSequential(ImageSequential):
raise NotImplementedError("PatchSequential inverse cannot be used with geometric transformations.")
- def forward( # type: ignore[override]
- self, input: Tensor, label: Optional[Tensor] = None, params: Optional[List[PatchParamItem]] = None
- ) -> Union[Tensor, Tuple[Tensor, Optional[Tensor]]]:
+ def forward(self, input: Tensor, params: Optional[List[PatchParamItem]] = None) -> Tensor: # type: ignore[override]
"""Input transformation will be returned if input is a tuple."""
# BCHW -> B(patch)CHW
if isinstance(input, (tuple,)):
raise ValueError("tuple input is not currently supported.")
- _input: Tensor
-
- pad = self.compute_padding(input, self.padding)
- input = self.extract_patches(input, self.grid_size, pad)
if params is None:
params = self.forward_parameters(input.shape)
- _input, label = self.forward_by_params(input, label, params)
-
- _input = self.restore_from_patches(_input, self.grid_size, pad=pad)
+ output = self.transform_inputs(input, params=params)
- self.return_label = label is not None or self.contains_label_operations(params)
+ self._params = params
- return self.__packup_output__(_input, label)
+ return output
diff --git a/kornia/augmentation/container/utils.py b/kornia/augmentation/container/utils.py
deleted file mode 100644
index 8ef9f8a43..000000000
--- a/kornia/augmentation/container/utils.py
+++ /dev/null
@@ -1,665 +0,0 @@
-import warnings
-from abc import ABCMeta, abstractmethod
-from functools import partial
-from typing import Any, Callable, Dict, Iterator, List, Optional, Tuple, Type, Union, cast
-
-import torch
-
-import kornia # lazy loading for circular dependencies
-from kornia.augmentation import GeometricAugmentationBase2D, MixAugmentationBaseV2, RandomCrop, RandomErasing
-from kornia.augmentation.base import _AugmentationBase
-from kornia.augmentation.container.base import ParamItem
-from kornia.augmentation.utils import override_parameters
-from kornia.constants import DataKey
-from kornia.core import Module, Tensor, as_tensor
-from kornia.geometry.bbox import transform_bbox
-from kornia.geometry.linalg import transform_points
-from kornia.testing import KORNIA_UNWRAP
-from kornia.utils.helpers import _torch_inverse_cast
-
-
-def _get_geometric_only_param(module: 'kornia.augmentation.ImageSequential', param: List[ParamItem]) -> List[ParamItem]:
- named_modules: Iterator[Tuple[str, Module]] = module.get_forward_sequence(param)
-
- res: List[ParamItem] = []
- for (_, mod), p in zip(named_modules, param):
- if isinstance(mod, (GeometricAugmentationBase2D,)):
- res.append(p)
- return res
-
-
-class ApplyInverseInterface(metaclass=ABCMeta):
- """Abstract interface for applying and inversing transformations."""
-
- @classmethod
- @abstractmethod
- def apply_trans(
- cls, input: Tensor, label: Optional[Tensor], module: Module, param: ParamItem, extra_args: Dict[str, Any] = {}
- ) -> Tuple[Tensor, Optional[Tensor]]:
- """Apply a transformation with respect to the parameters.
-
- Args:
- input: the input tensor.
- label: the optional label tensor.
- module: any torch Module but only kornia augmentation modules will count
- to apply transformations.
- param: the corresponding parameters to the module.
- """
- raise NotImplementedError
-
- @classmethod
- @abstractmethod
- def inverse(
- cls, input: Tensor, module: Module, param: Optional[ParamItem] = None, extra_args: Dict[str, Any] = {}
- ) -> Tensor:
- """Inverse a transformation with respect to the parameters.
-
- Args:
- input: the input tensor.
- module: any torch Module but only kornia augmentation modules will count
- to apply transformations.
- param: the corresponding parameters to the module.
- """
- raise NotImplementedError
-
-
-class ApplyInverseImpl(ApplyInverseInterface):
- """Standard matrix apply and inverse methods."""
-
- apply_func: Callable[[Tensor, Tensor], Tensor]
-
- @classmethod
- def apply_trans(
- cls, input: Tensor, label: Optional[Tensor], module: Module, param: ParamItem, extra_args: Dict[str, Any] = {}
- ) -> Tuple[Tensor, Optional[Tensor]]:
- """Apply a transformation with respect to the parameters.
-
- Args:
- input: the input tensor.
- label: the optional label tensor.
- module: any torch Module but only kornia augmentation modules will count
- to apply transformations.
- param: the corresponding parameters to the module.
- """
- mat: Optional[Tensor]
- if hasattr(module, "transform_matrix") and module.transform_matrix is not None:
- mat = cast(Tensor, module.transform_matrix)
- else:
- mat = cls._get_transformation(input, module, param, extra_args=extra_args)
- mat = as_tensor(mat, device=input.device, dtype=input.dtype)
-
- to_apply = None
- if isinstance(module, _AugmentationBase) and isinstance(param.data, dict):
- to_apply = param.data['batch_prob']
- elif isinstance(module, kornia.augmentation.ImageSequential):
- to_apply = torch.ones(input.shape[0], device=input.device, dtype=input.dtype).bool()
-
- # If any inputs need to be transformed.
- if mat is not None and to_apply is not None and to_apply.sum() != 0 and input.numel() > 0:
- input[to_apply] = cls.apply_func(mat[to_apply], input[to_apply])
-
- return input, label
-
- @classmethod
- def inverse(
- cls, input: Tensor, module: Module, param: Optional[ParamItem] = None, extra_args: Dict[str, Any] = {}
- ) -> Tensor:
- """Inverse a transformation with respect to the parameters.
-
- Args:
- input: the input tensor.
- module: any torch Module but only kornia augmentation modules will count
- to apply transformations.
- param: the corresponding parameters to the module.
- """
- mat: Optional[Tensor]
- if hasattr(module, "transform_matrix") and module.transform_matrix is not None:
- mat = cast(Tensor, module.transform_matrix)
- else:
- mat = cls._get_transformation(input, module, param, extra_args=extra_args)
- mat = as_tensor(mat, device=input.device, dtype=input.dtype)
-
- if mat is not None:
- transform: Tensor = cls._get_inverse_transformation(mat)
- input = cls.apply_func(as_tensor(transform, device=input.device, dtype=input.dtype), input)
- return input
-
- @classmethod
- def _get_transformation(
- cls, input: Tensor, module: Module, maybe_param: Optional[ParamItem] = None, extra_args: Dict[str, Any] = {}
- ) -> Optional[Tensor]:
-
- if (
- isinstance(module, (GeometricAugmentationBase2D, kornia.augmentation.ImageSequential))
- and maybe_param is None
- ):
- raise ValueError(f"Parameters of transformation matrix for {module} has not been computed.")
-
- maybe_mat: Optional[Tensor] = None
- param = KORNIA_UNWRAP(maybe_param, ParamItem)
- if isinstance(module, GeometricAugmentationBase2D):
- param_data = KORNIA_UNWRAP(param.data, Dict[str, Tensor])
- flags = override_parameters(module.flags, extra_args)
- maybe_mat = module.get_transformation_matrix(input, param_data, flags=flags)
- elif isinstance(module, kornia.augmentation.ImageSequential) and not module.is_intensity_only():
- param_data = KORNIA_UNWRAP(param.data, List[ParamItem])
- maybe_mat = module.get_transformation_matrix(input, param_data, recompute=False, extra_args=extra_args)
- else:
- pass # No need to update anything
- return maybe_mat
-
- @classmethod
- def _get_inverse_transformation(cls, transform: Tensor) -> Tensor:
- return _torch_inverse_cast(transform)
-
-
-class InputApplyInverse(ApplyInverseImpl):
- """Apply and inverse transformations for (image) input tensors."""
-
- data_key = DataKey.INPUT
-
- @classmethod
- def apply_trans(
- cls, input: Tensor, label: Optional[Tensor], module: Module, param: ParamItem, extra_args: Dict[str, Any] = {}
- ) -> Tuple[Tensor, Optional[Tensor]]:
- """Apply a transformation with respect to the parameters.
-
- Args:
- input: the input tensor.
- label: the optional label tensor.
- module: any torch Module but only kornia augmentation modules will count
- to apply transformations.
- param: the corresponding parameters to the module.
- """
- if isinstance(module, (_AugmentationBase, MixAugmentationBaseV2)):
- input = module(input, params=param.data, **extra_args)
- elif isinstance(module, kornia.augmentation.ImageSequential):
- temp = module.apply_inverse_func
- temp2 = module.return_label
- module.apply_inverse_func = InputApplyInverse
- module.return_label = True
- if isinstance(module, kornia.augmentation.AugmentationSequential):
- input, label = module(input, label=label, params=param.data, data_keys=[cls.data_key])
- else:
- input, label = module(input, label=label, params=param.data, extra_args=extra_args)
- module.apply_inverse_func = temp
- module.return_label = temp2
- else:
- if param.data is not None:
- raise AssertionError(f"Non-augmentaion operation {param.name} require empty parameters. Got {param}.")
- # In case of return_transform = True
- if isinstance(input, (tuple, list)):
- input = (module(input[0]), input[1])
- else:
- input = module(input)
- return input, label
-
- @classmethod
- def inverse(
- cls, input: Tensor, module: Module, param: Optional[ParamItem] = None, extra_args: Dict[str, Any] = {}
- ) -> Tensor:
- """Inverse a transformation with respect to the parameters.
-
- Args:
- input: the input tensor.
- module: any torch Module but only kornia augmentation modules will count
- to apply transformations.
- param: the corresponding parameters to the module.
- """
- if isinstance(module, GeometricAugmentationBase2D):
- if param is None:
- _params_geo = None
- elif isinstance(param, ParamItem) and isinstance(param.data, dict):
- _params_geo = param.data
- else:
- raise TypeError(f'Expected param (ParamItem.data) be a dictionary. Gotcha {type(param.data)}')
-
- input = module.inverse(input, params=_params_geo, extra_args=extra_args)
-
- elif isinstance(module, kornia.augmentation.ImageSequential):
- temp = module.apply_inverse_func
- module.apply_inverse_func = InputApplyInverse
- if param is None:
- _params = None
- elif isinstance(param, ParamItem) and isinstance(param.data, list):
- _params = param.data
- else:
- raise TypeError(f'Expected param (ParamItem.data) be a list. Gotcha {type(param.data)}')
-
- if isinstance(module, kornia.augmentation.AugmentationSequential):
- _ret = module.inverse(input, params=_params, data_keys=[cls.data_key])
- if isinstance(_ret, Tensor):
- input = _ret
- else:
- raise TypeError(
- f'The return of the method inverse from {module} should be a Tensor. Gotcha {type(_ret)}'
- )
- else:
- input = module.inverse(input, params=_params, extra_args=extra_args)
-
- module.apply_inverse_func = temp
- return input
-
-
-class MaskApplyInverse(ApplyInverseImpl):
- """Apply and inverse transformations for mask tensors."""
-
- data_key = DataKey.MASK
-
- @classmethod
- def make_input_only_sequential(cls, module: 'kornia.augmentation.ImageSequential') -> Callable[..., torch.Tensor]:
- """Disable all other additional inputs (e.g. ) for ImageSequential."""
-
- def f(*args, **kwargs):
- if_return_label = module.return_label
- module.return_label = False
- out = module(*args, **kwargs)
- module.return_label = if_return_label
- return out
-
- return f
-
- @classmethod
- def apply_trans(
- cls,
- input: Tensor,
- label: Optional[Tensor],
- module: Module,
- param: Optional[ParamItem] = None,
- extra_args: Dict[str, Any] = {},
- ) -> Tuple[Tensor, Optional[Tensor]]:
- """Apply a transformation with respect to the parameters.
-
- Args:
- input: the input tensor.
- label: the optional label tensor.
- module: any torch Module but only kornia augmentation modules will count
- to apply transformations.
- param: the corresponding parameters to the module.
- """
- if isinstance(module, (GeometricAugmentationBase2D, RandomErasing)):
- if isinstance(param, ParamItem) and isinstance(param.data, dict):
- _param = param.data.copy()
- # TODO: Parametrize value to pad with across the board for different keys
- if 'values' in _param:
- _param['values'] = torch.zeros_like(_param['values']) # Always pad with zeros
- elif param is None:
- _param = None
- else:
- raise TypeError(f'Expected param be None or ParamItem.data as a dict. Gotcha {type(_param)}')
-
- input = module(input, params=_param, **extra_args)
-
- elif isinstance(module, kornia.augmentation.ImageSequential) and not module.is_intensity_only():
- if param is None:
- geo_param = None
- elif isinstance(param, ParamItem) and isinstance(param.data, list):
- geo_param = _get_geometric_only_param(module, param.data)
- else:
- raise TypeError(f'Expected param be None or ParamItem.data as a list. Gotcha {type(geo_param)}')
-
- temp = module.apply_inverse_func
- module.apply_inverse_func = MaskApplyInverse
- if isinstance(module, kornia.augmentation.AugmentationSequential):
- input = cls.make_input_only_sequential(module)(
- input, label=None, params=geo_param, data_keys=[cls.data_key]
- )
- else:
- input = cls.make_input_only_sequential(module)(
- input, label=None, params=geo_param, extra_args=extra_args
- )
- module.apply_inverse_func = temp
- else:
- pass # No need to update anything
- return input, label
-
- @classmethod
- def inverse(
- cls, input: Tensor, module: Module, param: Optional[ParamItem] = None, extra_args: Dict[str, Any] = {}
- ) -> Tensor:
- """Inverse a transformation with respect to the parameters.
-
- Args:
- input: the input tensor.
- module: any torch Module but only kornia augmentation modules will count
- to apply transformations.
- param: the corresponding parameters to the module.
- """
-
- if isinstance(module, GeometricAugmentationBase2D):
- if param is None:
- _params_geo = None
- elif isinstance(param, ParamItem) and isinstance(param.data, dict):
- _params_geo = param.data
- else:
- raise TypeError(f'Expected param (ParamItem.data) be a dict. Gotcha {type(param.data)}')
-
- input = module.inverse(input, params=_params_geo, **extra_args)
-
- elif isinstance(module, kornia.augmentation.ImageSequential):
- temp = module.apply_inverse_func
- module.apply_inverse_func = MaskApplyInverse
-
- if param is None:
- _params = None
- elif isinstance(param, ParamItem) and isinstance(param.data, list):
- _params = param.data
- else:
- raise TypeError(f'Expected param (ParamItem.data) be a list. Gotcha {type(param.data)}')
-
- if isinstance(module, kornia.augmentation.AugmentationSequential):
- _ret = module.inverse(input, params=_params, data_keys=[cls.data_key])
- if isinstance(_ret, Tensor):
- input = _ret
- else:
- raise TypeError(
- f'The return of the method inverse from {module} should be a Tensor. Gotcha {type(_ret)}'
- )
- else:
- input = module.inverse(input, params=_params, extra_args=extra_args)
-
- module.apply_inverse_func = temp
- return input
-
-
-class BBoxApplyInverse(ApplyInverseImpl):
- """Apply and inverse transformations for bounding box tensors.
-
- This is for transform boxes in the format (B, N, 4, 2).
- """
-
- @classmethod
- def _get_padding_size(cls, module: Module, param: Optional[ParamItem]) -> Optional[Tensor]:
- if isinstance(module, RandomCrop) and param is not None and isinstance(param.data, dict):
- return param.data["padding_size"]
- return None
-
- @classmethod
- def pad(cls, input: Tensor, padding_size: Tensor) -> Tensor:
- """
- Args:
- input: (B, N, 4, 2)
- padding_size: (B, 4)
- """
- if len(input.shape) not in (3, 4):
- raise AssertionError(input.shape)
-
- if len(padding_size.shape) != 2:
- raise AssertionError(padding_size.shape)
-
- _input = input.clone()
-
- if input.dim() == 3:
- # B,4,2 to B,1,4,2
- _input = _input[:, None]
-
- _input[..., 0] += padding_size[..., None, :1] # left padding
- _input[..., 1] += padding_size[..., None, 2:3] # top padding
-
- if input.dim() == 3:
- _input = _input[:, 0] # squeeze back
-
- return _input
-
- @classmethod
- def unpad(cls, input: Tensor, padding_size: Tensor) -> Tensor:
- """
- Args:
- input: (B, N, 4, 2)
- padding_size: (B, 4)
- """
- if len(input.shape) not in (3, 4):
- raise AssertionError(input.shape)
-
- if len(padding_size.shape) != 2:
- raise AssertionError(padding_size.shape)
-
- _input = input.clone()
-
- if input.dim() == 3:
- # B,4,2 to B,1,4,2
- _input = _input[:, None]
-
- _input[..., 0] -= padding_size[..., None, :1] # left padding
- _input[..., 1] -= padding_size[..., None, 2:3] # top padding
-
- if input.dim() == 3:
- _input = _input[:, 0] # squeeze back
-
- return _input
-
- apply_func = partial(transform_bbox, mode="xyxy", restore_coordinates=True)
-
- @classmethod
- def apply_trans(
- cls, input: Tensor, label: Optional[Tensor], module: Module, param: ParamItem, extra_args: Dict[str, Any] = {}
- ) -> Tuple[Tensor, Optional[Tensor]]:
- """Apply a transformation with respect to the parameters.
-
- Args:
- input: the input tensor, (B, N, 4, 2) or (B, 4, 2).
- label: the optional label tensor.
- module: any torch Module but only kornia augmentation modules will count
- to apply transformations.
- param: the corresponding parameters to the module.
- """
- _input = input.clone()
-
- padding_size = cls._get_padding_size(module, param)
- if padding_size is not None:
- _input = cls.pad(_input, padding_size.to(_input))
-
- _input, label = super().apply_trans(_input, label, module, param, extra_args=extra_args)
-
- # TODO: Filter/crop boxes outside crop (with negative or larger than crop size coords)?
-
- return _input, label
-
- @classmethod
- def inverse(
- cls, input: Tensor, module: Module, param: Optional[ParamItem] = None, extra_args: Dict[str, Any] = {}
- ) -> Tensor:
- """Inverse a transformation with respect to the parameters.
-
- Args:
- input: the input tensor.
- module: any torch Module but only kornia augmentation modules will count
- to apply transformations.
- param: the corresponding parameters to the module.
- """
- _input = input.clone()
-
- _input = super().inverse(_input, module, param, extra_args=extra_args)
-
- padding_size = cls._get_padding_size(module, param)
- if padding_size is not None:
- _input = cls.unpad(_input, padding_size.to(input))
-
- return _input
-
-
-class BBoxXYXYApplyInverse(BBoxApplyInverse):
- """Apply and inverse transformations for bounding box tensors.
-
- This is for transform boxes in the format [xmin, ymin, xmax, ymax].
- """
-
- apply_func = partial(transform_bbox, mode="xyxy", restore_coordinates=True)
-
- @classmethod
- def pad(cls, input, padding_size):
- _padding_size = padding_size.to(input)
- for i in range(len(_padding_size)):
- input[i, :, 0::2] += _padding_size[i][0] # left padding
- input[i, :, 1::2] += _padding_size[i][2] # top padding
- return input
-
- @classmethod
- def unpad(cls, input, padding_size):
- _padding_size = padding_size.to(input)
- for i in range(len(_padding_size)):
- input[i, :, 0::2] -= _padding_size[i][0] # left padding
- input[i, :, 1::2] -= _padding_size[i][2] # top padding
- return input
-
- @classmethod
- def apply_trans(
- cls, input: Tensor, label: Optional[Tensor], module: Module, param: ParamItem, extra_args: Dict[str, Any] = {}
- ) -> Tuple[Tensor, Optional[Tensor]]:
- warnings.warn("BBoxXYXYApplyInverse is no longer maintained. Please use BBoxApplyInverse instead.")
- return super().apply_trans(input, label=label, module=module, param=param, extra_args=extra_args)
-
- @classmethod
- def inverse(
- cls, input: Tensor, module: Module, param: Optional[ParamItem] = None, extra_args: Dict[str, Any] = {}
- ) -> Tensor:
- warnings.warn("BBoxXYXYApplyInverse is no longer maintained. Please use BBoxApplyInverse instead.")
- return super().inverse(input, module=module, param=param, extra_args=extra_args)
-
-
-class BBoxXYWHApplyInverse(BBoxXYXYApplyInverse):
- """Apply and inverse transformations for bounding box tensors.
-
- This is for transform boxes in the format [xmin, ymin, width, height].
- """
-
- apply_func = partial(transform_bbox, mode="xywh", restore_coordinates=True)
-
- @classmethod
- def pad(cls, input, padding_size):
- _padding_size = padding_size.to(input)
- # pad only xy, not wh
- for i in range(len(_padding_size)):
- input[i, :, 0] += _padding_size[i][0] # left padding
- input[i, :, 1] += _padding_size[i][2] # top padding
- return input
-
- @classmethod
- def unpad(cls, input, padding_size):
- _padding_size = padding_size.to(input)
- # unpad only xy, not wh
- for i in range(len(_padding_size)):
- input[i, :, 0] -= _padding_size[i][0] # left padding
- input[i, :, 1] -= _padding_size[i][2] # top padding
- return input
-
-
-class KeypointsApplyInverse(BBoxApplyInverse):
- """Apply and inverse transformations for keypoints tensors.
-
- This is for transform keypoints in the format (B, N, 2).
- """
-
- # Hot fix for the typing mismatching
- apply_func = partial(transform_points)
-
- @classmethod
- def pad(cls, input: Tensor, padding_size: Tensor) -> Tensor:
- if len(input.shape) not in (2, 3):
- raise AssertionError(input.shape)
-
- if len(padding_size.shape) != 2:
- raise AssertionError(padding_size.shape)
-
- _input = input.clone()
-
- if input.dim() == 2:
- # B,2 to B,1,2
- _input = _input[:, None]
-
- _input[..., 0] += padding_size[..., :1] # left padding
- _input[..., 1] += padding_size[..., 2:3] # top padding
-
- if input.dim() == 2:
- _input = _input[:, 0] # squeeze back
-
- return _input
-
- @classmethod
- def unpad(cls, input: Tensor, padding_size: Tensor) -> Tensor:
- if len(input.shape) not in (2, 3):
- raise AssertionError(input.shape)
- if len(padding_size.shape) != 2:
- raise AssertionError(padding_size.shape)
-
- _input = input.clone()
-
- if input.dim() == 2:
- # B,2 to B,1,2
- _input = _input[:, None]
-
- # unpad only xy, not wh
- _input[..., 0] -= padding_size[..., :1] # left padding
- _input[..., 1] -= padding_size[..., 2:3] # top padding
-
- if input.dim() == 2:
- _input = _input[:, 0] # squeeze back
-
- return _input
-
-
-class ApplyInverse:
- """Apply and inverse transformations for any tensors (e.g. mask, box, points)."""
-
- @classmethod
- def _get_func_by_key(cls, dcate: Union[str, int, DataKey]) -> Type[ApplyInverseInterface]:
- if DataKey.get(dcate) == DataKey.INPUT:
- return InputApplyInverse
- if DataKey.get(dcate) == DataKey.MASK:
- return MaskApplyInverse
- if DataKey.get(dcate) in [DataKey.BBOX, DataKey.BBOX_XYXY, DataKey.BBOX_XYWH]:
- # We are converting to (B, 4, 2) internally for all formats.
- return BBoxApplyInverse
- if DataKey.get(dcate) in [DataKey.KEYPOINTS]:
- return KeypointsApplyInverse
- raise NotImplementedError(f"input type of {dcate} is not implemented.")
-
- @classmethod
- def apply_by_key(
- cls,
- input: Tensor,
- label: Optional[Tensor],
- module: Module,
- param: ParamItem,
- dcate: Union[str, int, DataKey] = DataKey.INPUT,
- extra_args: Dict[str, Any] = {},
- ) -> Tuple[Tensor, Optional[Tensor]]:
- """Apply a transformation with respect to the parameters.
-
- Args:
- input: the input tensor.
- label: the optional label tensor.
- module: any torch Module but only kornia augmentation modules will count
- to apply transformations.
- param: the corresponding parameters to the module.
- dcate: data category. 'input', 'mask', 'bbox', 'bbox_xyxy', 'bbox_xyhw', 'keypoints'.
- By default, it is set to 'input'.
- """
- func: Type[ApplyInverseInterface] = cls._get_func_by_key(dcate)
-
- if isinstance(input, (tuple,)):
- # If the input is a tuple with (input, mat) or something else
- return (func.apply_trans(input[0], label, module, param, extra_args), *input[1:])
- return func.apply_trans(input, label, module=module, param=param, extra_args=extra_args)
-
- @classmethod
- def inverse_by_key(
- cls,
- input: Tensor,
- module: Module,
- param: Optional[ParamItem] = None,
- dcate: Union[str, int, DataKey] = DataKey.INPUT,
- extra_args: Dict[str, Any] = {},
- ) -> Tensor:
- """Inverse a transformation with respect to the parameters.
-
- Args:
- input: the input tensor.
- module: any torch Module but only kornia augmentation modules will count
- to apply transformations.
- param: the corresponding parameters to the module.
- dcate: data category. 'input', 'mask', 'bbox', 'bbox_xyxy', 'bbox_xyhw', 'keypoints'.
- By default, it is set to 'input'.
- """
- func: Type[ApplyInverseInterface] = cls._get_func_by_key(dcate)
- return func.inverse(input, module, param, extra_args=extra_args)
diff --git a/kornia/augmentation/container/video.py b/kornia/augmentation/container/video.py
index 69aea0a4b..44ae8b843 100644
--- a/kornia/augmentation/container/video.py
+++ b/kornia/augmentation/container/video.py
@@ -7,8 +7,9 @@ from kornia.augmentation import MixAugmentationBaseV2, RandomCrop
from kornia.augmentation.base import _AugmentationBase
from kornia.augmentation.container.base import SequentialBase
from kornia.augmentation.container.image import ImageSequential, ParamItem, _get_new_batch_shape
-from kornia.augmentation.container.utils import InputApplyInverse, MaskApplyInverse
from kornia.core import Module, Tensor
+from kornia.geometry.boxes import Boxes
+from kornia.geometry.keypoints import Keypoints
__all__ = ["VideoSequential"]
@@ -40,7 +41,7 @@ class VideoSequential(ImageSequential):
If set `same_on_frame` to True, we would expect the same augmentation has been applied to each
timeframe.
- >>> input, label = torch.randn(2, 3, 1, 5, 6).repeat(1, 1, 4, 1, 1), torch.tensor([0, 1])
+ >>> input = torch.randn(2, 3, 1, 5, 6).repeat(1, 1, 4, 1, 1)
>>> aug_list = VideoSequential(
... kornia.augmentation.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0),
... kornia.color.BgrToRgb(),
@@ -64,14 +65,14 @@ class VideoSequential(ImageSequential):
... kornia.augmentation.RandomMixUpV2(p=1.0),
... data_format="BCTHW",
... same_on_frame=False)
- >>> output, lab = aug_list(input)
- >>> output.shape, lab.shape
- (torch.Size([3, 4, 5, 6]), torch.Size([3, 4, 5, 6]))
+ >>> output = aug_list(input)
+ >>> output.shape
+ torch.Size([2, 3, 4, 5, 6])
>>> (output[0, :, 0] == output[0, :, 1]).all()
tensor(False)
Reproduce with provided params.
- >>> out2, lab2 = aug_list(input, label, params=aug_list._params)
+ >>> out2 = aug_list(input, params=aug_list._params)
>>> torch.equal(output, out2)
True
@@ -88,10 +89,11 @@ class VideoSequential(ImageSequential):
... random_apply=1,
... random_apply_weights=[0.5, 0.3, 0.8]
... )
- >>> out= aug_list(input, label)
- >>> out[0].shape
+ >>> out = aug_list(input)
+ >>> out.shape
torch.Size([2, 3, 4, 5, 6])
"""
+ # TODO: implement transform_matrix
def __init__(
self,
@@ -134,9 +136,7 @@ class VideoSequential(ImageSequential):
repeated = param[:, None, ...].repeat(1, frame_num, *([1] * len(param.shape[1:])))
return repeated.reshape(-1, *list(param.shape[1:]))
- def _input_shape_convert_in(
- self, input: Tensor, label: Optional[Tensor], frame_num: int
- ) -> Tuple[Tensor, Optional[Tensor]]:
+ def _input_shape_convert_in(self, input: Tensor, frame_num: int) -> Tensor:
# Convert any shape to (B, T, C, H, W)
if self.data_format == "BCTHW":
# Convert (B, C, T, H, W) to (B, T, C, H, W)
@@ -144,32 +144,17 @@ class VideoSequential(ImageSequential):
if self.data_format == "BTCHW":
pass
- if label is not None:
- if label.shape == input.shape[:2]:
- # if label is provided as (B, T)
- label = label.view(-1)
- elif label.shape == input.shape[:1]:
- label = label[..., None].repeat(1, frame_num).view(-1)
- elif label.shape == torch.Size([input.shape[0] * input.shape[1]]):
- # Skip the conversion if label is provided as (B * T,)
- pass
- else:
- raise NotImplementedError(f"Invalid label shape of {label.shape}.")
input = input.reshape(-1, *input.shape[2:])
- return input, label
+ return input
- def _input_shape_convert_back(
- self, input: Tensor, label: Optional[Tensor], frame_num: int
- ) -> Tuple[Tensor, Optional[Tensor]]:
+ def _input_shape_convert_back(self, input: Tensor, frame_num: int) -> Tensor:
input = input.view(-1, frame_num, *input.shape[1:])
if self.data_format == "BCTHW":
input = input.transpose(1, 2)
if self.data_format == "BTCHW":
pass
- if label is not None:
- label = label.view(input.size(0), frame_num, -1)
- return input, label
+ return input
def forward_parameters(self, batch_shape: torch.Size) -> List[ParamItem]:
frame_num = batch_shape[self._temporal_channel]
@@ -184,7 +169,7 @@ class VideoSequential(ImageSequential):
params = []
for name, module in named_modules:
if isinstance(module, RandomCrop):
- mod_param = module.forward_parameters_precrop(batch_shape)
+ mod_param = module.forward_parameters(batch_shape)
if self.same_on_frame:
mod_param["src"] = mod_param["src"].repeat(frame_num, 1, 1)
mod_param["dst"] = mod_param["dst"].repeat(frame_num, 1, 1)
@@ -215,6 +200,114 @@ class VideoSequential(ImageSequential):
params.append(param)
return params
+ def transform_inputs(self, input: Tensor, params: List[ParamItem], extra_args: Dict[str, Any] = {}) -> Tensor:
+ frame_num: int = input.size(self._temporal_channel)
+ input = self._input_shape_convert_in(input, frame_num)
+
+ input = super().transform_inputs(input, params, extra_args=extra_args)
+
+ input = self._input_shape_convert_back(input, frame_num)
+ return input
+
+ def inverse_inputs(self, input: Tensor, params: List[ParamItem], extra_args: Dict[str, Any] = {}) -> Tensor:
+ frame_num: int = input.size(self._temporal_channel)
+ input = self._input_shape_convert_in(input, frame_num)
+
+ input = super().inverse_inputs(input, params, extra_args=extra_args)
+
+ input = self._input_shape_convert_back(input, frame_num)
+ return input
+
+ def transform_masks(self, input: Tensor, params: List[ParamItem], extra_args: Dict[str, Any] = {}) -> Tensor:
+ frame_num: int = input.size(self._temporal_channel)
+ input = self._input_shape_convert_in(input, frame_num)
+
+ input = super().transform_masks(input, params, extra_args=extra_args)
+
+ input = self._input_shape_convert_back(input, frame_num)
+ return input
+
+ def inverse_masks(self, input: Tensor, params: List[ParamItem], extra_args: Dict[str, Any] = {}) -> Tensor:
+ frame_num: int = input.size(self._temporal_channel)
+ input = self._input_shape_convert_in(input, frame_num)
+
+ input = super().inverse_masks(input, params, extra_args=extra_args)
+
+ input = self._input_shape_convert_back(input, frame_num)
+ return input
+
+ def transform_boxes( # type: ignore[override]
+ self, input: Union[Tensor, Boxes], params: List[ParamItem], extra_args: Dict[str, Any] = {}
+ ) -> Union[Tensor, Boxes]:
+ """Transform bounding boxes.
+
+ Args:
+ input: tensor with shape :math:`(B, T, N, 4, 2)`.
+ If input is a `Keypoints` type, the internal shape is :math:`(B * T, N, 4, 2)`.
+ """
+ if isinstance(input, Tensor):
+ batchsize, frame_num = input.size(0), input.size(1)
+ input = Boxes.from_tensor(input.view(-1, input.size(2), input.size(3), input.size(4)), mode="vertices_plus")
+ input = super().transform_boxes(input, params, extra_args=extra_args)
+ input = input.data.view(batchsize, frame_num, -1, 4, 2)
+ else:
+ input = super().transform_boxes(input, params, extra_args=extra_args)
+ return input
+
+ def inverse_boxes( # type: ignore[override]
+ self, input: Union[Tensor, Boxes], params: List[ParamItem], extra_args: Dict[str, Any] = {}
+ ) -> Union[Tensor, Boxes]:
+ """Transform bounding boxes.
+
+ Args:
+ input: tensor with shape :math:`(B, T, N, 4, 2)`.
+ If input is a `Keypoints` type, the internal shape is :math:`(B * T, N, 4, 2)`.
+ """
+ if isinstance(input, Tensor):
+ batchsize, frame_num = input.size(0), input.size(1)
+ input = Boxes.from_tensor(input.view(-1, input.size(2), input.size(3), input.size(4)), mode="vertices_plus")
+ input = super().inverse_boxes(input, params, extra_args=extra_args)
+ input = input.data.view(batchsize, frame_num, -1, 4, 2)
+ else:
+ input = super().inverse_boxes(input, params, extra_args=extra_args)
+ return input
+
+ def transform_keypoints( # type: ignore[override]
+ self, input: Union[Tensor, Keypoints], params: List[ParamItem], extra_args: Dict[str, Any] = {}
+ ) -> Union[Tensor, Keypoints]:
+ """Transform bounding boxes.
+
+ Args:
+ input: tensor with shape :math:`(B, T, N, 2)`.
+ If input is a `Keypoints` type, the internal shape is :math:`(B * T, N, 2)`.
+ """
+ if isinstance(input, Tensor):
+ batchsize, frame_num = input.size(0), input.size(1)
+ input = Keypoints(input.view(-1, input.size(2), input.size(3)))
+ input = super().transform_keypoints(input, params, extra_args=extra_args)
+ input = input.data.view(batchsize, frame_num, -1, 2)
+ else:
+ input = super().transform_keypoints(input, params, extra_args=extra_args)
+ return input
+
+ def inverse_keypoints( # type: ignore[override]
+ self, input: Union[Tensor, Keypoints], params: List[ParamItem], extra_args: Dict[str, Any] = {}
+ ) -> Union[Tensor, Keypoints]:
+ """Transform bounding boxes.
+
+ Args:
+ input: tensor with shape :math:`(B, T, N, 2)`.
+ If input is a `Keypoints` type, the internal shape is :math:`(B * T, N, 2)`.
+ """
+ if isinstance(input, Tensor):
+ frame_num, batchsize = input.size(0), input.size(1)
+ input = Keypoints(input.view(-1, input.size(2), input.size(3)))
+ input = super().inverse_keypoints(input, params, extra_args=extra_args)
+ input = input.data.view(batchsize, frame_num, -1, 2)
+ else:
+ input = super().inverse_keypoints(input, params, extra_args=extra_args)
+ return input
+
def inverse(
self, input: Tensor, params: Optional[List[ParamItem]] = None, extra_args: Dict[str, Any] = {}
) -> Tensor:
@@ -223,65 +316,26 @@ class VideoSequential(ImageSequential):
Used to inverse a tensor according to the performed transformation by a forward pass, or with respect to
provided parameters.
"""
- if self.apply_inverse_func in (InputApplyInverse, MaskApplyInverse):
- frame_num: int = input.size(self._temporal_channel)
- input, _ = self._input_shape_convert_in(input, None, frame_num)
- else:
- batch_size: int = input.size(0)
- input = input.view(-1, *input.shape[2:])
+ if params is None:
+ if self._params is not None: # type: ignore
+ params = self._params # type: ignore
+ else:
+ raise RuntimeError("No valid params to inverse the transformation.")
- input = super().inverse(input, params, extra_args=extra_args)
- if self.apply_inverse_func in (InputApplyInverse, MaskApplyInverse):
- input, _ = self._input_shape_convert_back(input, None, frame_num)
- else:
- input = input.view(batch_size, -1, *input.shape[1:])
-
- return input
+ return self.inverse_inputs(input, params, extra_args=extra_args)
def forward(
- self,
- input: Tensor,
- label: Optional[Tensor] = None,
- params: Optional[List[ParamItem]] = None,
- extra_args: Dict[str, Any] = {},
- ) -> Union[Tensor, Tuple[Tensor, Optional[Tensor]]]:
+ self, input: Tensor, params: Optional[List[ParamItem]] = None, extra_args: Dict[str, Any] = {}
+ ) -> Tensor:
"""Define the video computation performed."""
if len(input.shape) != 5:
raise AssertionError(f"Input must be a 5-dim tensor. Got {input.shape}.")
if params is None:
- params = self.forward_parameters(input.shape)
-
- # Size of T
- if self.apply_inverse_func in (InputApplyInverse, MaskApplyInverse):
- frame_num: int = input.size(self._temporal_channel)
- input, label = self._input_shape_convert_in(input, label, frame_num)
- else:
- if label is not None:
- raise ValueError(f"Invalid label value. Got {label}")
- batch_size: int = input.size(0)
- input = input.view(-1, *input.shape[2:])
-
- out = super().forward(input, label, params, extra_args=extra_args)
- if self.return_label:
- output, label = cast(Tuple[Tensor, Tensor], out)
- else:
- output = cast(Tensor, out)
+ if self._params is None: # type: ignore
+ self._params = self.forward_parameters(input.shape)
+ params = self._params
- if isinstance(output, (tuple, list)):
- if self.apply_inverse_func in (InputApplyInverse, MaskApplyInverse):
- _out, label = self._input_shape_convert_back(output[0], label, frame_num)
- output = (_out, output[1])
- else:
- if label is not None:
- raise ValueError(f"Invalid label value. Got {label}")
- output = output[0].view(batch_size, -1, *output[0].shape[1:])
- else:
- if self.apply_inverse_func in (InputApplyInverse, MaskApplyInverse):
- output, label = self._input_shape_convert_back(output, label, frame_num)
- else:
- if label is not None:
- raise ValueError(f"Invalid label value. Got {label}")
- output = output.view(batch_size, -1, *output.shape[1:])
+ output = self.transform_inputs(input, params, extra_args=extra_args)
- return self.__packup_output__(output, label)
+ return output
diff --git a/kornia/augmentation/utils/helpers.py b/kornia/augmentation/utils/helpers.py
index 54f358e45..082543758 100644
--- a/kornia/augmentation/utils/helpers.py
+++ b/kornia/augmentation/utils/helpers.py
@@ -5,6 +5,8 @@ import torch
from torch.distributions import Beta, Uniform
from kornia.core import Tensor, as_tensor
+from kornia.geometry.boxes import Boxes
+from kornia.geometry.keypoints import Keypoints
from kornia.utils import _extract_device_dtype
@@ -316,3 +318,62 @@ def override_parameters(
else:
raise ValueError(f"`{if_none_exist}` is not a valid option.")
return out
+
+
+def preprocess_boxes(input: Union[Tensor, Boxes], mode="vertices_plus") -> Boxes:
+ r"""Preprocess input boxes.
+
+ Args:
+ input: 2D boxes, shape of :math:`(N, 4, 2)`, :math:`(B, N, 4, 2)` or a list of :math:`(N, 4, 2)`.
+ See below for more details.
+ mode: The format in which the boxes are provided.
+
+ * 'xyxy': boxes are assumed to be in the format ``xmin, ymin, xmax, ymax`` where ``width = xmax - xmin``
+ and ``height = ymax - ymin``. With shape :math:`(N, 4)`, :math:`(B, N, 4)`.
+ * 'xyxy_plus': similar to 'xyxy' mode but where box width and length are defined as
+ ``width = xmax - xmin + 1`` and ``height = ymax - ymin + 1``.
+ With shape :math:`(N, 4)`, :math:`(B, N, 4)`.
+ * 'xywh': boxes are assumed to be in the format ``xmin, ymin, width, height`` where
+ ``width = xmax - xmin`` and ``height = ymax - ymin``. With shape :math:`(N, 4)`, :math:`(B, N, 4)`.
+ * 'vertices': boxes are defined by their vertices points in the following ``clockwise`` order:
+ *top-left, top-right, bottom-right, bottom-left*. Vertices coordinates are in (x,y) order. Finally,
+ box width and height are defined as ``width = xmax - xmin`` and ``height = ymax - ymin``.
+ With shape :math:`(N, 4, 2)` or :math:`(B, N, 4, 2)`.
+ * 'vertices_plus': similar to 'vertices' mode but where box width and length are defined as
+ ``width = xmax - xmin + 1`` and ``height = ymax - ymin + 1``. ymin + 1``.
+ With shape :math:`(N, 4, 2)` or :math:`(B, N, 4, 2)`.
+
+ Note:
+ **2D boxes format** is defined as a floating data type tensor of shape ``Nx4x2`` or ``BxNx4x2``
+ where each box is a `quadrilateral <https://en.wikipedia.org/wiki/Quadrilateral>`_ defined by it's 4 vertices
+ coordinates (A, B, C, D). Coordinates must be in ``x, y`` order. The height and width of a box is defined as
+ ``width = xmax - xmin + 1`` and ``height = ymax - ymin + 1``. Examples of
+ `quadrilaterals <https://en.wikipedia.org/wiki/Quadrilateral>`_ are rectangles, rhombus and trapezoids.
+ """
+ # TODO: We may allow list here.
+ # input is BxNx4x2 or Boxes.
+ if isinstance(input, Tensor):
+ if not (len(input.shape) == 4 and input.shape[2:] == torch.Size([4, 2])):
+ raise RuntimeError(f"Only BxNx4x2 tensor is supported. Got {input.shape}.")
+ input = Boxes.from_tensor(input, mode=mode)
+ if not isinstance(input, Boxes):
+ raise RuntimeError(f"Expect `Boxes` type. Got {type(input)}.")
+ return input
+
+
+def preprocess_keypoints(input: Union[Tensor, Keypoints]) -> Keypoints:
+ """Preprocess input keypoints."""
+ # TODO: We may allow list here.
+ if isinstance(input, Tensor):
+ if not (len(input.shape) == 3 and input.shape[1:] == torch.Size([2])):
+ raise RuntimeError(f"Only BxNx2 tensor is supported. Got {input.shape}.")
+ input = Keypoints(input, False)
+ if isinstance(input, Keypoints):
+ raise RuntimeError(f"Expect `Keypoints` type. Got {type(input)}.")
+ return input
+
+
+def preprocess_classes(input: Tensor) -> Tensor:
+ """Preprocess input class tags."""
+ # TODO: We may allow list here.
+ return input
diff --git a/kornia/filters/filter.py b/kornia/filters/filter.py
index 606e92ab1..ff5abaf53 100644
--- a/kornia/filters/filter.py
+++ b/kornia/filters/filter.py
@@ -122,7 +122,9 @@ def filter2d(
input = input.view(-1, tmp_kernel.size(0), input.size(-2), input.size(-1))
# convolve the tensor with the kernel.
- output = F.conv2d(input, tmp_kernel, groups=tmp_kernel.size(0), padding=0, stride=1)
+ # NOTE: type(...) to fix getting `torch.bfloat16` type.
+ # TODO: @johnnv1, fix it through the Augmentation Base.
+ output = F.conv2d(input, tmp_kernel, groups=tmp_kernel.size(0), padding=0, stride=1).type(input.dtype)
if padding == 'same':
out = output.view(b, c, h, w)
diff --git a/kornia/geometry/bbox.py b/kornia/geometry/bbox.py
index 7aee752ab..a029fc51e 100644
--- a/kornia/geometry/bbox.py
+++ b/kornia/geometry/bbox.py
@@ -197,7 +197,7 @@ def bbox_to_mask(boxes: torch.Tensor, width: int, height: int) -> torch.Tensor:
"""
validate_bbox(boxes)
# zero padding the surroudings
- mask = torch.zeros((len(boxes), height + 2, width + 2), dtype=torch.float, device=boxes.device)
+ mask = torch.zeros((len(boxes), height + 2, width + 2), dtype=boxes.dtype, device=boxes.device)
# push all points one pixel off
# in order to zero-out the fully filled rows or columns
box_i = (boxes + 1).long()
diff --git a/kornia/geometry/boxes.py b/kornia/geometry/boxes.py
index a8162c223..62de912d9 100644
--- a/kornia/geometry/boxes.py
+++ b/kornia/geometry/boxes.py
@@ -162,7 +162,6 @@ def _boxes3d_to_polygons3d(
return polygons3d
-# NOTE: Cannot jit with Union types with torch <= 0.10
# @torch.jit.script
class Boxes:
r"""2D boxes containing N or BxN boxes.
@@ -217,6 +216,19 @@ class Boxes:
self._data = boxes
self._mode = mode
+ def __getitem__(self, key) -> "Boxes":
+ new_box = type(self)(self._data[key], False)
+ new_box._mode = self._mode
+ return new_box
+
+ def __setitem__(self, key, value: "Boxes") -> "Boxes":
+ self._data[key] = value._data
+ return self
+
+ @property
+ def shape(self):
+ return self.data.shape
+
def get_boxes_shape(self) -> Tuple[torch.Tensor, torch.Tensor]:
r"""Compute boxes heights and widths.
@@ -248,7 +260,54 @@ class Boxes:
if inplace:
self._data = data
return self
- return Boxes(data, False)
+
+ obj = self.clone()
+ obj._data = data
+ return obj
+
+ def index_put(
+ self, indices: Union[Tuple[Tensor, ...], List[Tensor]], values: Union[Tensor, "Boxes"], inplace: bool = False
+ ) -> "Boxes":
+ if inplace:
+ _data = self._data
+ else:
+ _data = self._data.clone()
+
+ if isinstance(values, Boxes):
+ _data.index_put_(indices, values.data)
+ else:
+ _data.index_put_(indices, values)
+
+ if inplace:
+ return self
+
+ obj = self.clone()
+ obj._data = _data
+ return obj
+
+ def pad(self, padding_size: Tensor) -> "Boxes":
+ """Pad a bounding box.
+
+ Args:
+ padding_size: (B, 4)
+ """
+ if not (len(padding_size.shape) == 2 and padding_size.size(1) == 4):
+ raise RuntimeError(f"Expected padding_size as (B, 4). Got {padding_size.shape}.")
+ self._data[..., 0] += padding_size[..., None, :1] # left padding
+ self._data[..., 1] += padding_size[..., None, 2:3] # top padding
+ return self
+
+ def unpad(self, padding_size: Tensor) -> "Boxes":
+ """Pad a bounding box.
+
+ Args:
+ padding_size: (B, 4)
+ """
+ if not (len(padding_size.shape) == 2 and padding_size.size(1) == 4):
+ raise RuntimeError(f"Expected padding_size as (B, 4). Got {padding_size.shape}.")
+ self._data[..., 0] -= padding_size[..., None, :1] # left padding
+ self._data[..., 1] -= padding_size[..., None, 2:3] # top padding
+ return self
def clamp(
self,
@@ -276,7 +335,10 @@ class Boxes:
_data[..., 1][_data[..., 1] > botright_y] = botright_y[_data[..., 1] > botright_y]
if inplace:
return self
- return Boxes(_data, False)
+
+ obj = self.clone()
+ obj._data = _data
+ return obj
def trim(self, correspondence_preserve: bool = False, inplace: bool = False) -> "Boxes":
"""Trim out zero padded boxes.
@@ -321,7 +383,10 @@ class Boxes:
_data[area > max_area] = 0.0
if inplace:
return self
- return Boxes(_data, False)
+
+ obj = self.clone()
+ obj._data = _data
+ return obj
def compute_area(self) -> torch.Tensor:
"""Returns :math:`(B, N)`."""
@@ -405,7 +470,7 @@ class Boxes:
* 'vertices_plus': similar to 'vertices' mode but where box width and length are defined as
``width = xmax - xmin + 1`` and ``height = ymax - ymin + 1``. ymin + 1``.
as_padded_sequence: whether to keep the pads for a list of boxes. This parameter is only valid
- if the boxes are from a box list.
+ if the boxes are from a box list whilst `from_tensor`.
Returns:
Boxes tensor in the ``mode`` format. The shape depends with the ``mode`` value:
@@ -529,7 +594,9 @@ class Boxes:
self._data = transformed_boxes
return self
- return Boxes(transformed_boxes, False)
+ obj = self.clone()
+ obj._data = transformed_boxes
+ return obj
def transform_boxes_(self, M: torch.Tensor) -> "Boxes":
"""Inplace version of :func:`Boxes.transform_boxes`"""
@@ -584,7 +651,52 @@ class Boxes:
return self
def clone(self) -> "Boxes":
- return Boxes(self._data.clone(), False)
+ obj = type(self)(self._data.clone(), False)
+ obj._mode = self._mode
+ obj._N = self._N
+ obj._is_batched = self._is_batched
+ return obj
+
+
+class VideoBoxes(Boxes):
+ temporal_channel_size: int
+
+ @classmethod
+ def from_tensor( # type: ignore[override]
+ cls, boxes: Union[torch.Tensor, List[torch.Tensor]], validate_boxes: bool = True
+ ) -> "VideoBoxes":
+ if isinstance(boxes, (list,)) or (boxes.dim() != 5 or boxes.shape[-2:] != torch.Size([4, 2])):
+ raise ValueError("Input box type is not yet supported. Please input an `BxTxNx4x2` tensor directly.")
+
+ temporal_channel_size = boxes.size(1)
+
+ quadrilaterals = _boxes_to_quadrilaterals(
+ boxes.view(boxes.size(0) * boxes.size(1), -1, boxes.size(3), boxes.size(4)),
+ mode="vertices_plus",
+ validate_boxes=validate_boxes,
+ )
+ # Due to some torch.jit.script bug (at least <= 1.9), you need to pass all arguments to __init__ when
+ # constructing the class from inside of a method.
+ out = cls(quadrilaterals, False, "vertices_plus")
+ out.temporal_channel_size = temporal_channel_size
+ return out
+
+ def to_tensor( # type: ignore[override]
+ self, mode: Optional[str] = None
+ ) -> Union[torch.Tensor, List[torch.Tensor]]:
+ out = super().to_tensor(mode, as_padded_sequence=False)
+ if isinstance(out, Tensor):
+ return out.view(-1, self.temporal_channel_size, *out.shape[1:])
+ # If returns a list of boxes.
+ return [_out.view(-1, self.temporal_channel_size, *_out.shape[1:]) for _out in out]
+
+ def clone(self) -> "VideoBoxes":
+ obj = type(self)(self._data.clone(), False)
+ obj._mode = self._mode
+ obj._N = self._N
+ obj._is_batched = self._is_batched
+ obj.temporal_channel_size = self.temporal_channel_size
+ return obj
@torch.jit.script
@@ -629,6 +741,19 @@ class Boxes3D:
self._data = boxes
self._mode = mode
+ def __getitem__(self, key) -> "Boxes3D":
+ new_box = Boxes3D(self._data[key], False, mode="xyzxyz_plus")
+ new_box._mode = self._mode
+ return new_box
+
+ def __setitem__(self, key, value: "Boxes3D") -> "Boxes3D":
+ self._data[key] = value._data
+ return self
+
+ @property
+ def shape(self):
+ return self.data.shape
+
def get_boxes_shape(self) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
r"""Compute boxes heights and widths.
diff --git a/kornia/geometry/keypoints.py b/kornia/geometry/keypoints.py
new file mode 100644
index 000000000..735552149
--- /dev/null
+++ b/kornia/geometry/keypoints.py
@@ -0,0 +1,282 @@
+from typing import List, Optional, Tuple, Union, cast
+
+from kornia.core import Tensor
+from kornia.geometry import transform_points
+
+
+def _merge_keypoint_list(keypoints: List[Tensor]) -> Tensor:
+ raise NotImplementedError
+
+
+class Keypoints:
+ def __init__(self, keypoints: Union[Tensor, List[Tensor]], raise_if_not_floating_point: bool = True) -> None:
+ self._N: Optional[List[int]] = None
+
+ if isinstance(keypoints, list):
+ keypoints, self._N = _merge_keypoint_list(keypoints)
+
+ if not isinstance(keypoints, Tensor):
+ raise TypeError(f"Input keypoints is not a Tensor. Got: {type(keypoints)}.")
+
+ if not keypoints.is_floating_point():
+ if raise_if_not_floating_point:
+ raise ValueError(f"Coordinates must be in floating point. Got {keypoints.dtype}")
+
+ keypoints = keypoints.float()
+
+ if len(keypoints.shape) == 0:
+ # Use reshape, so we don't end up creating a new tensor that does not depend on
+ # the inputs (and consequently confuses jit)
+ keypoints = keypoints.reshape((-1, 2))
+
+ if not (2 <= keypoints.ndim <= 3 and keypoints.shape[-1:] == (2,)):
+ raise ValueError(f"Keypoints shape must be (N, 2) or (B, N, 2). Got {keypoints.shape}.")
+
+ self._is_batched = False if keypoints.ndim == 2 else True
+
+ self._data = keypoints
+
+ def __getitem__(self, key) -> "Keypoints":
+ new_obj = type(self)(self._data[key], False)
+ return new_obj
+
+ def __setitem__(self, key, value: "Keypoints") -> "Keypoints":
+ self._data[key] = value._data
+ return self
+
+ @property
+ def shape(self):
+ return self.data.shape
+
+ @property
+ def data(self):
+ return self._data
+
+ def index_put(
+ self,
+ indices: Union[Tuple[Tensor, ...], List[Tensor]],
+ values: Union[Tensor, "Keypoints"],
+ inplace: bool = False,
+ ) -> "Keypoints":
+ if inplace:
+ _data = self._data
+ else:
+ _data = self._data.clone()
+
+ if isinstance(values, Keypoints):
+ _data.index_put_(indices, values.data)
+ else:
+ _data.index_put_(indices, values)
+
+ if inplace:
+ return self
+
+ obj = self.clone()
+ obj._data = _data
+ return obj
+
+ def pad(self, padding_size: Tensor) -> "Keypoints":
+ """Pad a bounding keypoints.
+
+ Args:
+ padding_size: (B, 4)
+ """
+ if not (len(padding_size.shape) == 2 and padding_size.size(1) == 4):
+ raise RuntimeError(f"Expected padding_size as (B, 4). Got {padding_size.shape}.")
+ self._data[..., 0] += padding_size[..., :1] # left padding
+ self._data[..., 1] += padding_size[..., 2:3] # top padding
+ return self
+
+ def unpad(self, padding_size: Tensor) -> "Keypoints":
+ """Pad a bounding keypoints.
+
+ Args:
+ padding_size: (B, 4)
+ """
+ if not (len(padding_size.shape) == 2 and padding_size.size(1) == 4):
+ raise RuntimeError(f"Expected padding_size as (B, 4). Got {padding_size.shape}.")
+ self._data[..., 0] -= padding_size[..., :1] # left padding
+ self._data[..., 1] -= padding_size[..., 2:3] # top padding
+ return self
+
+ def transform_keypoints(self, M: Tensor, inplace: bool = False) -> "Keypoints":
+ r"""Apply a transformation matrix to the 2D keypoints.
+
+ Args:
+ M: The transformation matrix to be applied, shape of :math:`(3, 3)` or :math:`(B, 3, 3)`.
+ inplace: do transform in-place and return self.
+
+ Returns:
+ The transformed keypoints.
+ """
+ if not 2 <= M.ndim <= 3 or M.shape[-2:] != (3, 3):
+ raise ValueError(f"The transformation matrix shape must be (3, 3) or (B, 3, 3). Got {M.shape}.")
+
+ transformed_boxes = transform_points(M, self._data)
+ if inplace:
+ self._data = transformed_boxes
+ return self
+
+ return Keypoints(transformed_boxes, False)
+
+ def transform_keypoints_(self, M: Tensor) -> "Keypoints":
+ """Inplace version of :func:`Keypoints.transform_keypoints`"""
+ return self.transform_keypoints(M, inplace=True)
+
+ @classmethod
+ def from_tensor(cls, keypoints: Tensor) -> "Keypoints":
+ return cls(keypoints)
+
+ def to_tensor(self, as_padded_sequence: bool = False) -> Union[Tensor, List[Tensor]]:
+ r"""Cast :class:`Keypoints` to a tensor. ``mode`` controls which 2D keypoints format should be use to
+ represent keypoints in the tensor.
+
+ Args:
+ as_padded_sequence: whether to keep the pads for a list of keypoints. This parameter is only valid
+ if the keypoints are from a keypoint list.
+
+ Returns:
+ Keypoints tensor :math:`(B, N, 2)`
+ """
+
+ if as_padded_sequence:
+ raise NotImplementedError
+ return self._data
+
+ def clone(self) -> "Keypoints":
+ return Keypoints(self._data.clone(), False)
+
+
+class VideoKeypoints(Keypoints):
+ temporal_channel_size: int
+
+ @classmethod
+ def from_tensor(cls, boxes: Union[Tensor, List[Tensor]], validate_boxes: bool = True) -> "VideoKeypoints":
+ if isinstance(boxes, (list,)) or (boxes.dim() != 4 or boxes.shape[-1] != 2):
+ raise ValueError("Input box type is not yet supported. Please input an `BxTxNx2` tensor directly.")
+
+ temporal_channel_size = boxes.size(1)
+
+ # Due to some torch.jit.script bug (at least <= 1.9), you need to pass all arguments to __init__ when
+ # constructing the class from inside of a method.
+ out = cls(boxes.view(boxes.size(0) * boxes.size(1), -1, boxes.size(3)))
+ out.temporal_channel_size = temporal_channel_size
+ return out
+
+ def to_tensor(self) -> Tensor: # type: ignore[override]
+ out = super().to_tensor(as_padded_sequence=False)
+ out = cast(Tensor, out)
+ return out.view(-1, self.temporal_channel_size, *out.shape[1:])
+
+ def transform_keypoints(self, M: Tensor, inplace: bool = False) -> "VideoKeypoints":
+ out = super().transform_keypoints(M, inplace=inplace)
+ if inplace:
+ return self
+ out = VideoKeypoints(out.data, False)
+ out.temporal_channel_size = self.temporal_channel_size
+ return out
+
+ def clone(self) -> "VideoKeypoints":
+ out = VideoKeypoints(self._data.clone(), False)
+ out.temporal_channel_size = self.temporal_channel_size
+ return out
+
+
+class Keypoints3D:
+ def __init__(self, keypoints: Union[Tensor, List[Tensor]], raise_if_not_floating_point: bool = True) -> None:
+ self._N: Optional[List[int]] = None
+
+ if isinstance(keypoints, list):
+ keypoints, self._N = _merge_keypoint_list(keypoints)
+
+ if not isinstance(keypoints, Tensor):
+ raise TypeError(f"Input keypoints is not a Tensor. Got: {type(keypoints)}.")
+
+ if not keypoints.is_floating_point():
+ if raise_if_not_floating_point:
+ raise ValueError(f"Coordinates must be in floating point. Got {keypoints.dtype}")
+
+ keypoints = keypoints.float()
+
+ if len(keypoints.shape) == 0:
+ # Use reshape, so we don't end up creating a new tensor that does not depend on
+ # the inputs (and consequently confuses jit)
+ keypoints = keypoints.reshape((-1, 3))
+
+ if not (2 <= keypoints.ndim <= 3 and keypoints.shape[-1:] == (3,)):
+ raise ValueError(f"Keypoints shape must be (N, 3) or (B, N, 3). Got {keypoints.shape}.")
+
+ self._is_batched = False if keypoints.ndim == 2 else True
+
+ self._data = keypoints
+
+ def __getitem__(self, key) -> "Keypoints3D":
+ new_obj = type(self)(self._data[key], False)
+ return new_obj
+
+ def __setitem__(self, key, value: "Keypoints3D") -> "Keypoints3D":
+ self._data[key] = value._data
+ return self
+
+ @property
+ def shape(self):
+ return self.data.shape
+
+ @property
+ def data(self):
+ return self._data
+
+ def pad(self, padding_size: Tensor) -> "Keypoints3D":
+ """Pad a bounding keypoints.
+
+ Args:
+ padding_size: (B, 6)
+ """
+ raise NotImplementedError
+
+ def unpad(self, padding_size: Tensor) -> "Keypoints3D":
+ """Pad a bounding keypoints.
+
+ Args:
+ padding_size: (B, 6)
+ """
+ raise NotImplementedError
+
+ def transform_keypoints(self, M: Tensor, inplace: bool = False) -> "Keypoints3D":
+ r"""Apply a transformation matrix to the 2D keypoints.
+
+ Args:
+ M: The transformation matrix to be applied, shape of :math:`(3, 3)` or :math:`(B, 3, 3)`.
+ inplace: do transform in-place and return self.
+
+ Returns:
+ The transformed keypoints.
+ """
+ raise NotImplementedError
+
+ def transform_keypoints_(self, M: Tensor) -> "Keypoints3D":
+ """Inplace version of :func:`Keypoints.transform_keypoints`"""
+ return self.transform_keypoints(M, inplace=True)
+
+ @classmethod
+ def from_tensor(cls, keypoints: Tensor) -> "Keypoints3D":
+ return cls(keypoints)
+
+ def to_tensor(self, as_padded_sequence: bool = False) -> Union[Tensor, List[Tensor]]:
+ r"""Cast :class:`Keypoints` to a tensor. ``mode`` controls which 2D keypoints format should be use to
+ represent keypoints in the tensor.
+
+ Args:
+ as_padded_sequence: whether to keep the pads for a list of keypoints. This parameter is only valid
+ if the keypoints are from a keypoint list.
+
+ Returns:
+ Keypoints tensor :math:`(B, N, 3)`
+ """
+
+ if as_padded_sequence:
+ raise NotImplementedError
+ return self._data
+
+ def clone(self) -> "Keypoints3D":
+ return Keypoints3D(self._data.clone(), False)
diff --git a/test/augmentation/test_augmentation.py b/test/augmentation/test_augmentation.py
index 136fbf1f7..ec3011734 100644
--- a/test/augmentation/test_augmentation.py
+++ b/test/augmentation/test_augmentation.py
@@ -1583,11 +1583,11 @@ class TestColorJitter(BaseTester):
f = AugmentationSequential(ColorJiggle(), ColorJiggle())
- input = torch.rand(3, 5, 5, device=device, dtype=dtype).unsqueeze(0) # 1 x 3 x 5 x 5
+ input = torch.rand(3, 5, 5, device=device, dtype=dtype).unsqueeze(0).repeat(4, 1, 1, 1) # 4 x 3 x 5 x 5
expected = input
- expected_transform = torch.eye(3, device=device, dtype=dtype).unsqueeze(0) # 3 x 3
+ expected_transform = torch.eye(3, device=device, dtype=dtype).unsqueeze(0).repeat(4, 1, 1) # 4 x 3 x 3
self.assert_close(f(input), expected)
self.assert_close(f.transform_matrix, expected_transform)
diff --git a/test/augmentation/test_base.py b/test/augmentation/test_base.py
index be1f48779..0b869e994 100644
--- a/test/augmentation/test_base.py
+++ b/test/augmentation/test_base.py
@@ -100,43 +100,21 @@ class TestBasicAugmentationBase:
class TestAugmentationBase2D:
- @pytest.mark.parametrize(
- 'input_shape, in_trans_shape',
- [
- ((2, 3, 4, 5), (2, 3, 3)),
- ((3, 4, 5), (3, 3)),
- ((4, 5), (3, 3)),
- pytest.param((1, 2, 3, 4, 5), (2, 3, 3), marks=pytest.mark.xfail),
- pytest.param((2, 3, 4, 5), (1, 3, 3), marks=pytest.mark.xfail),
- pytest.param((2, 3, 4, 5), (3, 3), marks=pytest.mark.xfail),
- ],
- )
- def test_check_batching(self, device, dtype, input_shape, in_trans_shape):
- input = torch.rand(input_shape, device=device, dtype=dtype)
- in_trans = torch.rand(in_trans_shape, device=device, dtype=dtype)
- augmentation = AugmentationBase2D(p=1.0, p_batch=1)
- augmentation.__check_batching__(input)
- augmentation.__check_batching__((input, in_trans))
-
def test_forward(self, device, dtype):
torch.manual_seed(42)
input = torch.rand((2, 3, 4, 5), device=device, dtype=dtype)
# input_transform = torch.rand((2, 3, 3), device=device, dtype=dtype)
expected_output = torch.rand((2, 3, 4, 5), device=device, dtype=dtype)
- expected_transform = torch.rand((2, 3, 3), device=device, dtype=dtype)
augmentation = AugmentationBase2D(p=1.0)
with patch.object(augmentation, "apply_transform", autospec=True) as apply_transform, patch.object(
augmentation, "generate_parameters", autospec=True
- ) as generate_parameters, patch.object(
- augmentation, "compute_transformation", autospec=True
- ) as compute_transformation:
+ ) as generate_parameters:
# Calling the augmentation with a single tensor shall return the expected tensor using the generated params.
params = {'params': {}, 'flags': {'foo': 0}}
generate_parameters.return_value = params
apply_transform.return_value = expected_output
- compute_transformation.return_value = expected_transform
output = augmentation(input)
# RuntimeError: Boolean value of Tensor with more than one value is ambiguous
# Not an easy fix, happens on verifying torch.tensor([True, True])
@@ -184,10 +162,6 @@ class TestAugmentationBase2D:
augmentation = AugmentationBase2D(p=1.0)
- with patch.object(augmentation, "apply_transform", autospec=True) as apply_transform, patch.object(
- augmentation, "compute_transformation", autospec=True
- ) as compute_transformation:
-
+ with patch.object(augmentation, "apply_transform", autospec=True) as apply_transform:
apply_transform.return_value = output
- compute_transformation.return_value = other_transform
assert gradcheck(augmentation, ((input, input_param)), raise_exception=True, fast_mode=True)
diff --git a/test/augmentation/test_container.py b/test/augmentation/test_container.py
index 4fa1565b9..bdca4e859 100644
--- a/test/augmentation/test_container.py
+++ b/test/augmentation/test_container.py
@@ -226,7 +226,7 @@ class TestAugmentationSequential:
def test_video(self, device, dtype):
input = torch.randn(2, 3, 5, 6, device=device, dtype=dtype)[None]
bbox = torch.tensor([[[1.0, 1.0], [2.0, 1.0], [2.0, 2.0], [1.0, 2.0]]], device=device, dtype=dtype).expand(
- 2, -1, -1
+ 2, 1, -1, -1
)[None]
points = torch.tensor([[[1.0, 1.0]]], device=device, dtype=dtype).expand(2, -1, -1)[None]
aug_list = K.AugmentationSequential(
@@ -336,8 +336,8 @@ class TestAugmentationSequential:
# horizontally flip boxes based on crop width
xmins = expected_out_bbox[..., 0].clone()
xmaxs = expected_out_bbox[..., 2].clone()
- expected_out_bbox[..., 0] = crop_width - xmaxs
- expected_out_bbox[..., 2] = crop_width - xmins
+ expected_out_bbox[..., 0] = crop_width - xmaxs - 1
+ expected_out_bbox[..., 2] = crop_width - xmins - 1
out = aug(input, bbox, params=_params)
assert out[1].shape == bbox.shape
@@ -442,9 +442,9 @@ class TestAugmentationSequential:
assert len(transformed) == len(inputs)
bboxes_transformed = transformed[-1]
- assert len(bboxes_transformed) == len(bbox)
+ assert len(bboxes_transformed) == len(bbox) and isinstance(bboxes_transformed, (list,))
assert len(bboxes_transformed[0]) == 2
- assert len(bboxes_transformed[1]) == 3
+ assert len(bboxes_transformed[1]) == 3, bboxes_transformed[1]
assert len(bboxes_transformed[2]) == 0
@pytest.mark.parametrize('random_apply', [1, (2, 2), (1, 2), (2,), 10, True, False])
@@ -454,7 +454,7 @@ class TestAugmentationSequential:
keypoints = torch.tensor([[[465, 115], [545, 116]]], device=device, dtype=dtype)
mask = bbox_to_mask(
torch.tensor([[[155, 0], [900, 0], [900, 400], [155, 400]]], device=device, dtype=dtype), 1000, 500
- )[:, None].float()
+ )[:, None]
aug = K.AugmentationSequential(
K.ImageSequential(K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), K.RandomAffine(360, p=1.0)),
K.AugmentationSequential(
@@ -487,11 +487,11 @@ class TestAugmentationSequential:
def test_individual_forward_and_inverse(self, device, dtype):
inp = torch.randn(1, 3, 1000, 500, device=device, dtype=dtype)
- bbox = torch.tensor([[[355, 10], [660, 10], [660, 250], [355, 250]]], device=device, dtype=dtype)
+ bbox = torch.tensor([[[[355, 10], [660, 10], [660, 250], [355, 250]]]], device=device, dtype=dtype)
keypoints = torch.tensor([[[465, 115], [545, 116]]], device=device, dtype=dtype)
mask = bbox_to_mask(
torch.tensor([[[155, 0], [900, 0], [900, 400], [155, 400]]], device=device, dtype=dtype), 500, 1000
- )[:, None].float()
+ )[:, None]
crop_size = (200, 200)
aug = K.AugmentationSequential(
@@ -535,7 +535,7 @@ class TestAugmentationSequential:
keypoints = torch.tensor([[[465, 115], [545, 116]]], device=device, dtype=dtype)
mask = bbox_to_mask(
torch.tensor([[[155, 0], [900, 0], [900, 400], [155, 400]]], device=device, dtype=dtype), 1000, 500
- )[:, None].float()
+ )[:, None]
aug = K.AugmentationSequential(
K.ImageSequential(K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), K.RandomAffine(360, p=1.0)),
K.AugmentationSequential(K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), K.RandomAffine(360, p=1.0)),
@@ -579,7 +579,7 @@ class TestAugmentationSequential:
keypoints = torch.tensor([[[465, 115], [545, 116]]], device=device, dtype=dtype)
mask = bbox_to_mask(
torch.tensor([[[155, 0], [900, 0], [900, 400], [155, 400]]], device=device, dtype=dtype), 1000, 500
- )[:, None].float()
+ )[:, None]
aug = K.AugmentationSequential(
K.ImageSequential(K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), K.RandomAffine(360, p=1.0)),
K.AugmentationSequential(K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), K.RandomAffine(360, p=1.0)),