Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Feat: Support list of masks in `AugmentationSequential` (#2740)

João Gustavo A. Amorim64c41e2cef13
diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.py
index 164a52105..b8857c765 100644
--- a/kornia/augmentation/container/augment.py
+++ b/kornia/augmentation/container/augment.py
@@ -146,6 +146,28 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
>>> out = aug_list(input, mask, bbox, points)
>>> [o.shape for o in out] # doctest: +ELLIPSIS
[torch.Size([1, 2, 3, 5, 6]), torch.Size([1, 2, 3, 5, 6]), ...([1, 2, 1, 4, 2]), torch.Size([1, 2, 1, 2])]
+
+ This example shows how to use a list of masks and boxes within AugmentationSequential
+
+ >>> import kornia.augmentation as K
+ >>> input = torch.randn(2, 3, 256, 256)
+ >>> mask = [torch.ones(1, 3, 256, 256), torch.ones(1, 2, 256, 256)]
+ >>> bbox = [
+ ... torch.tensor([[28.0, 53.0, 143.0, 164.0], [254.0, 158.0, 364.0, 290.0], [307.0, 204.0, 413.0, 350.0]]),
+ ... torch.tensor([[254.0, 158.0, 364.0, 290.0], [307.0, 204.0, 413.0, 350.0]])
+ ... ]
+ >>> bbox = [Boxes.from_tensor(i).data for i in bbox]
+
+ >>> aug_list = K.AugmentationSequential(
+ ... K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0),
+ ... K.RandomHorizontalFlip(p=1.0),
+ ... K.ImageSequential(K.RandomHorizontalFlip(p=1.0)),
+ ... K.ImageSequential(K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0)),
+ ... data_keys=["input", "mask", "bbox"],
+ ... same_on_batch=False,
+ ... random_apply=10,
+ ... )
+ >>> out = aug_list(input, mask, bbox)
"""
def __init__(
diff --git a/kornia/augmentation/container/ops.py b/kornia/augmentation/container/ops.py
index c75293b86..bfb65dc65 100644
--- a/kornia/augmentation/container/ops.py
+++ b/kornia/augmentation/container/ops.py
@@ -14,6 +14,9 @@ from .params import ParamItem
DataType = Union[Tensor, List[Tensor], Boxes, Keypoints]
+# NOTE: shouldn't this SequenceDataType alias be equals to List[DataType]?
+SequenceDataType = Union[List[Tensor], List[List[Tensor]], List[Boxes], List[Keypoints]]
+
T = TypeVar("T")
@@ -102,7 +105,7 @@ class AugmentationSequentialOps:
param: ParamItem,
extra_args: Dict[DataKey, Dict[str, Any]],
data_keys: Optional[Union[List[str], List[int], List[DataKey]]] = None,
- ) -> Union[DataType, List[DataType]]:
+ ) -> Union[DataType, SequenceDataType]:
_data_keys = self.preproc_datakeys(data_keys)
if isinstance(module, K.RandomTransplantation):
@@ -121,7 +124,10 @@ class AugmentationSequentialOps:
for inp, dcate in zip(arg, _data_keys):
op = self._get_op(dcate)
extra_arg = extra_args[dcate] if dcate in extra_args else {}
- outputs.append(op.transform(inp, module, param=param, extra_args=extra_arg))
+ if dcate.name == "MASK" and isinstance(inp, list):
+ outputs.append(MaskSequentialOps.transform_list(inp, module, param=param, extra_args=extra_arg))
+ else:
+ outputs.append(op.transform(inp, module, param=param, extra_args=extra_arg))
if len(outputs) == 1 and isinstance(outputs, (list, tuple)):
return outputs[0]
return outputs
@@ -133,7 +139,7 @@ class AugmentationSequentialOps:
param: ParamItem,
extra_args: Dict[DataKey, Dict[str, Any]],
data_keys: Optional[Union[List[str], List[int], List[DataKey]]] = None,
- ) -> Union[DataType, List[DataType]]:
+ ) -> Union[DataType, SequenceDataType]:
_data_keys = self.preproc_datakeys(data_keys)
outputs = []
for inp, dcate in zip(arg, _data_keys):
@@ -260,6 +266,69 @@ class MaskSequentialOps(SequentialOpsInterface[Tensor]):
return MaskSequentialOps.transform(input, module=module.op, param=param, extra_args=extra_args)
return input
+ @classmethod
+ def transform_list(
+ cls, input: List[Tensor], module: Module, param: ParamItem, extra_args: Dict[str, Any] = {}
+ ) -> List[Tensor]:
+ """Apply a transformation with respect to the parameters.
+
+ Args:
+ input: list of input tensors.
+ module: any torch Module but only kornia augmentation modules will count
+ to apply transformations.
+ param: the corresponding parameters to the module.
+ """
+ if isinstance(module, (K.GeometricAugmentationBase2D,)):
+ tfm_input = []
+ params = cls.get_instance_module_param(param)
+ for inp in input:
+ inp = module.transform_tensor(inp)
+ tfm_inp = module.transform_masks(
+ inp, params=params, flags=module.flags, transform=module.transform_matrix, **extra_args
+ )
+ tfm_input.append(tfm_inp)
+ input = tfm_input
+
+ elif isinstance(module, (K.GeometricAugmentationBase3D,)):
+ raise NotImplementedError(
+ "The support for 3d mask operations are not yet supported. You are welcome to file a PR in our repo."
+ )
+
+ elif isinstance(module, (_AugmentationBase)):
+ tfm_input = []
+ params = cls.get_instance_module_param(param)
+ for inp in input:
+ inp = module.transform_tensor(inp)
+ tfm_inp = module.transform_masks(inp, params=params, flags=module.flags, **extra_args)
+ tfm_input.append(tfm_inp)
+ input = tfm_input
+
+ elif isinstance(module, K.ImageSequential) and not module.is_intensity_only():
+ tfm_input = []
+ seq_params = cls.get_sequential_module_param(param)
+ for inp in input:
+ tfm_inp = module.transform_masks(inp, params=seq_params, extra_args=extra_args)
+ tfm_input.append(tfm_inp)
+ input = tfm_input
+
+ elif isinstance(module, K.container.ImageSequentialBase):
+ tfm_input = []
+ seq_params = cls.get_sequential_module_param(param)
+ for inp in input:
+ tfm_inp = module.transform_masks(inp, params=seq_params, extra_args=extra_args)
+ tfm_input.append(tfm_inp)
+ input = tfm_input
+
+ elif isinstance(module, (K.auto.operations.OperationBase,)):
+ raise NotImplementedError(
+ "The support for list of masks under auto operations are not yet supported. You are welcome to file a"
+ " PR in our repo."
+ )
+ # return [
+ # MaskSequentialOps.transform(inp, module=module.op, param=param, extra_args=extra_args) for inp in input
+ # ]
+ return input
+
@classmethod
def inverse(cls, input: Tensor, module: Module, param: ParamItem, extra_args: Dict[str, Any] = {}) -> Tensor:
"""Inverse a transformation with respect to the parameters.
diff --git a/tests/augmentation/test_container.py b/tests/augmentation/test_container.py
index 9c6480786..903156998 100644
--- a/tests/augmentation/test_container.py
+++ b/tests/augmentation/test_container.py
@@ -9,6 +9,7 @@ import kornia.augmentation as K
from kornia.augmentation.container.base import ParamItem
from kornia.constants import BorderType
from kornia.geometry.bbox import bbox_to_mask
+from kornia.geometry.boxes import Boxes
from testing.base import assert_close
@@ -672,6 +673,39 @@ class TestAugmentationSequential:
if random_apply is False:
reproducibility_test((inp, mask, bbox, keypoints, bbox_2, bbox_wh, bbox_wh_2), aug)
+ def test_transform_list_of_masks_and_boxes(self, device, dtype):
+ input = torch.randn(2, 3, 256, 256, device=device, dtype=dtype)
+ mask = [
+ torch.ones(1, 3, 256, 256, device=device, dtype=dtype),
+ torch.ones(1, 2, 256, 256, device=device, dtype=dtype),
+ ]
+
+ bbox = [
+ torch.tensor(
+ [[28.0, 53.0, 143.0, 164.0], [254.0, 158.0, 364.0, 290.0], [307.0, 204.0, 413.0, 350.0]],
+ device=device,
+ dtype=dtype,
+ ),
+ torch.tensor([[254.0, 158.0, 364.0, 290.0], [307.0, 204.0, 413.0, 350.0]], device=device, dtype=dtype),
+ ]
+
+ bbox = [Boxes.from_tensor(i).data for i in bbox]
+
+ aug_list = K.AugmentationSequential(
+ K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0),
+ K.RandomHorizontalFlip(p=1.0),
+ K.ImageSequential(K.RandomHorizontalFlip(p=1.0)),
+ K.ImageSequential(K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0)),
+ data_keys=["input", "mask", "bbox"],
+ same_on_batch=False,
+ random_apply=10,
+ )
+ out = aug_list(input, mask, bbox)
+
+ assert out[0].shape == input.shape
+ assert len(out[1]) == len(bbox)
+ assert len(out[2]) == len(mask)
+
@pytest.mark.jit()
@pytest.mark.skip(reason="turn off due to Union Type")
def test_jit(self, device, dtype):