Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

[feat] Added more augmentations containers (#1014)

shijianjian5713087423fb
diff --git a/docs/source/augmentation.container.rst b/docs/source/augmentation.container.rst
index d288f6ed8..1d7bd3ac3 100644
--- a/docs/source/augmentation.container.rst
+++ b/docs/source/augmentation.container.rst
@@ -3,17 +3,40 @@ Augmentation Containers
.. currentmodule:: kornia.augmentation.container
-The classes in this section are containers for augmenting different data formats (e.g. videos).
+The classes in this section are containers for augmenting different data formats (e.g. images, videos).
-Video Data Augmentation
+Augmentation Sequential
-----------------------
-.. autoclass:: VideoSequential
+Kornia augmentations provides simple on-device augmentation framework with the support of various syntax sugars
+(e.g. return transformation matrix, inverse geometric transform). Therefore, we provide advanced augmentation
+container to ease the pain of building augmenation pipelines. This API would also provide predefined routines
+for automating the processing of masks, bounding boxes, and keypoints.
+
+.. autoclass:: AugmentationSequential
+
+ .. automethod:: forward
+
+ .. automethod:: inverse
+
+
+
+ImageSequential
+---------------
+
+Kornia augmentations provides simple on-device augmentation framework with the support of various syntax sugars
+(e.g. return transformation matrix, inverse geometric transform). Additionally, ImageSequential supports the
+mix usage of both image processing and augmentation modules.
+
+.. autoclass:: ImageSequential
.. automethod:: forward
+Video Data Augmentation
+-----------------------
+
Video data is a special case of 3D volumetric data that contains both spatial and temporal information, which can be referred as 2.5D than 3D.
In most applications, augmenting video data requires a static temporal dimension to have the same augmentations are performed for each frame.
Thus, `VideoSequential` can be used to do such trick as same as `nn.Sequential`.
@@ -29,3 +52,7 @@ Currently, `VideoSequential` supports data format like :math:`(B, C, T, H, W)` a
data_format="BCTHW",
same_on_frame=True
)
+
+.. autoclass:: VideoSequential
+
+ .. automethod:: forward
diff --git a/kornia/augmentation/.augmentation.py.swm b/kornia/augmentation/.augmentation.py.swm
deleted file mode 100644
index f307c5e54..000000000
Binary files a/kornia/augmentation/.augmentation.py.swm and /dev/null differ
diff --git a/kornia/augmentation/__init__.py b/kornia/augmentation/__init__.py
index 4f1aebcc2..6d17c30b8 100644
--- a/kornia/augmentation/__init__.py
+++ b/kornia/augmentation/__init__.py
@@ -40,7 +40,7 @@ from .augmentation3d import (
RandomPerspective3D,
)
from .mix_augmentation import RandomMixUp, RandomCutMix
-from .container import VideoSequential
+from .container import VideoSequential, AugmentationSequential, ImageSequential
__all__ = [
"AugmentationBase2D",
@@ -52,33 +52,38 @@ __all__ = [
"RandomAffine",
"RandomBoxBlur",
"RandomCrop",
+ "RandomChannelShuffle",
"RandomErasing",
"RandomElasticTransform",
"RandomFisheye",
"RandomGrayscale",
+ "RandomGaussianNoise",
"RandomHorizontalFlip",
"RandomVerticalFlip",
"RandomPerspective",
"RandomResizedCrop",
"RandomRotation",
"RandomSolarize",
- "RandomPosterize",
"RandomSharpness",
+ "RandomPosterize",
"RandomEqualize",
"RandomMotionBlur",
+ "RandomInvert",
+ "RandomThinPlateSpline",
"RandomMixUp",
"RandomCutMix",
"AugmentationBase3D",
+ "CenterCrop3D",
+ "RandomAffine3D",
+ "RandomCrop3D",
"RandomDepthicalFlip3D",
"RandomVerticalFlip3D",
"RandomHorizontalFlip3D",
"RandomRotation3D",
- "RandomMotionBlur3D",
- "RandomAffine3D",
"RandomPerspective3D",
- "RandomCrop3D",
- "CenterCrop3D",
"RandomEqualize3D",
+ "RandomMotionBlur3D",
+ "AugmentationSequential",
+ "ImageSequential",
"VideoSequential",
- "RandomThinPlateSpline",
]
diff --git a/kornia/augmentation/augmentation.py b/kornia/augmentation/augmentation.py
index 3754fa88b..92ac04540 100644
--- a/kornia/augmentation/augmentation.py
+++ b/kornia/augmentation/augmentation.py
@@ -1,10 +1,7 @@
-from re import S
-from typing import Callable, Tuple, Union, List, Optional, Dict, cast
+from typing import Tuple, Union, List, Optional, Dict, cast
import warnings
import torch
-from torch.functional import Tensor
-import torch.nn as nn
from torch.nn.functional import pad
from kornia.constants import Resample, BorderType, SamplePadding, pi
@@ -14,7 +11,6 @@ from kornia.geometry import (
affine,
bbox_generator,
bbox_to_mask,
- crop_by_boxes,
crop_by_transform_mat,
deg2rad,
elastic_transform2d,
@@ -23,7 +19,6 @@ from kornia.geometry import (
get_tps_transform,
hflip,
vflip,
- rotate,
warp_affine,
warp_image_tps,
warp_perspective,
@@ -41,8 +36,6 @@ from kornia.enhance import (
adjust_contrast,
adjust_saturation,
adjust_hue,
- adjust_gamma,
- Invert,
)
from kornia.filters import box_blur
from kornia.utils import _extract_device_dtype, create_meshgrid
@@ -677,13 +670,13 @@ class RandomAffine(GeometricAugmentationBase2D):
def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
return get_affine_matrix2d(
- params['translations'],
- params['center'],
- params['scale'],
- params['angle'],
- deg2rad(params['sx']),
- deg2rad(params['sy']),
- ).type_as(input)
+ torch.as_tensor(params['translations'], device=input.device, dtype=input.dtype),
+ torch.as_tensor(params['center'], device=input.device, dtype=input.dtype),
+ torch.as_tensor(params['scale'], device=input.device, dtype=input.dtype),
+ torch.as_tensor(params['angle'], device=input.device, dtype=input.dtype),
+ deg2rad(torch.as_tensor(params['sx'], device=input.device, dtype=input.dtype)),
+ deg2rad(torch.as_tensor(params['sy'], device=input.device, dtype=input.dtype)),
+ )
def apply_transform(
self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
diff --git a/kornia/augmentation/base.py b/kornia/augmentation/base.py
index c5a7cd96b..1a0b2ec1d 100644
--- a/kornia/augmentation/base.py
+++ b/kornia/augmentation/base.py
@@ -341,12 +341,27 @@ class GeometricAugmentationBase2D(AugmentationBase2D):
**kwargs,
) -> torch.Tensor:
"""By default, the exact transformation as ``apply_transform`` will be used."""
- return self.apply_transform(input, params=self._params, transform=transform)
+ return self.apply_transform(
+ input, params=self._params, transform=torch.as_tensor(transform, device=input.device, dtype=input.dtype)
+ )
def compute_inverse_transformation(self, transform: torch.Tensor):
"""Compute the inverse transform of given transformation matrices."""
return _torch_inverse_cast(transform)
+ def get_transformation_matrix(
+ self, input: torch.Tensor, params: Optional[Dict[str, torch.Tensor]] = None
+ ) -> torch.Tensor:
+ if params is not None:
+ transform = self.compute_transformation(input, params)
+ elif not hasattr(self, "_transform_matrix"):
+ params = self.forward_parameters(input.shape)
+ transform = self.identity_matrix(input)
+ transform[params['batch_prob']] = self.compute_transformation(input[params['batch_prob']], params)
+ else:
+ transform = self._transform_matrix
+ return torch.as_tensor(transform, device=input.device, dtype=input.dtype)
+
def inverse(
self,
input: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]],
@@ -357,7 +372,11 @@ class GeometricAugmentationBase2D(AugmentationBase2D):
if isinstance(input, (list, tuple)):
input, transform = input
else:
- transform = self._transform_matrix
+ transform = self.get_transformation_matrix(input, params)
+ if params is not None:
+ transform = self.identity_matrix(input)
+ transform[params['batch_prob']] = self.compute_transformation(input[params['batch_prob']], params)
+
ori_shape = input.shape
in_tensor = self.transform_tensor(input)
batch_shape = input.shape
diff --git a/kornia/augmentation/container/__init__.py b/kornia/augmentation/container/__init__.py
index 8fd46ab1d..7bcd66194 100644
--- a/kornia/augmentation/container/__init__.py
+++ b/kornia/augmentation/container/__init__.py
@@ -1 +1,3 @@
from .video import VideoSequential
+from .augment import AugmentationSequential
+from .image import ImageSequential
diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.py
new file mode 100644
index 000000000..66da62d7c
--- /dev/null
+++ b/kornia/augmentation/container/augment.py
@@ -0,0 +1,271 @@
+from typing import Tuple, Union, Optional, List, Dict, cast
+
+import torch
+import torch.nn as nn
+
+from kornia.geometry import transform_points, transform_boxes
+from kornia.augmentation.base import _AugmentationBase, IntensityAugmentationBase2D, GeometricAugmentationBase2D
+from kornia.constants import DataKey
+from .image import ImageSequential
+
+
+class AugmentationSequential(ImageSequential):
+ r"""AugmentationSequential for handling multiple input types like inputs, masks, keypoints at once.
+
+ Args:
+ *args (_AugmentationBase): a list of kornia augmentation modules.
+ data_keys (List[str]): the input type sequential for applying augmentations.
+ Accepts "input", "mask", "bbox", "bbox_xyxy", "bbox_xywh", "keypoints".
+ same_on_batch (bool, optional): apply the same transformation across the batch.
+ If None, it will not overwrite the function-wise settings. Default: None.
+ return_transform (bool, optional): if ``True`` return the matrix describing the transformation
+ applied to each. If None, it will not overwrite the function-wise settings. Default: None.
+ keepdim (bool, optional): whether to keep the output shape the same as input (True) or broadcast it
+ to the batch form (False). If None, it will not overwrite the function-wise settings. Default: None.
+
+ Return:
+ List[Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]]: the tensor (, and the transformation matrix)
+ has been sequentially modified by the args.
+
+ Examples:
+ >>> import kornia
+ >>> input = torch.randn(2, 3, 5, 6)
+ >>> bbox = torch.tensor([[
+ ... [1., 1.],
+ ... [2., 1.],
+ ... [2., 2.],
+ ... [1., 2.],
+ ... ]]).expand(2, -1, -1)
+ >>> points = torch.tensor([[[1., 1.]]]).expand(2, -1, -1)
+ >>> aug_list = AugmentationSequential(
+ ... kornia.augmentation.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0),
+ ... kornia.augmentation.RandomAffine(360, p=1.0),
+ ... data_keys=["input", "mask", "bbox", "keypoints"],
+ ... return_transform=False,
+ ... same_on_batch=False,
+ ... )
+ >>> out = aug_list(input, input, 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])]
+ >>> 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])]
+ """
+
+ def __init__(
+ self,
+ *args: _AugmentationBase,
+ data_keys: List[Union[str, int, DataKey]] = [DataKey.INPUT],
+ same_on_batch: Optional[bool] = None,
+ return_transform: Optional[bool] = None,
+ keepdim: Optional[bool] = None,
+ ) -> None:
+ super(AugmentationSequential, self).__init__(
+ *args, same_on_batch=same_on_batch, return_transform=return_transform, keepdim=keepdim
+ )
+
+ self.data_keys = [DataKey.get(inp) for inp in data_keys]
+
+ assert all(
+ [in_type in DataKey for in_type in self.data_keys]
+ ), f"`data_keys` must be in {DataKey}. Got {data_keys}."
+
+ if self.data_keys[0] != DataKey.INPUT:
+ raise NotImplementedError(f"The first input must be {DataKey.INPUT}.")
+
+ def apply_to_mask(
+ self, input: torch.Tensor, module: nn.Module, param: Optional[Dict[str, torch.Tensor]] = None
+ ) -> torch.Tensor:
+ if isinstance(module, GeometricAugmentationBase2D) and param is None:
+ input = module(input, return_transform=False)
+ elif isinstance(module, GeometricAugmentationBase2D) and param is not None:
+ input = module(input, param, return_transform=False)
+ else:
+ pass # No need to update anything
+ return input
+
+ def apply_to_bbox(
+ self,
+ input: torch.Tensor,
+ module: nn.Module,
+ param: Optional[Dict[str, torch.Tensor]] = None,
+ mode: str = "xyxy",
+ ) -> torch.Tensor:
+ if isinstance(module, GeometricAugmentationBase2D) and param is None:
+ raise ValueError(f"Transformation matrix for {module} has not been computed.")
+ elif isinstance(module, GeometricAugmentationBase2D) and param is not None:
+ input = transform_boxes(module.get_transformation_matrix(input, param), input, mode)
+ else:
+ pass # No need to update anything
+ return input
+
+ def apply_to_keypoints(
+ self, input: torch.Tensor, module: nn.Module, param: Optional[Dict[str, torch.Tensor]] = None
+ ) -> torch.Tensor:
+ if isinstance(module, GeometricAugmentationBase2D) and param is None:
+ raise ValueError(f"Transformation matrix for {module} has not been computed.")
+ elif isinstance(module, GeometricAugmentationBase2D) and param is not None:
+ input = transform_points(module.get_transformation_matrix(input, param), input)
+ else:
+ pass # No need to update anything
+ return input
+
+ def apply_by_key(
+ self,
+ input: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]],
+ module: nn.Module,
+ param: Optional[Dict[str, torch.Tensor]] = None,
+ dcate: Union[str, int, DataKey] = DataKey.INPUT,
+ ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
+ if DataKey.get(dcate) in [DataKey.INPUT]:
+ return self.apply_to_input(input, module, param)
+ if DataKey.get(dcate) in [DataKey.MASK]:
+ if isinstance(input, (tuple,)):
+ return (self.apply_to_mask(input[0], module, param), *input[1:])
+ return self.apply_to_mask(input, module, param)
+ if DataKey.get(dcate) in [DataKey.BBOX, DataKey.BBOX_XYXY]:
+ if isinstance(input, (tuple,)):
+ return (self.apply_to_bbox(input[0], module, param, mode='xyxy'), *input[1:])
+ return self.apply_to_bbox(input, module, param, mode='xyxy')
+ if DataKey.get(dcate) in [DataKey.BBOX_XYHW]:
+ if isinstance(input, (tuple,)):
+ return (self.apply_to_bbox(input[0], module, param, mode='xyhw'), *input[1:])
+ return self.apply_to_bbox(input, module, param, mode='xyhw')
+ if DataKey.get(dcate) in [DataKey.KEYPOINTS]:
+ if isinstance(input, (tuple,)):
+ return (self.apply_to_keypoints(input[0], module, param), *input[1:])
+ return self.apply_to_keypoints(input, module, param)
+ raise NotImplementedError(f"input type of {dcate} is not implemented.")
+
+ def inverse_input(
+ self, input: torch.Tensor, module: nn.Module, param: Optional[Dict[str, torch.Tensor]] = None
+ ) -> torch.Tensor:
+ if isinstance(module, GeometricAugmentationBase2D) and param is None:
+ input = module.inverse(input)
+ elif isinstance(module, GeometricAugmentationBase2D) and param is not None:
+ input = module.inverse(input, param)
+ else:
+ pass # No need to update anything
+ return input
+
+ def inverse_bbox(
+ self,
+ input: torch.Tensor,
+ module: nn.Module,
+ param: Optional[Dict[str, torch.Tensor]] = None,
+ mode: str = "xyxy",
+ ) -> torch.Tensor:
+ if isinstance(module, GeometricAugmentationBase2D):
+ transform = module.compute_inverse_transformation(module.get_transformation_matrix(input, param))
+ input = transform_boxes(torch.as_tensor(transform, device=input.device, dtype=input.dtype), input, mode)
+ return input
+
+ def inverse_keypoints(
+ self, input: torch.Tensor, module: nn.Module, param: Optional[Dict[str, torch.Tensor]] = None
+ ) -> torch.Tensor:
+ if isinstance(module, GeometricAugmentationBase2D):
+ transform = module.compute_inverse_transformation(module.get_transformation_matrix(input, param))
+ input = transform_points(torch.as_tensor(transform, device=input.device, dtype=input.dtype), input)
+ return input
+
+ def inverse_by_key(
+ self,
+ input: torch.Tensor,
+ module: nn.Module,
+ param: Optional[Dict[str, torch.Tensor]] = None,
+ dcate: Union[str, int, DataKey] = DataKey.INPUT,
+ ) -> torch.Tensor:
+ if DataKey.get(dcate) in [DataKey.INPUT, DataKey.MASK]:
+ return self.inverse_input(input, module, param)
+ if DataKey.get(dcate) in [DataKey.BBOX, DataKey.BBOX_XYXY]:
+ return self.inverse_bbox(input, module, param, mode='xyxy')
+ if DataKey.get(dcate) in [DataKey.BBOX_XYHW]:
+ return self.inverse_bbox(input, module, param, mode='xyhw')
+ if DataKey.get(dcate) in [DataKey.KEYPOINTS]:
+ return self.inverse_keypoints(input, module, param)
+ raise NotImplementedError(f"input type of {dcate} is not implemented.")
+
+ def inverse(
+ self,
+ *args: torch.Tensor,
+ params: Optional[Dict[str, Dict[str, torch.Tensor]]] = None,
+ data_keys: Optional[List[Union[str, int, DataKey]]] = None,
+ ) -> Union[torch.Tensor, List[torch.Tensor]]:
+ """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 = cast(List[Union[str, int, DataKey]], self.data_keys)
+ assert len(args) == len(data_keys), (
+ "The number of inputs must align with the number of data_keys, " f"Got {len(args)} and {len(data_keys)}."
+ )
+ self._params = {}
+ params = params if params is not None else {}
+
+ outputs = []
+ for input, dcate in zip(args, data_keys):
+ for module in list(self.children())[::-1]:
+ if isinstance(module, _AugmentationBase):
+ func_name = module.__class__.__name__
+ # Check if a param recorded
+ param = self._params[func_name] if func_name in self._params else None
+ # Check if a param provided. If provided, it will overwrite the recorded ones.
+ param = params[func_name] if func_name in params else param
+ else:
+ param = None
+ if isinstance(module, GeometricAugmentationBase2D) and dcate in DataKey:
+ # Waiting for #1013 to specify the geometric and intensity augmentations.
+ input = self.inverse_by_key(input, module, param, dcate)
+ elif isinstance(module, IntensityAugmentationBase2D) and dcate in DataKey:
+ pass # Do nothing
+ else:
+ raise NotImplementedError(f"data_key {dcate} is not implemented for {module}.")
+ outputs.append(input)
+
+ if len(outputs) == 1:
+ return outputs[0]
+
+ return outputs
+
+ def forward( # type: ignore
+ self,
+ *args: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]],
+ params: Optional[Dict[str, Dict[str, torch.Tensor]]] = None,
+ data_keys: Optional[List[Union[str, int, DataKey]]] = None,
+ ) -> Union[
+ torch.Tensor, Tuple[torch.Tensor, torch.Tensor], List[Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]]
+ ]:
+ if data_keys is None:
+ self._params = {}
+ data_keys = cast(List[Union[str, int, DataKey]], self.data_keys)
+
+ """Compute multiple tensors simultaneously according to ``self.data_keys``."""
+ assert len(args) == len(
+ data_keys
+ ), f"The number of inputs must align with the number of data_keys. Got {len(args)} and {len(data_keys)}."
+ params = params if params is not None else {}
+
+ outputs = []
+ for input, dcate in zip(args, data_keys):
+ for module in self.children():
+ func_name = module.__class__.__name__
+ # Check if a param recorded
+ param = self._params[func_name] if func_name in self._params else None
+ # Check if a param provided. If provided, it will overwrite the recorded ones.
+ param = params[func_name] if func_name in params else param
+
+ if dcate == DataKey.INPUT:
+ input = self.apply_to_input(input, module, param)
+ elif isinstance(module, GeometricAugmentationBase2D) and dcate in DataKey:
+ input = self.apply_by_key(input, module, param, dcate)
+ elif isinstance(module, IntensityAugmentationBase2D) and dcate in DataKey:
+ pass # Do nothing
+ else:
+ raise NotImplementedError(f"data_key {dcate} is not implemented for {module}.")
+ outputs.append(input)
+ if len(outputs) == 1:
+ return outputs[0]
+
+ return outputs
diff --git a/kornia/augmentation/container/image.py b/kornia/augmentation/container/image.py
new file mode 100644
index 000000000..c173fef33
--- /dev/null
+++ b/kornia/augmentation/container/image.py
@@ -0,0 +1,105 @@
+from typing import Dict, Optional, Tuple, Union
+
+import torch
+import torch.nn as nn
+
+from kornia.augmentation.base import _AugmentationBase
+
+
+class ImageSequential(nn.Sequential):
+ r"""Sequential for creating kornia image processing pipeline.
+
+ Args:
+ *args (nn.Module): a list of kornia augmentation and image operation modules.
+ same_on_batch (bool, optional): apply the same transformation across the batch.
+ If None, it will not overwrite the function-wise settings. Default: None.
+ return_transform (bool, optional): if ``True`` return the matrix describing the transformation
+ applied to each. If None, it will not overwrite the function-wise settings. Default: None.
+ keepdim (bool, optional): whether to keep the output shape the same as input (True) or broadcast it
+ to the batch form (False). If None, it will not overwrite the function-wise settings. Default: None.
+
+ Returns:
+ Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]: the tensor (, and the transformation matrix)
+ has been sequentially modified by the args.
+
+ Examples:
+ >>> import kornia
+ >>> input = torch.randn(2, 3, 5, 6)
+ >>> aug_list = ImageSequential(
+ ... kornia.color.BgrToRgb(),
+ ... kornia.augmentation.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0),
+ ... kornia.filters.MedianBlur((3, 3)),
+ ... kornia.augmentation.RandomAffine(360, p=1.0),
+ ... kornia.enhance.Invert(),
+ ... return_transform=True,
+ ... same_on_batch=True,
+ ... )
+ >>> out = aug_list(input)
+ >>> out[0].shape, out[1].shape
+ (torch.Size([2, 3, 5, 6]), torch.Size([2, 3, 3]))
+
+ Reproduce with provided params.
+ >>> out2 = aug_list(input, params=aug_list._params)
+ >>> torch.equal(out[0], out2[0]), torch.equal(out[1], out2[1])
+ (True, True)
+
+ Note:
+ Transformation matrix returned only considers the transformation applied in ``kornia.augmentation`` module.
+ Those transformations in ``kornia.geometry`` will not be taken into account.
+ """
+
+ def __init__(
+ self,
+ *args: nn.Module,
+ same_on_batch: Optional[bool] = None,
+ return_transform: Optional[bool] = None,
+ keepdim: Optional[bool] = None,
+ ) -> None:
+ super(ImageSequential, self).__init__(*args)
+ self.same_on_batch = same_on_batch
+ self.return_transform = return_transform
+ self.keepdim = keepdim
+ for arg in args:
+ if not isinstance(arg, nn.Module):
+ raise NotImplementedError(f"Only nn.Module are supported at this moment. Got {arg}.")
+ if isinstance(arg, _AugmentationBase):
+ if same_on_batch is not None:
+ arg.same_on_batch = same_on_batch
+ if return_transform is not None:
+ arg.return_transform = return_transform
+ if keepdim is not None:
+ arg.keepdim = keepdim
+ self._params: Dict[str, Dict[str, torch.Tensor]] = {}
+
+ def apply_to_input(
+ self,
+ input: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]],
+ module: nn.Module,
+ param: Optional[Dict[str, torch.Tensor]] = None,
+ ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
+ func_name = module.__class__.__name__
+ if isinstance(module, _AugmentationBase) and param is None:
+ input = module(input)
+ self._params.update({func_name: module._params})
+ elif isinstance(module, _AugmentationBase) and param is not None:
+ input = module(input, param)
+ self._params.update({func_name: param})
+ else:
+ # In case of return_transform = True
+ if isinstance(input, (tuple, list)):
+ input = (module(input[0]), input[1])
+ else:
+ input = module(input)
+ return input
+
+ def forward(
+ self, input: torch.Tensor, params: Optional[Dict[str, Dict[str, torch.Tensor]]] = None
+ ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
+ if params is None:
+ params = {}
+ self._params = {}
+ for module in self.children():
+ func_name = module.__class__.__name__
+ param = params[func_name] if func_name in params else None
+ input = self.apply_to_input(input, module, param) # type: ignore
+ return input
diff --git a/kornia/augmentation/container/video.py b/kornia/augmentation/container/video.py
index ecfc5765f..a7d614119 100644
--- a/kornia/augmentation/container/video.py
+++ b/kornia/augmentation/container/video.py
@@ -4,10 +4,12 @@ import torch
import torch.nn as nn
import kornia
-from kornia.augmentation.base import _AugmentationBase, MixAugmentationBase
+from kornia.augmentation.base import _AugmentationBase
+from .image import ImageSequential
-class VideoSequential(nn.Sequential):
+# TODO: Rewrite this to support inverse operation by having a generic AugmentationSequential.
+class VideoSequential(ImageSequential):
r"""VideoSequential for processing 5-dim video data like (B, T, C, H, W) and (B, C, T, H, W).
`VideoSequential` is used to replace `nn.Sequential` for processing video data augmentations.
@@ -27,6 +29,7 @@ class VideoSequential(nn.Sequential):
>>> input = torch.randn(2, 3, 1, 5, 6).repeat(1, 1, 4, 1, 1)
>>> aug_list = VideoSequential(
... kornia.augmentation.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0),
+ ... kornia.color.BgrToRgb(),
... kornia.augmentation.RandomAffine(360, p=1.0),
... data_format="BCTHW",
... same_on_frame=True)
@@ -52,12 +55,9 @@ class VideoSequential(nn.Sequential):
tensor(False)
"""
- def __init__(self, *args: _AugmentationBase, data_format="BTCHW", same_on_frame: bool = True) -> None:
- super(VideoSequential, self).__init__(*args)
+ def __init__(self, *args: nn.Module, data_format="BTCHW", same_on_frame: bool = True) -> None:
+ super(VideoSequential, self).__init__(*args, same_on_batch=None, return_transform=None, keepdim=None)
self.same_on_frame = same_on_frame
- for aug in args:
- if isinstance(aug, MixAugmentationBase):
- raise NotImplementedError(f"MixAugmentations are not supported at this moment. Got {aug}.")
self.data_format = data_format.upper()
assert self.data_format in ["BCTHW", "BTCHW"], f"Only `BCTHW` and `BTCHW` are supported. Got `{data_format}`."
self._temporal_channel: int
@@ -100,7 +100,8 @@ class VideoSequential(nn.Sequential):
pass
return input
- def forward(self, input: torch.Tensor) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
+ def forward(self, input: torch.Tensor) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]: # type: ignore
+ """Define the video computation performed."""
assert len(input.shape) == 5, f"Input must be a 5-dim tensor. Got {input.shape}."
# Size of T
frame_num = input.size(self._temporal_channel)
@@ -112,14 +113,17 @@ class VideoSequential(nn.Sequential):
# Overwrite param generation shape to (B * T, C, H, W).
batch_shape = input.shape
for aug in self.children():
- aug = cast(_AugmentationBase, aug)
- param = aug.forward_parameters(batch_shape)
- if self.same_on_frame:
- for k, v in param.items():
- # TODO: revise colorjitter order param in the future to align the standard.
- if not (k == "order" and isinstance(aug, kornia.augmentation.ColorJitter)):
- param.update({k: self.__repeat_param_across_channels__(v, frame_num)})
- input = aug(input, params=param)
+ if isinstance(aug, _AugmentationBase):
+ param = aug.forward_parameters(batch_shape)
+ if self.same_on_frame:
+ for k, v in param.items():
+ # TODO: revise colorjitter order param in the future to align the standard.
+ if not (k == "order" and isinstance(aug, kornia.augmentation.ColorJitter)):
+ param.update({k: self.__repeat_param_across_channels__(v, frame_num)})
+ else:
+ param = None
+
+ input = self.apply_to_input(input, aug, param=param) # type: ignore
if isinstance(input, (tuple, list)):
input[0] = self._input_shape_convert_back(input[0], frame_num)
diff --git a/kornia/constants.py b/kornia/constants.py
index ab9089530..b4f6ddee3 100644
--- a/kornia/constants.py
+++ b/kornia/constants.py
@@ -1,5 +1,5 @@
-from typing import Union, TypeVar
-from enum import Enum
+from typing import Union, TypeVar, cast
+from enum import Enum, EnumMeta
import torch
@@ -21,20 +21,42 @@ class ConstantBase:
raise TypeError()
-class Resample(ConstantBase, Enum):
+class EnumMetaFlags(EnumMeta):
+ def __contains__(self, other: Union[str, int, T]) -> bool: # type: ignore
+ if type(other) == str:
+ other = cast(str, other)
+ return any([val.name == other.upper() for val in self]) # type: ignore
+ if type(other) == int:
+ return any([val.value == other for val in self]) # type: ignore
+ return any([val == other for val in self]) # type: ignore
+
+ def __repr__(self):
+ return ' | '.join(f"{self.__name__}.{val.name}" for val in self)
+
+
+class Resample(ConstantBase, Enum, metaclass=EnumMetaFlags):
NEAREST = 0
BILINEAR = 1
BICUBIC = 2
-class BorderType(ConstantBase, Enum):
+class BorderType(ConstantBase, Enum, metaclass=EnumMetaFlags):
CONSTANT = 0
REFLECT = 1
REPLICATE = 2
CIRCULAR = 3
-class SamplePadding(ConstantBase, Enum):
+class SamplePadding(ConstantBase, Enum, metaclass=EnumMetaFlags):
ZEROS = 0
BORDER = 1
REFLECTION = 2
+
+
+class DataKey(ConstantBase, Enum, metaclass=EnumMetaFlags):
+ INPUT = 0
+ MASK = 1
+ BBOX = 2
+ BBOX_XYXY = 3
+ BBOX_XYHW = 4
+ KEYPOINTS = 5
diff --git a/kornia/geometry/linalg.py b/kornia/geometry/linalg.py
index ca0ea403d..91e46a57c 100644
--- a/kornia/geometry/linalg.py
+++ b/kornia/geometry/linalg.py
@@ -183,12 +183,6 @@ def transform_points(trans_01: torch.Tensor, points_1: torch.Tensor) -> torch.Te
"""
check_is_tensor(trans_01)
check_is_tensor(points_1)
- if not (trans_01.device == points_1.device and trans_01.dtype == points_1.dtype):
- raise TypeError(
- "Tensor must be in the same device and dtype. "
- f"Got trans_01 with ({trans_01.dtype}, {points_1.dtype}) and "
- f"points_1 with ({points_1.dtype}, {points_1.dtype})"
- )
if not trans_01.shape[0] == points_1.shape[0] and trans_01.shape[0] != 1:
raise ValueError("Input batch size must be the same for both tensors or 1")
if not trans_01.shape[-1] == (points_1.shape[-1] + 1):
@@ -232,12 +226,6 @@ def transform_boxes(trans_mat: torch.Tensor, boxes: torch.Tensor, mode: str = "x
"""
- if not torch.is_tensor(boxes):
- raise TypeError(f"Boxes type is not a torch.Tensor. Got {type(boxes)}")
-
- if not torch.is_tensor(trans_mat):
- raise TypeError(f"Tranformation matrix type is not a torch.Tensor. Got {type(trans_mat)}")
-
if not isinstance(mode, str):
raise TypeError(f"Mode must be a string. Got {type(mode)}")
diff --git a/test/augmentation/test_container.py b/test/augmentation/test_container.py
index 17bf3eb02..14681d691 100644
--- a/test/augmentation/test_container.py
+++ b/test/augmentation/test_container.py
@@ -1,7 +1,12 @@
import pytest
import torch
+from torch.testing import assert_allclose
+
+import kornia
import kornia.augmentation as K
+from kornia.geometry.transform import bbox_to_mask
+from kornia.constants import BorderType
class TestVideoSequential:
@@ -59,7 +64,7 @@ class TestVideoSequential:
[
[K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0), K.RandomAffine(360, p=1.0)],
[K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0)],
- [K.RandomAffine(360, p=1.0)],
+ [K.RandomAffine(360, p=1.0), kornia.color.BgrToRgb()],
[K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=0.0), K.RandomAffine(360, p=0.0)],
[K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=0.0)],
[K.RandomAffine(360, p=0.0)],
@@ -117,3 +122,152 @@ class TestVideoSequential:
op = K.VideoSequential(K.ColorJitter(0.1, 0.1, 0.1, 0.1), same_on_frame=True)
op_jit = torch.jit.script(op)
assert_allclose(op(img), op_jit(img))
+
+
+class TestSequential:
+ @pytest.mark.parametrize('same_on_batch', [True, False, None])
+ @pytest.mark.parametrize("return_transform", [True, False, None])
+ @pytest.mark.parametrize("keepdim", [True, False, None])
+ def test_construction(self, same_on_batch, return_transform, keepdim):
+ K.ImageSequential(
+ K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0),
+ K.RandomAffine(360, p=1.0),
+ same_on_batch=same_on_batch,
+ return_transform=return_transform,
+ keepdim=keepdim,
+ )
+
+ @pytest.mark.parametrize("return_transform", [True, False, None])
+ def test_forward(self, return_transform, device, dtype):
+ inp = torch.randn(1, 3, 30, 30, device=device, dtype=dtype)
+ aug = K.ImageSequential(
+ K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0),
+ kornia.filters.MedianBlur((3, 3)),
+ K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0, return_transform=True),
+ K.RandomAffine(360, p=1.0),
+ return_transform=return_transform,
+ )
+ out = aug(inp)
+ if isinstance(out, (tuple,)):
+ assert out[0].shape == inp.shape
+ else:
+ assert out.shape == inp.shape
+
+
+class TestAugmentationSequential:
+ @pytest.mark.parametrize(
+ 'data_keys', ["input", ["mask", "input"], ["input", "bbox_yxyx"], [0, 10], [BorderType.REFLECT]]
+ )
+ @pytest.mark.parametrize("augmentation_list", [K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0)])
+ def test_exception(self, augmentation_list, data_keys, device, dtype):
+ with pytest.raises(Exception): # AssertError and NotImplementedError
+ K.AugmentationSequential(augmentation_list, data_keys=data_keys)
+
+ def test_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)
+ 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()
+ aug = K.AugmentationSequential(
+ K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0),
+ K.RandomAffine(360, p=1.0),
+ data_keys=["input", "mask", "bbox", "keypoints"],
+ )
+ out = aug(inp, mask, bbox, keypoints)
+ assert out[0].shape == inp.shape
+ assert out[1].shape == mask.shape
+ assert out[2].shape == bbox.shape
+ assert out[3].shape == keypoints.shape
+
+ out_inv = aug.inverse(*out)
+ assert out_inv[0].shape == inp.shape
+ assert out_inv[1].shape == mask.shape
+ assert out_inv[2].shape == bbox.shape
+ assert out_inv[3].shape == keypoints.shape
+
+ 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)
+ 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()
+
+ aug = K.AugmentationSequential(K.RandomAffine(360, p=1.0, return_transform=True))
+ assert aug(inp, data_keys=['input'])[0].shape == inp.shape
+ aug = K.AugmentationSequential(K.RandomAffine(360, p=1.0, return_transform=False))
+ assert aug(inp, data_keys=['input']).shape == inp.shape
+ assert aug(mask, data_keys=['mask']).shape == mask.shape
+ assert aug(bbox, data_keys=['bbox']).shape == bbox.shape
+ assert aug(keypoints, data_keys=['keypoints']).shape == keypoints.shape
+
+ aug = K.AugmentationSequential(K.RandomAffine(360, p=1.0, return_transform=True))
+ assert aug.inverse(inp, data_keys=['input']).shape == inp.shape
+ aug = K.AugmentationSequential(K.RandomAffine(360, p=1.0, return_transform=True))
+ assert aug.inverse(bbox, data_keys=['bbox']).shape == bbox.shape
+ aug = K.AugmentationSequential(K.RandomAffine(360, p=1.0, return_transform=True))
+ assert aug.inverse(keypoints, data_keys=['keypoints']).shape == keypoints.shape
+ aug = K.AugmentationSequential(K.RandomAffine(360, p=1.0, return_transform=True))
+ assert aug.inverse(mask, data_keys=['mask']).shape == mask.shape
+
+ def test_forward_and_inverse_return_transform(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)
+ 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()
+ aug = K.AugmentationSequential(
+ K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0, return_transform=True),
+ K.RandomAffine(360, p=1.0, return_transform=True),
+ data_keys=["input", "mask", "bbox", "keypoints"],
+ )
+ out = aug(inp, mask, bbox, keypoints)
+ assert out[0][0].shape == inp.shape
+ assert out[1].shape == mask.shape
+ assert out[2].shape == bbox.shape
+ assert out[3].shape == keypoints.shape
+
+ out_inv = aug.inverse(*out)
+ assert out_inv[0].shape == inp.shape
+ assert out_inv[1].shape == mask.shape
+ assert out_inv[2].shape == bbox.shape
+ assert out_inv[3].shape == keypoints.shape
+
+ def test_inverse_and_forward_return_transform(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)
+ 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()
+ aug = K.AugmentationSequential(
+ K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0, return_transform=True),
+ K.RandomAffine(360, p=1.0, return_transform=True),
+ data_keys=["input", "mask", "bbox", "keypoints"],
+ )
+
+ out_inv = aug.inverse(inp, mask, bbox, keypoints)
+ assert out_inv[0].shape == inp.shape
+ assert out_inv[1].shape == mask.shape
+ assert out_inv[2].shape == bbox.shape
+ assert out_inv[3].shape == keypoints.shape
+
+ out = aug(inp, mask, bbox, keypoints)
+ assert out[0][0].shape == inp.shape
+ assert out[1].shape == mask.shape
+ assert out[2].shape == bbox.shape
+ assert out[3].shape == keypoints.shape
+
+ @pytest.mark.jit
+ @pytest.mark.skip(reason="turn off due to Union Type")
+ def test_jit(self, device, dtype):
+ B, C, H, W = 2, 3, 4, 4
+ img = torch.ones(B, C, H, W, device=device, dtype=dtype)
+ op = K.AugmentationSequential(
+ K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0), K.RandomAffine(360, p=1.0), same_on_batch=True
+ )
+ op_jit = torch.jit.script(op)
+ assert_allclose(op(img), op_jit(img))
diff --git a/test/augmentation/test_perspective.py b/test/augmentation/test_perspective.py
index d0919934e..607a6fe7b 100644
--- a/test/augmentation/test_perspective.py
+++ b/test/augmentation/test_perspective.py
@@ -155,6 +155,7 @@ class TestRandomAffine:
out = aug(x_data)
assert out.shape == x_data.shape
assert aug.inverse(out).shape == x_data.shape
+ assert aug.inverse(out, aug._params).shape == x_data.shape
def test_smoke_no_transform_batch(self, device):
x_data = torch.rand(2, 2, 8, 9).to(device)
@@ -162,6 +163,7 @@ class TestRandomAffine:
out = aug(x_data)
assert out.shape == x_data.shape
assert aug.inverse(out).shape == x_data.shape
+ assert aug.inverse(out, aug._params).shape == x_data.shape
@pytest.mark.parametrize("degrees", [45.0, (-45.0, 45.0), torch.tensor([45.0, 45.0])])
@pytest.mark.parametrize("translate", [(0.1, 0.1), torch.tensor([0.1, 0.1])])