🐍 Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Fix AugmentationSequential to return list of boxes (#2114)
João Gustavo A. Amorim58a6a4725229
diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.pyindex 430c3ec81..e0d28756b 100644--- a/kornia/augmentation/container/augment.py+++ b/kornia/augmentation/container/augment.py@@ -18,6 +18,7 @@ from kornia.augmentation.container.video import VideoSequentialfrom kornia.constants import DataKey, Resamplefrom kornia.core import Tensorfrom kornia.geometry.boxes import Boxes+from kornia.testing import KORNIA_CHECK_IS_LIST_OF_TENSORfrom kornia.utils import eye_like__all__ = ["AugmentationSequential"]@@ -193,7 +194,7 @@ class AugmentationSequential(ImageSequential):*args: Tensor,params: Optional[List[ParamItem]] = None,data_keys: Optional[List[Union[str, int, DataKey]]] = None,- ) -> Union[Tensor, List[Tensor]]:+ ) -> Union[Tensor, List[Tensor], List[Union[Tensor, List[Tensor]]]]:"""Reverse the transformation applied.Number of input tensors must align with the number of``data_keys``. If ``data_keys`` is not set, use@@ -276,7 +277,7 @@ class AugmentationSequential(ImageSequential):else:outputs[idx] = input- _outputs = [i for i in outputs if isinstance(i, Tensor)]+ _outputs = [i for i in outputs if isinstance(i, Tensor) or KORNIA_CHECK_IS_LIST_OF_TENSOR(i)]if len(_outputs) == 1 and isinstance(_outputs, list):return _outputs[0]@@ -284,10 +285,15 @@ class AugmentationSequential(ImageSequential):return _outputsdef __packup_output__( # type: ignore[override]- self, output: List[Tensor], label: Optional[Tensor] = None- ) -> Union[Tensor, List[Tensor], Tuple[Union[Tensor, List[Tensor]], Optional[Tensor]]]:+ self, output: List[Union[Tensor, List[Tensor]]], label: Optional[Tensor] = None+ ) -> Union[+ Tensor,+ List[Tensor],+ List[Union[Tensor, List[Tensor]]],+ Tuple[Union[Tensor, List[Tensor], List[Union[Tensor, List[Tensor]]]], Optional[Tensor]],+ ]:- _out: Union[Tensor, List[Tensor]]+ _out: Union[Tensor, List[Tensor], List[Union[Tensor, List[Tensor]]]]if len(output) == 1 and isinstance(output, list):_out = output[0]@@ -331,7 +337,12 @@ class AugmentationSequential(ImageSequential):label: Optional[Tensor] = None,params: Optional[List[ParamItem]] = None,data_keys: Optional[List[Union[str, int, DataKey]]] = None,- ) -> Union[Tensor, List[Tensor], Tuple[Union[Tensor, List[Tensor]], Optional[Tensor]]]:+ ) -> Union[+ Tensor,+ List[Tensor],+ List[Union[Tensor, List[Tensor]]],+ Tuple[Union[Tensor, List[Tensor], List[Union[Tensor, List[Tensor]]]], Optional[Tensor]],+ ]:"""Compute multiple tensors simultaneously according to ``self.data_keys``."""if data_keys is None:_data_keys = self.data_keys@@ -425,5 +436,6 @@ class AugmentationSequential(ImageSequential):outputs[idx] = arg.to_tensor()else:outputs[idx] = input- _outputs = [i for i in outputs if isinstance(i, Tensor)]+ _outputs = [i for i in outputs if isinstance(i, Tensor) or KORNIA_CHECK_IS_LIST_OF_TENSOR(i)]+return self.__packup_output__(_outputs, label)diff --git a/kornia/testing/__init__.py b/kornia/testing/__init__.pyindex 4092fe745..348bbc6a8 100644--- a/kornia/testing/__init__.py+++ b/kornia/testing/__init__.py@@ -4,10 +4,11 @@ import mathfrom abc import ABC, abstractmethodfrom copy import deepcopyfrom itertools import product-from typing import Any, Dict, List, Optional, Tuple, TypeVar, cast+from typing import Any, Dict, List, Optional, Sequence, Tuple, TypeVar, castimport torchfrom torch.testing import assert_close as _assert_close+from typing_extensions import TypeGuardfrom kornia.core import Tensor, eye, tensor@@ -21,6 +22,7 @@ __all__ = ["KORNIA_UNWRAP","KORNIA_CHECK_TYPE","KORNIA_CHECK_IS_TENSOR",+ "KORNIA_CHECK_IS_LIST_OF_TENSOR","KORNIA_CHECK_SAME_DEVICE","KORNIA_CHECK_SAME_DEVICES","KORNIA_CHECK_IS_COLOR",@@ -396,6 +398,25 @@ def KORNIA_CHECK_IS_TENSOR(x, msg: Optional[str] = None):raise TypeError(f"Not a Tensor type. Got: {type(x)}.\n{msg}")+def KORNIA_CHECK_IS_LIST_OF_TENSOR(x: Optional[Sequence[object]]) -> TypeGuard[List[Tensor]]:+ """Check the input variable is a List of Tensors.++ Args:+ x: Any sequence of objects++ Return:+ True if the input is a list of Tensors, otherwise return False.++ Example:+ >>> x = torch.rand(2, 3, 3)+ >>> KORNIA_CHECK_IS_LIST_OF_TENSOR(x)+ False+ >>> KORNIA_CHECK_IS_LIST_OF_TENSOR([x])+ True+ """+ return isinstance(x, list) and all(isinstance(d, Tensor) for d in x)++def KORNIA_CHECK_SAME_DEVICE(x: Tensor, y: Tensor):"""Check whether two tensor in the same device.diff --git a/test/augmentation/test_container.py b/test/augmentation/test_container.pyindex ce3e535c6..4fa1565b9 100644--- a/test/augmentation/test_container.py+++ b/test/augmentation/test_container.py@@ -426,6 +426,27 @@ class TestAugmentationSequential:assert out_inv[3].shape == points.shapeassert_close(out_inv[3], points, atol=1e-4, rtol=1e-4)+ def test_bbox(self, device, dtype):+ img = torch.rand((3, 3, 10, 10), device=device, dtype=dtype)+ bbox = [+ torch.tensor([[1, 5, 2, 7], [0, 3, 9, 9]], device=device, dtype=dtype),+ torch.tensor([[1, 5, 2, 7], [0, 3, 9, 9], [0, 5, 8, 7]], device=device, dtype=dtype),+ torch.empty((0, 4), device=device, dtype=dtype),+ ]++ inputs = [img, bbox]++ aug = K.AugmentationSequential(K.Resize((30, 30)), data_keys=['input', 'bbox_xyxy'])++ transformed = aug(*inputs)++ assert len(transformed) == len(inputs)+ bboxes_transformed = transformed[-1]+ assert len(bboxes_transformed) == len(bbox)+ assert len(bboxes_transformed[0]) == 2+ assert len(bboxes_transformed[1]) == 3+ assert len(bboxes_transformed[2]) == 0+@pytest.mark.parametrize('random_apply', [1, (2, 2), (1, 2), (2,), 10, True, False])def test_forward_and_inverse(self, random_apply, device, dtype):inp = torch.randn(1, 3, 1000, 500, device=device, dtype=dtype)