π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
[Feat] Enable ImageSequential and VideoSequential to AugmentationSequential (#1231)
Jian Shiea50bd664188
diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.pyindex c56f6a45d..9817c10b2 100644--- a/kornia/augmentation/container/augment.py+++ b/kornia/augmentation/container/augment.py@@ -1,6 +1,6 @@import warningsfrom itertools import zip_longest-from typing import cast, Dict, List, Optional, Tuple, Union+from typing import cast, List, Optional, Tuple, Unionimport torchimport torch.nn as nn@@ -11,13 +11,13 @@ from kornia.augmentation.base import (IntensityAugmentationBase2D,TensorWithTransformMat,)-from kornia.augmentation.container.base import SequentialBasefrom kornia.constants import DataKey-from kornia.geometry.bbox import transform_bbox-from kornia.geometry.linalg import transform_points+from .base import SequentialBasefrom .image import ImageSequential, ParamItemfrom .patch import PatchSequential+from .utils import ApplyInverse+from .video import VideoSequential__all__ = ["AugmentationSequential"]@@ -80,6 +80,28 @@ class AugmentationSequential(ImageSequential):>>> 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])]++ Examples:+ This example demonstrates the integration of VideoSequential and AugmentationSequential.+ >>> import kornia+ >>> input = torch.randn(2, 3, 5, 6)[None]+ >>> bbox = torch.tensor([[+ ... [1., 1.],+ ... [2., 1.],+ ... [2., 2.],+ ... [1., 2.],+ ... ]]).expand(2, -1, -1)[None]+ >>> points = torch.tensor([[[1., 1.]]]).expand(2, -1, -1)[None]+ >>> aug_list = AugmentationSequential(+ ... VideoSequential(+ ... 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"]+ ... )+ >>> out = aug_list(input, input, 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])]"""def __init__(@@ -107,129 +129,14 @@ class AugmentationSequential(ImageSequential):if self.data_keys[0] != DataKey.INPUT:raise NotImplementedError(f"The first input must be {DataKey.INPUT}.")+ self.contains_video_sequential: bool = Falsefor arg in args:if isinstance(arg, PatchSequential) and not arg.is_intensity_only():warnings.warn("Geometric transformation detected in PatchSeqeuntial, which would break bbox, mask.")+ if isinstance(arg, VideoSequential):+ self.contains_video_sequential = True- def apply_to_mask(self, input: torch.Tensor, module: nn.Module, param: Optional[ParamItem] = None) -> torch.Tensor:- if param is not None:- _param = cast(Dict[str, torch.Tensor], param.data)- else:- _param = None # type: ignore-- 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[ParamItem] = None, mode: str = "xyxy"- ) -> torch.Tensor:- if param is not None:- _param = cast(Dict[str, torch.Tensor], param.data)- else:- _param = None # type: ignore-- if isinstance(module, GeometricAugmentationBase2D) and _param is None:- raise ValueError(f"Transformation matrix for {module} has not been computed.")- if isinstance(module, GeometricAugmentationBase2D) and _param is not None:- input = transform_bbox(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[ParamItem] = None- ) -> torch.Tensor:- if param is not None:- _param = cast(Dict[str, torch.Tensor], param.data)- else:- _param = None # type: ignore-- if isinstance(module, GeometricAugmentationBase2D) and _param is None:- raise ValueError(f"Transformation matrix for {module} has not been computed.")- if 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: TensorWithTransformMat,- label: Optional[torch.Tensor],- module: Optional[nn.Module],- param: ParamItem,- dcate: Union[str, int, DataKey] = DataKey.INPUT,- ) -> Tuple[TensorWithTransformMat, Optional[torch.Tensor]]:- if module is None:- module = self.get_submodule(param.name)- if DataKey.get(dcate) in [DataKey.INPUT]:- return self.apply_to_input(input, label, module=module, param=param)- if DataKey.get(dcate) in [DataKey.MASK]:- if isinstance(input, (tuple,)):- return (self.apply_to_mask(input[0], module, param), *input[1:]), None- return self.apply_to_mask(input, module, param), None- 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:]), None- return self.apply_to_bbox(input, module, param, mode='xyxy'), None- 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:]), None- return self.apply_to_bbox(input, module, param, mode='xyhw'), None- if DataKey.get(dcate) in [DataKey.KEYPOINTS]:- if isinstance(input, (tuple,)):- return (self.apply_to_keypoints(input[0], module, param), *input[1:]), None- return self.apply_to_keypoints(input, module, param), None- raise NotImplementedError(f"input type of {dcate} is not implemented.")-- def inverse_input(self, input: torch.Tensor, module: nn.Module, param: Optional[ParamItem] = None) -> torch.Tensor:- if isinstance(module, GeometricAugmentationBase2D):- input = module.inverse(input, None if param is None else cast(Dict, param.data))- return input-- def inverse_bbox(- self, input: torch.Tensor, module: nn.Module, param: Optional[ParamItem] = None, mode: str = "xyxy"- ) -> torch.Tensor:- if isinstance(module, GeometricAugmentationBase2D):- transform = module.compute_inverse_transformation(- module.get_transformation_matrix(input, None if param is None else cast(Dict, param.data))- )- input = transform_bbox(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[ParamItem] = None- ) -> torch.Tensor:- if isinstance(module, GeometricAugmentationBase2D):- transform = module.compute_inverse_transformation(- module.get_transformation_matrix(input, None if param is None else cast(Dict, param.data))- )- 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[ParamItem] = 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(+ def inverse( # type: ignoreself,*args: torch.Tensor,params: Optional[List[ParamItem]] = None,@@ -260,19 +167,25 @@ class AugmentationSequential(ImageSequential):if dcate == DataKey.INPUT and isinstance(input, (tuple, list)):input, _ = input # ignore the transformation matrix whilst inversefor (name, module), param in zip_longest(list(self.get_forward_sequence(params))[::-1], params[::-1]):- if isinstance(module, _AugmentationBase):+ if isinstance(module, (_AugmentationBase, ImageSequential)):param = params[name] if name in params else paramelse: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:+ if isinstance(module, IntensityAugmentationBase2D) and dcate in DataKey:pass # Do nothing- elif isinstance(module, PatchSequential) and module.is_intensity_only() and dcate in DataKey:+ 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)+ input = input.view(batch_size, -1, *input.shape[1:])+ elif isinstance(module, PatchSequential):+ raise NotImplementedError("Geometric involved PatchSequential is not supported.")+ elif isinstance(module, (GeometricAugmentationBase2D, ImageSequential)) and dcate in DataKey:+ input = ApplyInverse.inverse_by_key(input, module, param, dcate)elif isinstance(module, (SequentialBase,)):- raise ValueError("Sequential is currently unsupported.")+ raise ValueError(f"Unsupported Sequential {module}.")else:raise NotImplementedError(f"data_key {dcate} is not implemented for {module}.")outputs.append(input)@@ -328,9 +241,11 @@ class AugmentationSequential(ImageSequential):inp = _input[0]else:inp = _input- _, out_shape = self.autofill_dim(inp, dim_range=(2, 4))- if params is None:- params = self.forward_parameters(out_shape)+ if self.contains_video_sequential:+ _, out_shape = self.autofill_dim(inp, dim_range=(3, 5))+ else:+ _, out_shape = self.autofill_dim(inp, dim_range=(2, 4))+ params = self.forward_parameters(out_shape)else:raise ValueError("`params` must be provided whilst INPUT is not in data_keys.")@@ -353,14 +268,21 @@ class AugmentationSequential(ImageSequential):module = self.get_submodule(param.name)if dcate == DataKey.INPUT:input, label = self.apply_to_input(input, label, module=module, param=param)- elif isinstance(module, GeometricAugmentationBase2D) and dcate in DataKey:- input, label = self.apply_by_key(input, label, module, param, dcate)elif isinstance(module, IntensityAugmentationBase2D) and dcate in DataKey:pass # Do nothing- elif isinstance(module, PatchSequential) and module.is_intensity_only() and dcate in DataKey:+ 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)+ input = input.view(batch_size, -1, *input.shape[1:])+ elif isinstance(module, PatchSequential):+ raise NotImplementedError("Geometric involved PatchSequential is not supported.")+ elif isinstance(module, (GeometricAugmentationBase2D, ImageSequential,)) and dcate in DataKey:+ input, label = ApplyInverse.apply_by_key(input, label, module, param, dcate)elif isinstance(module, (SequentialBase,)):- raise ValueError("Sequential is currently unsupported.")+ raise ValueError(f"Unsupported Sequential {module}.")else:raise NotImplementedError(f"data_key {dcate} is not implemented for {module}.")outputs[idx] = inputdiff --git a/kornia/augmentation/container/base.py b/kornia/augmentation/container/base.pyindex c06915a4a..4fa05c770 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, Iterator, List, NamedTuple, Optional, Tuple, Union+from typing import Any, Dict, Iterator, List, NamedTuple, Optional, Tuple, Unionimport torchimport torch.nn as nn@@ -44,7 +44,7 @@ class SequentialBase(nn.Sequential):self._same_on_batch = same_on_batchself._return_transform = return_transformself._keepdim = keepdim- self._params: Optional[List[Any]] = None+ self._params: Optional[List[ParamItem]] = Noneself.update_attribute(same_on_batch, return_transform, keepdim)def update_attribute(@@ -63,6 +63,8 @@ class SequentialBase(nn.Sequential):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)def get_submodule(self, target: str) -> nn.Module:"""Get submodule.@@ -149,6 +151,7 @@ class SequentialBase(nn.Sequential):def get_children_by_params(self, params: List[ParamItem]) -> Iterator[Tuple[str, nn.Module]]:modules = list(self.named_children())+ # TODO: Wrong params passed here when nested ImageSequentialfor param in params:yield modules[list(dict(self.named_children()).keys()).index(param.name)]diff --git a/kornia/augmentation/container/image.py b/kornia/augmentation/container/image.pyindex 99841d800..24f1ef7c6 100644--- a/kornia/augmentation/container/image.py+++ b/kornia/augmentation/container/image.py@@ -1,16 +1,24 @@-from typing import Iterator, List, Optional, Tuple, Union+from itertools import zip_longest+from typing import Any, Iterator, List, Optional, Tuple, Type, Unionimport torchimport torch.nn as nn-from kornia.augmentation.base import _AugmentationBase, MixAugmentationBase, TensorWithTransformMat+import kornia+from kornia.augmentation.base import (+ _AugmentationBase,+ GeometricAugmentationBase2D,+ IntensityAugmentationBase2D,+ MixAugmentationBase,+ TensorWithTransformMat,+)from .base import ParamItem, SequentialBase+from .utils import ApplyInverseInterface, InputApplyInverse__all__ = ["ImageSequential"]-# TODO: Add forward_parameters for ImageSequentialclass ImageSequential(SequentialBase):r"""Sequential for creating kornia image processing pipeline.@@ -69,15 +77,19 @@ class ImageSequential(SequentialBase):return_transform: Optional[bool] = None,keepdim: Optional[bool] = None,random_apply: Union[int, bool, Tuple[int, int]] = False,+ if_unsupported_ops: str = 'raise') -> None:super().__init__(*args, same_on_batch=same_on_batch, return_transform=return_transform, keepdim=keepdim)self.random_apply: Union[Tuple[int, int], bool] = self._read_random_apply(random_apply, len(args))self.return_label: Optional[bool] = None+ self.apply_inverse_func: Type[ApplyInverseInterface] = InputApplyInverse+ self.if_unsupported_ops = if_unsupported_opsdef _read_random_apply(self, random_apply: Union[int, bool, Tuple[int, int]], max_length: int) -> Union[Tuple[int, int], bool]:+ """Process the scenarios for random apply."""if isinstance(random_apply, (bool,)) and random_apply is False:random_apply = Falseelif isinstance(random_apply, (bool,)) and random_apply is True:@@ -105,6 +117,11 @@ class ImageSequential(SequentialBase):return random_applydef get_random_forward_sequence(self, with_mix: bool = True) -> Tuple[Iterator[Tuple[str, nn.Module]], bool]:+ """Get a forward sequence when random apply is in need.++ Note:+ Mix augmentations (e.g. RandomMixUp) will be only applied once even in a random forward.+ """num_samples = int(torch.randint(*self.random_apply, (1,)).item()) # type: ignoremultinomial_weights = torch.ones((len(self),))# Mix augmentation can only be applied once per forward@@ -129,6 +146,10 @@ class ImageSequential(SequentialBase):return self.get_children_by_indices(indices), mix_addeddef get_mix_augmentation_indices(self, named_modules: Iterator[Tuple[str, nn.Module]]) -> List[int]:+ """Get all the mix augmentations since they are label-involved.++ Special operations needed for label-involved augmentations.+ """indices = []for idx, (_, child) in enumerate(named_modules):if isinstance(child, (MixAugmentationBase,)):@@ -162,40 +183,27 @@ class ImageSequential(SequentialBase):) -> Tuple[TensorWithTransformMat, Optional[torch.Tensor]]:if module is None:module = self.get_submodule(param.name)- if isinstance(module, (MixAugmentationBase,)):- input, label = module(input, label, params=param.data)- elif isinstance(module, (ImageSequential,)):- out = module(input, label, params=param.data)- if module.return_label:- input, label = out- else:- input = out- elif isinstance(module, (_AugmentationBase,)):- input = module(input, params=param.data)- 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+ return self.apply_inverse_func.apply_trans(input, label, module, param) # type: ignoredef forward_parameters(self, batch_shape: torch.Size) -> List[ParamItem]:- named_modules = self.get_forward_sequence()+ named_modules: Iterator[Tuple[str, nn.Module]] = self.get_forward_sequence()- params = []+ params: List[ParamItem] = []+ mod_param: Union[dict, list]for name, module in named_modules:if isinstance(module, (_AugmentationBase, MixAugmentationBase)):mod_param = module.forward_parameters(batch_shape)param = ParamItem(name, mod_param)+ elif isinstance(module, ImageSequential):+ mod_param = module.forward_parameters(batch_shape)+ param = ParamItem(name, mod_param)else:param = ParamItem(name, None)params.append(param)return paramsdef 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@@ -209,6 +217,85 @@ class ImageSequential(SequentialBase):# Implicitly indicating the label cannot be optional since there is a mix augreturn output+ def get_transformation_matrix(+ self, input: torch.Tensor, params: Optional[List[ParamItem]] = None,+ ) -> torch.Tensor:+ """Compute the transformation matrix according to the provided parameters."""+ if params is None:+ raise NotImplementedError("requires params to be provided.")+ named_modules: Iterator[Tuple[str, nn.Module]] = self.get_forward_sequence(params)++ res_mat: torch.Tensor = kornia.eye_like(3, input)+ for (_, module), param in zip(named_modules, params):+ if isinstance(module, (_AugmentationBase, MixAugmentationBase)):+ mat = module.compute_transformation(input, param.data) # type: ignore+ res_mat = mat @ res_mat+ elif isinstance(module, (ImageSequential,)):+ mat = module.get_transformation_matrix(input, param.data) # type: ignore+ res_mat = mat @ res_mat+ return res_mat++ def is_intensity_only(self, strict: bool = True) -> bool:+ """Check if all transformations are intensity-based.++ Args:+ strict: if strict is False, it will allow non-augmentation nn.Modules to be passed.+ e.g. `kornia.enhance.AdjustBrightness` will be recognized as non-intensity module+ if strict is set to True.++ Note: patch processing would break the continuity of labels (e.g. bbounding boxes, masks).+ """+ for arg in self.children():+ if isinstance(arg, (ImageSequential,)) and not arg.is_intensity_only(strict):+ return False+ elif isinstance(arg, (ImageSequential,)):+ pass+ elif isinstance(arg, IntensityAugmentationBase2D):+ pass+ elif strict:+ # disallow non-registered ops if in strict mode+ # TODO: add an ops register module+ return False+ return True++ def inverse(+ self,+ input: torch.Tensor,+ params: Optional[List[ParamItem]] = None,+ ) -> torch.Tensor:+ """Inverse transformation.++ Used to inverse a tensor according to the performed transformation by a forward pass, or with respect to+ provided parameters.+ """+ if params is None:+ if self._params is None:+ raise ValueError(+ "No parameters available for inversing, please run a forward pass first "+ "or passing valid params into this function."+ )+ params = self._params++ for (name, module), param in zip_longest(list(self.get_forward_sequence(params))[::-1], params[::-1]):+ if isinstance(module, (_AugmentationBase, ImageSequential)):+ param = params[name] if name in params else param+ else:+ param = None++ if isinstance(module, IntensityAugmentationBase2D):+ pass # Do nothing+ elif isinstance(module, ImageSequential) and module.is_intensity_only():+ pass # Do nothing+ elif isinstance(module, ImageSequential):+ input = module.inverse(input, param.data)+ elif isinstance(module, (GeometricAugmentationBase2D,)):+ input = self.apply_inverse_func.inverse(input, module, param)+ else:+ pass+ # raise NotImplementedError(f"`inverse` is not implemented for {module}.")++ return input+def forward( # type: ignoreself,input: TensorWithTransformMat,@@ -223,7 +310,8 @@ class ImageSequential(SequentialBase):inp = input_, out_shape = self.autofill_dim(inp, dim_range=(2, 4))params = self.forward_parameters(out_shape)- self.return_label = label is not None or self.contains_label_operations(params)+ 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) # type: ignorediff --git a/kornia/augmentation/container/patch.py b/kornia/augmentation/container/patch.pyindex 084411332..5e7f54bda 100644--- a/kornia/augmentation/container/patch.py+++ b/kornia/augmentation/container/patch.py@@ -4,12 +4,7 @@ from typing import Iterator, List, NamedTuple, Optional, Tuple, Unionimport torchimport torch.nn as nn-from kornia.augmentation.base import (- _AugmentationBase,- IntensityAugmentationBase2D,- MixAugmentationBase,- TensorWithTransformMat,-)+from kornia.augmentation.base import _AugmentationBase, MixAugmentationBase, TensorWithTransformMatfrom kornia.augmentation.container.base import SequentialBasefrom kornia.contrib.extract_patches import extract_tensor_patches@@ -129,20 +124,6 @@ class PatchSequential(ImageSequential):self.padding = paddingself.patchwise_apply = patchwise_apply- def is_intensity_only(self) -> bool:- """Check if all transformations are intensity-based.-- Note: patch processing would break the continuity of labels (e.g. bbounding boxes, masks).- """- for arg in self.children():- if isinstance(arg, (ImageSequential,)):- for _arg in arg.children():- if not isinstance(_arg, IntensityAugmentationBase2D):- return False- elif not isinstance(_arg, IntensityAugmentationBase2D):- return False- return True-def contains_label_operations(self, params: List[PatchParamItem]) -> bool: # type: ignorefor param in params:if param.param.name.startswith("RandomMixUp") or param.param.name.startswith("RandomCutMix"):@@ -378,6 +359,21 @@ class PatchSequential(ImageSequential):_input = _input.reshape(in_shape)return _input, label+ def inverse( # type: ignore+ self,+ input: torch.Tensor,+ params: List[ParamItem],+ ) -> torch.Tensor:+ """Inverse transformation.++ Used to inverse a tensor according to the performed transformation by a forward pass, or with respect to+ provided parameters.+ """+ if self.is_intensity_only():+ return input++ raise NotImplementedError("PatchSequential inverse cannot be used with geometric transformations.")+def forward( # type: ignoreself, input: torch.Tensor, label: Optional[torch.Tensor] = None, params: Optional[List[PatchParamItem]] = None) -> Union[TensorWithTransformMat, Tuple[TensorWithTransformMat, torch.Tensor]]:diff --git a/kornia/augmentation/container/utils.py b/kornia/augmentation/container/utils.pynew file mode 100644index 000000000..7206e5919--- /dev/null+++ b/kornia/augmentation/container/utils.py@@ -0,0 +1,368 @@+from abc import ABCMeta, abstractmethod+from functools import partial+from typing import Callable, cast, Dict, Iterator, List, Optional, Tuple, Type, Union++import torch+import torch.nn as nn++import kornia # lazy loading for circular dependencies+from kornia.augmentation.base import (+ _AugmentationBase,+ GeometricAugmentationBase2D,+ MixAugmentationBase,+ TensorWithTransformMat,+)+from kornia.constants import DataKey+from kornia.geometry.bbox import transform_bbox+from kornia.geometry.linalg import transform_points+from kornia.utils.helpers import _torch_inverse_cast++from .base import ParamItem+++def _get_geometric_only_param(+ module: "kornia.augmentation.container.ImageSequential", param: List[ParamItem]+) -> List[ParamItem]:+ named_modules: Iterator[Tuple[str, nn.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: torch.Tensor,+ label: Optional[torch.Tensor],+ module: nn.Module,+ param: ParamItem,+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:+ """Apply a transformation with respect to the parameters.++ 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: torch.Tensor,+ module: nn.Module,+ param: Optional[ParamItem] = None+ ) -> torch.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++ @classmethod+ def apply_trans(+ cls, input: torch.Tensor, label: Optional[torch.Tensor], module: nn.Module, param: ParamItem+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:+ """Apply a transformation with respect to the parameters.++ 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[torch.Tensor] = cls._get_transformation(input, module, param)++ if mat is not None:+ input = cls.apply_func(mat, input)++ return input, label++ @classmethod+ def inverse(+ cls, input: torch.Tensor, module: nn.Module, param: Optional[ParamItem] = None+ ) -> torch.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[torch.Tensor] = cls._get_transformation(input, module, param)++ if mat is not None:+ transform: torch.Tensor = cls._get_inverse_transformation(mat)+ input = cls.apply_func(torch.as_tensor(transform, device=input.device, dtype=input.dtype), input)+ return input++ @classmethod+ def _get_transformation(+ cls, input: torch.Tensor, module: nn.Module, param: Optional[ParamItem] = None+ ) -> Optional[torch.Tensor]:++ if isinstance(module, (+ GeometricAugmentationBase2D,+ kornia.augmentation.container.ImageSequential,+ )) and param is None:+ raise ValueError(f"Parameters of transformation matrix for {module} has not been computed.")++ if isinstance(module, GeometricAugmentationBase2D):+ _param = cast(Dict[str, torch.Tensor], param.data) # type: ignore+ mat = module.get_transformation_matrix(input, _param)+ elif isinstance(module, kornia.augmentation.container.ImageSequential) and not module.is_intensity_only():+ _param = cast(List[ParamItem], param.data) # type: ignore+ mat = module.get_transformation_matrix(input, _param) # type: ignore+ else:+ return None # No need to update anything+ return mat++ @classmethod+ def _get_inverse_transformation(cls, transform: torch.Tensor) -> torch.Tensor:+ return _torch_inverse_cast(transform)+++class InputApplyInverse(ApplyInverseImpl):+ """Apply and inverse transformations for (image) input tensors."""++ @classmethod+ def apply_trans( # type: ignore+ cls,+ input: TensorWithTransformMat,+ label: Optional[torch.Tensor],+ module: nn.Module,+ param: ParamItem,+ ) -> Tuple[TensorWithTransformMat, Optional[torch.Tensor]]:+ """Apply a transformation with respect to the parameters.++ 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, (MixAugmentationBase,)):+ input, label = module(input, label, params=param.data)+ elif isinstance(module, (_AugmentationBase,)):+ input = module(input, params=param.data)+ elif isinstance(module, kornia.augmentation.container.ImageSequential):+ temp = module.apply_inverse_func+ temp2 = module.return_label+ module.apply_inverse_func = InputApplyInverse+ module.return_label = True+ input, label = module(input, label, param.data)+ 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: torch.Tensor, module: nn.Module, param: Optional[ParamItem] = None) -> torch.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):+ input = module.inverse(input, None if param is None else cast(Dict, param.data))+ elif isinstance(module, kornia.augmentation.container.ImageSequential):+ temp = module.apply_inverse_func+ module.apply_inverse_func = InputApplyInverse+ input = module.inverse(input, None if param is None else cast(List, param.data))+ module.apply_inverse_func = temp+ return input+++class MaskApplyInverse(ApplyInverseImpl):+ """Apply and inverse transformations for mask tensors."""++ @classmethod+ def make_input_only_sequential(cls, module: "kornia.augmentation.container.ImageSequential") -> Callable:+ """Disable all other additional inputs (e.g. ) for ImageSequential."""+ def f(*args, **kwargs):+ if_return_trans = module.return_transform+ if_return_label = module.return_label+ module.return_transform = False+ module.return_label = False+ out = module(*args, **kwargs)+ module.return_transform = if_return_trans+ module.return_label = if_return_label+ return out+ return f++ @classmethod+ def apply_trans(+ cls, input: torch.Tensor, label: Optional[torch.Tensor], module: nn.Module, param: Optional[ParamItem] = None+ ) -> Tuple[torch.Tensor, Optional[torch.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 param is not None:+ _param = param.data+ else:+ _param = None # type: ignore++ if isinstance(module, GeometricAugmentationBase2D):+ _param = cast(Dict[str, torch.Tensor], _param)+ input = module(input, _param, return_transform=False)+ elif isinstance(module, kornia.augmentation.container.ImageSequential) and not module.is_intensity_only():+ _param = cast(List[ParamItem], _param)+ temp = module.apply_inverse_func+ module.apply_inverse_func = MaskApplyInverse+ geo_param: List[ParamItem] = _get_geometric_only_param(module, _param)+ input = cls.make_input_only_sequential(module)(input, None, geo_param)+ module.apply_inverse_func = temp+ else:+ pass # No need to update anything+ return input, label++ @classmethod+ def inverse(+ cls, input: torch.Tensor, module: nn.Module, param: Optional[ParamItem] = None+ ) -> torch.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):+ input = module.inverse(input, None if param is None else cast(Dict, param.data))+ elif isinstance(module, kornia.augmentation.container.ImageSequential):+ temp = module.apply_inverse_func+ module.apply_inverse_func = MaskApplyInverse+ input = module.inverse(input, None if param is None else cast(List, param.data))+ module.apply_inverse_func = temp+ return input+++class BBoxXYXYApplyInverse(ApplyInverseImpl):+ """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")+++class BBoxXYWHApplyInverse(ApplyInverseImpl):+ """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")+++class KeypointsApplyInverse(ApplyInverseImpl):+ """Apply and inverse transformations for keypoints tensors."""++ apply_func = transform_points+++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) in [DataKey.MASK]:+ return MaskApplyInverse+ if DataKey.get(dcate) in [DataKey.BBOX, DataKey.BBOX_XYXY]:+ return BBoxXYXYApplyInverse+ if DataKey.get(dcate) in [DataKey.BBOX_XYHW]:+ return BBoxXYWHApplyInverse+ 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: TensorWithTransformMat,+ label: Optional[torch.Tensor],+ module: nn.Module,+ param: ParamItem,+ dcate: Union[str, int, DataKey] = DataKey.INPUT,+ ) -> Tuple[TensorWithTransformMat, Optional[torch.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), *input[1:]) # type: ignore+ return func.apply_trans(input, label, module=module, param=param)++ @classmethod+ def inverse_by_key(+ cls,+ input: torch.Tensor,+ module: nn.Module,+ param: Optional[ParamItem] = None,+ dcate: Union[str, int, DataKey] = DataKey.INPUT,+ ) -> torch.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)diff --git a/kornia/augmentation/container/video.py b/kornia/augmentation/container/video.pyindex ed32b9ac6..3e689e034 100644--- a/kornia/augmentation/container/video.py+++ b/kornia/augmentation/container/video.py@@ -6,6 +6,7 @@ import torch.nn as nnimport korniafrom kornia.augmentation.base import _AugmentationBase, MixAugmentationBase, TensorWithTransformMatfrom kornia.augmentation.container.base import SequentialBase+from kornia.augmentation.container.utils import InputApplyInverse, MaskApplyInversefrom .image import ImageSequential, ParamItem@@ -176,6 +177,27 @@ class VideoSequential(ImageSequential):params.append(param)return params+ def inverse(self, input: torch.Tensor, params: Optional[List[ParamItem]] = None) -> torch.Tensor:+ """Inverse transformation.++ Used to inverse a tensor according to the performed transformation by a forward pass, or with respect to+ 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:])++ input = super().inverse(input, params)+ 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+def forward( # type: ignoreself, input: torch.Tensor, label: Optional[torch.Tensor] = None, params: Optional[List[ParamItem]] = None) -> Union[TensorWithTransformMat, Tuple[TensorWithTransformMat, torch.Tensor]]:@@ -187,8 +209,14 @@ class VideoSequential(ImageSequential):params = self.forward_parameters(input.shape)# Size of T- frame_num = input.size(self._temporal_channel)- input, label = self._input_shape_convert_in(input, label, frame_num)+ 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) # type: ignoreif self.return_label:@@ -197,9 +225,19 @@ class VideoSequential(ImageSequential):output = cast(TensorWithTransformMat, out)if isinstance(output, (tuple, list)):- _out, label = self._input_shape_convert_back(output[0], label, frame_num)- output = (_out, output[1])+ 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:- output, label = self._input_shape_convert_back(output, label, frame_num)+ 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:])return self.__packup_output__(output, label)diff --git a/kornia/geometry/linalg.py b/kornia/geometry/linalg.pyindex 79e01f72e..e34853df3 100644--- a/kornia/geometry/linalg.py+++ b/kornia/geometry/linalg.py@@ -176,9 +176,15 @@ def transform_points(trans_01: torch.Tensor, points_1: torch.Tensor) -> torch.Techeck_is_tensor(trans_01)check_is_tensor(points_1)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")+ raise ValueError(+ "Input batch size must be the same for both tensors or 1."+ f"Got {trans_01.shape} and {points_1.shape}"+ )if not trans_01.shape[-1] == (points_1.shape[-1] + 1):- raise ValueError("Last input dimensions must differ by one unit")+ raise ValueError(+ "Last input dimensions must differ by one unit"+ f"Got{trans_01} and {points_1}"+ )# We reshape to BxNxD in case we get more dimensions, e.g., MxBxNxDshape_inp = list(points_1.shape)diff --git a/test/augmentation/test_container.py b/test/augmentation/test_container.pyindex 7d1d965a7..a6b1134b7 100644--- a/test/augmentation/test_container.py+++ b/test/augmentation/test_container.py@@ -150,6 +150,11 @@ class TestVideoSequential:class TestSequential:+ def test_exception(self, device, dtype):+ inp = torch.randn(1, 3, 30, 30, device=device, dtype=dtype)+ with pytest.raises(Exception): # AssertError and NotImplementedError+ K.ImageSequential(K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0)).inverse(inp)+@pytest.mark.parametrize('same_on_batch', [True, False, None])@pytest.mark.parametrize("return_transform", [True, False, None])@pytest.mark.parametrize("keepdim", [True, False, None])@@ -186,6 +191,12 @@ class TestSequential: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.ImageSequential(+ K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0)+ ),+ K.ImageSequential(+ K.RandomAffine(360, p=1.0)+ ),K.RandomAffine(360, p=1.0),K.RandomMixUp(p=1.0),return_transform=return_transform,@@ -198,6 +209,7 @@ class TestSequential:assert out[0].shape == inp.shapeelse:assert out.shape == inp.shape+ aug.inverse(inp)reproducibility_test(inp, aug)@@ -217,6 +229,10 @@ class TestAugmentationSequential:def test_mixup(self, inp, return_transform, random_apply, same_on_batch, device, dtype):inp = torch.as_tensor(inp, device=device, dtype=dtype)aug = K.AugmentationSequential(+ K.ImageSequential(+ K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0),+ K.RandomAffine(360, p=1.0, return_transform=True),+ ),K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0),K.RandomAffine(360, p=1.0),K.RandomMixUp(p=1.0),@@ -233,6 +249,34 @@ class TestAugmentationSequential:assert out.shape[-3:] == inp.shape[-3:]reproducibility_test(inp, aug)+ def test_video(self, device, dtype):+ input = torch.randn(2, 3, 5, 6, device=device, dtype=dtype)[None]+ bbox = torch.tensor([[+ [1., 1.],+ [2., 1.],+ [2., 2.],+ [1., 2.],+ ]], device=device, dtype=dtype).expand(2, -1, -1)[None]+ points = torch.tensor([[[1., 1.]]], device=device, dtype=dtype).expand(2, -1, -1)[None]+ aug_list = K.AugmentationSequential(+ K.VideoSequential(+ 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"]+ )+ out = aug_list(input, input, bbox, points)+ assert out[0].shape == input.shape+ assert out[1].shape == input.shape+ assert out[2].shape == bbox.shape+ assert out[3].shape == points.shape++ out_inv = aug_list.inverse(*out)+ assert out_inv[0].shape == input.shape+ assert out_inv[1].shape == input.shape+ assert out_inv[2].shape == bbox.shape+ assert out_inv[3].shape == points.shape+def test_random_flips(self, device, dtype):inp = torch.randn(1, 3, 510, 1020, device=device, dtype=dtype)bbox = torch.tensor([[[355, 10], [660, 10], [660, 250], [355, 250]]], device=device, dtype=dtype)@@ -268,6 +312,10 @@ class TestAugmentationSequential:torch.tensor([[[155, 0], [900, 0], [900, 400], [155, 400]]], device=device, dtype=dtype), 1000, 500)[:, None].float()aug = K.AugmentationSequential(+ K.ImageSequential(+ K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0),+ K.RandomAffine(360, p=1.0, return_transform=True),+ ),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"],@@ -299,7 +347,12 @@ class TestAugmentationSequential:)[:, None].float()aug = K.AugmentationSequential(- K.RandomAffine(360, p=1.0, return_transform=False), data_keys=['input', 'mask', 'bbox', 'keypoints']+ K.ImageSequential(+ K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0),+ K.RandomAffine(360, p=1.0, return_transform=True),+ ),+ K.RandomAffine(360, p=1.0, return_transform=False),+ data_keys=['input', 'mask', 'bbox', 'keypoints'])reproducibility_test((inp, mask, bbox, keypoints), aug)@@ -323,6 +376,10 @@ class TestAugmentationSequential:torch.tensor([[[155, 0], [900, 0], [900, 400], [155, 400]]], device=device, dtype=dtype), 1000, 500)[:, None].float()aug = K.AugmentationSequential(+ K.ImageSequential(+ K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0),+ K.RandomAffine(360, p=1.0, return_transform=True),+ ),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"],@@ -351,6 +408,10 @@ class TestAugmentationSequential:torch.tensor([[[155, 0], [900, 0], [900, 400], [155, 400]]], device=device, dtype=dtype), 1000, 500)[:, None].float()aug = K.AugmentationSequential(+ K.ImageSequential(+ K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0),+ K.RandomAffine(360, p=1.0, return_transform=True),+ ),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"],