π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
[Feat] Added AugmentationDispatcher (#1914)
Jian Shi9d9cee39b1d5
diff --git a/docs/source/augmentation.container.rst b/docs/source/augmentation.container.rstindex 228418aaa..5c43a8a19 100644--- a/docs/source/augmentation.container.rst+++ b/docs/source/augmentation.container.rst@@ -21,6 +21,23 @@ for automating the processing of masks, bounding boxes, and keypoints... automethod:: inverse+Augmentation Dispatchers+------------------------+Kornia supports two types of augmentation dispatching, namely many-to-many and many-to-one. The former wraps+different augmentations into one group and allows user to input multiple inputs in align with the number of+augmentations. The latter aims at performing different augmentations for one input that to obtain a list of+various transformed data.++.. autoclass:: ManyToManyAugmentationDispather++ .. automethod:: forward+++.. autoclass:: ManyToOneAugmentationDispather++ .. automethod:: forward++ImageSequential---------------diff --git a/kornia/augmentation/__init__.py b/kornia/augmentation/__init__.pyindex 22c50e4bc..ac9f8c480 100644--- a/kornia/augmentation/__init__.py+++ b/kornia/augmentation/__init__.py@@ -60,7 +60,14 @@ from kornia.augmentation._3d import (RandomVerticalFlip3D,)from kornia.augmentation._3d.base import AugmentationBase3D-from kornia.augmentation.container import AugmentationSequential, ImageSequential, PatchSequential, VideoSequential+from kornia.augmentation.container import (+ AugmentationSequential,+ ImageSequential,+ ManyToManyAugmentationDispather,+ ManyToOneAugmentationDispather,+ PatchSequential,+ VideoSequential,+)__all__ = ["AugmentationBase2D",@@ -120,6 +127,8 @@ __all__ = ["RandomEqualize3D","RandomMotionBlur3D","AugmentationSequential",+ "ManyToOneAugmentationDispather",+ "ManyToManyAugmentationDispather","ImageSequential","PatchSequential","VideoSequential",diff --git a/kornia/augmentation/container/__init__.py b/kornia/augmentation/container/__init__.pyindex cc31c01c7..a05780e08 100644--- a/kornia/augmentation/container/__init__.py+++ b/kornia/augmentation/container/__init__.py@@ -1,4 +1,5 @@from kornia.augmentation.container.augment import AugmentationSequential+from kornia.augmentation.container.dispatcher import ManyToManyAugmentationDispather, ManyToOneAugmentationDispatherfrom kornia.augmentation.container.image import ImageSequentialfrom kornia.augmentation.container.patch import PatchSequentialfrom kornia.augmentation.container.video import VideoSequentialdiff --git a/kornia/augmentation/container/dispatcher.py b/kornia/augmentation/container/dispatcher.pynew file mode 100644index 000000000..0cc70ebf8--- /dev/null+++ b/kornia/augmentation/container/dispatcher.py@@ -0,0 +1,96 @@+from typing import List, Tuple, Union++import torch.nn as nn+from torch import Tensor++from kornia.augmentation.container.augment import AugmentationSequential+++class ManyToManyAugmentationDispather(nn.Module):+ """Dispatches different augmentations to different inputs element-wisely.++ Args:+ augmentations: *args: a list of kornia AugmentationSequential modules.++ Examples:+ >>> import torch+ >>> input_1, input_2 = torch.randn(2, 3, 5, 6), torch.randn(2, 3, 5, 6)+ >>> mask_1, mask_2 = torch.ones(2, 3, 5, 6), torch.ones(2, 3, 5, 6)+ >>> aug_list = ManyToManyAugmentationDispather(+ ... AugmentationSequential(+ ... kornia.augmentation.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0),+ ... kornia.augmentation.RandomAffine(360, p=1.0),+ ... data_keys=["input", "mask",],+ ... ),+ ... AugmentationSequential(+ ... kornia.augmentation.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0),+ ... kornia.augmentation.RandomAffine(360, p=1.0),+ ... data_keys=["input", "mask",],+ ... )+ ... )+ >>> output = aug_list((input_1, mask_1), (input_2, mask_2))+ """++ def __init__(self, *augmentations: AugmentationSequential) -> None:+ super().__init__()+ self._check_consistency(*augmentations)+ self.augmentations = augmentations++ def _check_consistency(self, *augmentations: AugmentationSequential) -> bool:+ for i, aug in enumerate(augmentations):+ if not isinstance(aug, AugmentationSequential):+ raise ValueError(f"Please wrap your augmentations[`{i}`] with `AugmentationSequentials`.")+ return True++ def forward(self, *input: Union[List[Tensor], List[Tuple[Tensor]]]) -> Union[List[Tensor], List[Tuple[Tensor]]]:+ return [aug(*inp) for inp, aug in zip(input, self.augmentations)]+++class ManyToOneAugmentationDispather(nn.Module):+ """Dispatches different augmentations to a single input and returns a list.++ Same `datakeys` must be applied across different augmentations. By default, with input+ (image, mask), the augmentations must not mess it as (mask, image) to avoid unexpected+ errors. This check can be cancelled with `strict=False` if needed.++ Args:+ augmentations: *args: a list of kornia AugmentationSequential modules.++ Examples:+ >>> import torch+ >>> input = torch.randn(2, 3, 5, 6)+ >>> mask = torch.ones(2, 3, 5, 6)+ >>> aug_list = ManyToManyAugmentationDispather(+ ... AugmentationSequential(+ ... kornia.augmentation.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0),+ ... kornia.augmentation.RandomAffine(360, p=1.0),+ ... data_keys=["input", "mask",],+ ... ),+ ... AugmentationSequential(+ ... kornia.augmentation.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0),+ ... kornia.augmentation.RandomAffine(360, p=1.0),+ ... data_keys=["input", "mask",],+ ... )+ ... )+ >>> output = aug_list((input, mask))+ """++ def __init__(self, *augmentations: AugmentationSequential, strict: bool = True) -> None:+ super().__init__()+ self.strict = strict+ self._check_consistency(*augmentations)+ self.augmentations = augmentations++ def _check_consistency(self, *augmentations: AugmentationSequential) -> bool:+ for i, aug in enumerate(augmentations):+ if not isinstance(aug, AugmentationSequential):+ raise ValueError(f"Please wrap your augmentations[`{i}`] with `AugmentationSequentials`.")+ if self.strict and i != 0 and aug.data_keys != augmentations[i - 1].data_keys:+ raise RuntimeError(+ f"Different `data_keys` between {i - 1} and {i} elements, "+ f"got {aug.data_keys} and {augmentations[i - 1].data_keys}."+ )+ return True++ def forward(self, *input: Union[Tensor, Tuple[Tensor]]) -> Union[List[Tensor], List[Tuple[Tensor]]]:+ return [aug(*input) for aug in self.augmentations]diff --git a/test/augmentation/test_container.py b/test/augmentation/test_container.pyindex ed214275d..0a7e3c957 100644--- a/test/augmentation/test_container.py+++ b/test/augmentation/test_container.py@@ -665,3 +665,76 @@ class TestPatchSequential:grid_size=(2, 2),)assert seq.is_intensity_only()+++class TestDispatcher:+ def test_many_to_many(self, device, dtype):+ input_1 = torch.randn(2, 3, 5, 6, device=device, dtype=dtype)+ input_2 = torch.randn(2, 3, 5, 6, device=device, dtype=dtype)+ mask_1 = torch.ones(2, 1, 5, 6, device=device, dtype=dtype)+ mask_2 = torch.ones(2, 1, 5, 6, device=device, dtype=dtype)+ aug_list = K.ManyToManyAugmentationDispather(+ K.AugmentationSequential(+ kornia.augmentation.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0),+ kornia.augmentation.RandomAffine(360, p=1.0),+ data_keys=["input", "mask"],+ ),+ K.AugmentationSequential(+ kornia.augmentation.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0),+ kornia.augmentation.RandomAffine(360, p=1.0),+ data_keys=["input", "mask"],+ ),+ )+ output = aug_list((input_1, mask_1), (input_2, mask_2))++ assert output[0][0].shape == input_1.shape+ assert output[1][0].shape == input_2.shape+ assert output[0][1].shape == mask_1.shape+ assert output[1][1].shape == mask_2.shape++ @pytest.mark.parametrize('strict', [True, False])+ def test_many_to_one(self, strict, device, dtype):+ input = torch.randn(2, 3, 5, 6, device=device, dtype=dtype)+ mask = torch.ones(2, 1, 5, 6, device=device, dtype=dtype)+ aug_list = K.ManyToOneAugmentationDispather(+ K.AugmentationSequential(+ kornia.augmentation.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0),+ kornia.augmentation.RandomAffine(360, p=1.0),+ data_keys=["input", "mask"],+ ),+ K.AugmentationSequential(+ kornia.augmentation.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0),+ kornia.augmentation.RandomAffine(360, p=1.0),+ data_keys=["input", "mask"],+ ),+ strict=strict,+ )+ output = aug_list(input, mask)++ assert output[0][0].shape == input.shape+ assert output[1][0].shape == input.shape+ assert output[0][1].shape == mask.shape+ assert output[1][1].shape == mask.shape++ @pytest.mark.parametrize('strict', [True, False])+ def test_many_to_one_strict_mode(self, strict):+ def _init_many_to_one(strict):+ K.ManyToOneAugmentationDispather(+ K.AugmentationSequential(+ kornia.augmentation.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0),+ kornia.augmentation.RandomAffine(360, p=1.0),+ data_keys=["input"],+ ),+ K.AugmentationSequential(+ kornia.augmentation.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0),+ kornia.augmentation.RandomAffine(360, p=1.0),+ data_keys=["input", "mask"],+ ),+ strict=strict,+ )++ if strict:+ with pytest.raises(RuntimeError):+ _init_many_to_one(strict) # fails+ else:+ _init_many_to_one(strict) # passes