Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

feat: augmentation sequential supports mask (B, H, W) with images (B, C, H, W) (#2800)

João Gustavo A. Amorim2bd814384b23
diff --git a/kornia/augmentation/_2d/base.py b/kornia/augmentation/_2d/base.py
index e84b18962..71d8bf4f6 100644
--- a/kornia/augmentation/_2d/base.py
+++ b/kornia/augmentation/_2d/base.py
@@ -3,7 +3,7 @@ from typing import Any, Dict, Optional
from torch import float16, float32, float64
from kornia.augmentation.base import _AugmentationBase
-from kornia.augmentation.utils import _transform_input, _validate_input_dtype
+from kornia.augmentation.utils import _transform_input, _transform_input_by_shape, _validate_input_dtype
from kornia.core import Tensor
from kornia.geometry.boxes import Boxes
from kornia.geometry.keypoints import Keypoints
@@ -33,10 +33,14 @@ class AugmentationBase2D(_AugmentationBase):
if len(input.shape) != 4:
raise RuntimeError(f"Expect (B, C, H, W). Got {input.shape}.")
- def transform_tensor(self, input: Tensor) -> Tensor:
+ def transform_tensor(self, input: Tensor, *, shape: Optional[Tensor] = None, match_channel: bool = True) -> Tensor:
"""Convert any incoming (H, W), (C, H, W) and (B, C, H, W) into (B, C, H, W)."""
_validate_input_dtype(input, accepted_dtypes=[float16, float32, float64])
- return _transform_input(input)
+
+ if shape is None:
+ return _transform_input(input)
+ else:
+ return _transform_input_by_shape(input, reference_shape=shape, match_channel=match_channel)
class RigidAffineAugmentationBase2D(AugmentationBase2D):
diff --git a/kornia/augmentation/_2d/mix/base.py b/kornia/augmentation/_2d/mix/base.py
index ff30c2cf2..44efd496a 100644
--- a/kornia/augmentation/_2d/mix/base.py
+++ b/kornia/augmentation/_2d/mix/base.py
@@ -3,7 +3,12 @@ from typing import Any, Dict, List, Optional, Union
import torch
from kornia.augmentation.base import _BasicAugmentationBase
-from kornia.augmentation.utils import _transform_input, _transform_output_shape, _validate_input_dtype
+from kornia.augmentation.utils import (
+ _transform_input,
+ _transform_input_by_shape,
+ _transform_output_shape,
+ _validate_input_dtype,
+)
from kornia.constants import DataKey, DType
from kornia.core import Tensor, tensor
from kornia.core.check import KORNIA_UNWRAP
@@ -38,10 +43,14 @@ class MixAugmentationBaseV2(_BasicAugmentationBase):
super().__init__(p, p_batch=p_batch, same_on_batch=same_on_batch, keepdim=keepdim)
self.data_keys = [DataKey.get(inp) for inp in data_keys]
- def transform_tensor(self, input: Tensor) -> Tensor:
+ def transform_tensor(self, input: Tensor, *, shape: Optional[Tensor] = None, match_channel: bool = True) -> Tensor:
"""Convert any incoming (H, W), (C, H, W) and (B, C, H, W) into (B, C, H, W)."""
_validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])
- return _transform_input(input)
+
+ if shape is None:
+ return _transform_input(input)
+ else:
+ return _transform_input_by_shape(input, reference_shape=shape, match_channel=match_channel)
def apply_transform(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
# NOTE: apply_transform receives the whole tensor, but returns only altered elements.
diff --git a/kornia/augmentation/_3d/base.py b/kornia/augmentation/_3d/base.py
index cf76f878a..180959943 100644
--- a/kornia/augmentation/_3d/base.py
+++ b/kornia/augmentation/_3d/base.py
@@ -4,7 +4,7 @@ from torch import float16, float32, float64
import kornia
from kornia.augmentation.base import _AugmentationBase
-from kornia.augmentation.utils import _transform_input3d, _validate_input_dtype
+from kornia.augmentation.utils import _transform_input3d, _transform_input3d_by_shape, _validate_input_dtype
from kornia.core import Tensor
from kornia.geometry.boxes import Boxes3D
from kornia.geometry.keypoints import Keypoints3D
@@ -27,10 +27,13 @@ class AugmentationBase3D(_AugmentationBase):
if len(input.shape) != 5:
raise RuntimeError(f"Expect (B, C, D, H, W). Got {input.shape}.")
- def transform_tensor(self, input: Tensor) -> Tensor:
+ def transform_tensor(self, input: Tensor, *, shape: Optional[Tensor] = None, match_channel: bool = True) -> Tensor:
"""Convert any incoming (D, H, W), (C, D, H, W) and (B, C, D, H, W) into (B, C, D, H, W)."""
_validate_input_dtype(input, accepted_dtypes=[float16, float32, float64])
- return _transform_input3d(input)
+ if shape is None:
+ return _transform_input3d(input)
+ else:
+ return _transform_input3d_by_shape(input, reference_shape=shape, match_channel=match_channel)
def identity_matrix(self, input: Tensor) -> Tensor:
"""Return 4x4 identity matrix."""
diff --git a/kornia/augmentation/base.py b/kornia/augmentation/base.py
index 39136cbeb..6a92a975d 100644
--- a/kornia/augmentation/base.py
+++ b/kornia/augmentation/base.py
@@ -87,7 +87,7 @@ class _BasicAugmentationBase(Module):
def __unpack_input__(self, input: Tensor) -> Tensor:
return input
- def transform_tensor(self, input: Tensor) -> Tensor:
+ def transform_tensor(self, input: Tensor, *, shape: Optional[Tensor] = None, match_channel: bool = True) -> Tensor:
"""Standardize input tensors."""
raise NotImplementedError
@@ -247,8 +247,6 @@ class _AugmentationBase(_BasicAugmentationBase):
transform: Optional[Tensor] = None,
**kwargs: Any,
) -> Tensor:
- self.validate_tensor(input)
-
params, flags = self._process_kwargs_to_params_and_flags(
self._params if params is None else params, flags, **kwargs
)
@@ -257,6 +255,8 @@ class _AugmentationBase(_BasicAugmentationBase):
to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions.
ori_shape = input.shape
in_tensor = self.transform_tensor(input)
+
+ self.validate_tensor(in_tensor)
if to_apply.all():
output = self.apply_transform(in_tensor, params, flags, transform=transform)
elif not to_apply.any():
@@ -271,6 +271,7 @@ class _AugmentationBase(_BasicAugmentationBase):
output = output.type(input.dtype)
applied = applied.type(input.dtype)
output = output.index_put((to_apply,), applied)
+
output = _transform_output_shape(output, ori_shape) if self.keepdim else output
if is_autocast_enabled():
@@ -285,8 +286,6 @@ class _AugmentationBase(_BasicAugmentationBase):
transform: Optional[Tensor] = None,
**kwargs: Any,
) -> Tensor:
- self.validate_tensor(input)
-
params, flags = self._process_kwargs_to_params_and_flags(
self._params if params is None else params, flags, **kwargs
)
@@ -294,7 +293,11 @@ class _AugmentationBase(_BasicAugmentationBase):
batch_prob = params["batch_prob"]
to_apply = batch_prob > 0.5 # NOTE: in case of Relaxed Distributions.
ori_shape = input.shape
- in_tensor = self.transform_tensor(input)
+
+ shape = params["forward_input_shape"]
+ in_tensor = self.transform_tensor(input, shape=shape, match_channel=False)
+
+ self.validate_tensor(in_tensor)
if to_apply.all():
output = self.apply_transform_mask(in_tensor, params, flags, transform=transform)
elif not to_apply.any():
@@ -305,7 +308,7 @@ class _AugmentationBase(_BasicAugmentationBase):
in_tensor[to_apply], params, flags, transform=transform if transform is None else transform[to_apply]
)
output = output.index_put((to_apply,), applied)
- output = _transform_output_shape(output, ori_shape) if self.keepdim else output
+ output = _transform_output_shape(output, ori_shape, reference_shape=shape) if self.keepdim else output
return output
def transform_boxes(
diff --git a/kornia/augmentation/utils/__init__.py b/kornia/augmentation/utils/__init__.py
index f96e354eb..7c7b8c348 100644
--- a/kornia/augmentation/utils/__init__.py
+++ b/kornia/augmentation/utils/__init__.py
@@ -8,6 +8,8 @@ from kornia.augmentation.utils.helpers import (
_shape_validation,
_transform_input,
_transform_input3d,
+ _transform_input3d_by_shape,
+ _transform_input_by_shape,
_transform_output_shape,
_validate_input,
_validate_input3d,
@@ -30,6 +32,8 @@ __all__ = [
"_infer_batch_shape3d",
"_transform_input",
"_transform_input3d",
+ "_transform_input_by_shape",
+ "_transform_input3d_by_shape",
"_validate_input_dtype",
"_validate_shape",
"_validate_input_shape",
diff --git a/kornia/augmentation/utils/helpers.py b/kornia/augmentation/utils/helpers.py
index 0693be1e3..6fc3ca050 100644
--- a/kornia/augmentation/utils/helpers.py
+++ b/kornia/augmentation/utils/helpers.py
@@ -82,6 +82,62 @@ def _infer_batch_shape3d(input: Union[Tensor, Tuple[Tensor, Tensor]]) -> torch.S
return tensor.shape
+def _transform_input_by_shape(input: Tensor, reference_shape: Tensor, match_channel: bool = True) -> Tensor:
+ """Reshape an input tensor to have the same dimensions as the reference_shape.
+
+ Arguments
+ input: tensor to be transformed
+ reference_shape: shape used as reference
+ match_channel: if True, C_{src} == C_{ref}. otherwise, no constrain. C =1 by default
+ """
+ B = reference_shape[-4] if len(reference_shape) >= 4 else None
+ C = reference_shape[-3] if len(reference_shape) >= 3 else None
+
+ if len(input.shape) == 2:
+ input = input.unsqueeze(0)
+
+ if len(input.shape) == 3 and B == input.shape[-3]:
+ # If the first dim matches within the batch_size, add a `C` dim
+ # Useful to handler Masks without `C` dimensions
+ input = input.unsqueeze(1)
+
+ if match_channel and C:
+ if not input.shape[-3] == C:
+ raise ValueError("The C dimension of tensor did not match with the reference tensor.")
+ elif match_channel and C is None:
+ raise ValueError("The reference tensor do not have a C dimension!")
+
+ return input
+
+
+def _transform_input3d_by_shape(input: Tensor, reference_shape: Tensor, match_channel: bool = True) -> Tensor:
+ """Reshape an input tensor to have the same dimensions as the reference_shape.
+
+ Arguments
+ input: tensor to be transformed
+ reference_shape: shape used as reference
+ match_channel: if True, C_{src} == C_{ref}. otherwise, no constrain. C =1 by default
+ """
+ B = reference_shape[-5] if len(reference_shape) >= 5 else None
+ C = reference_shape[-4] if len(reference_shape) >= 4 else None
+
+ if len(input.shape) == 3:
+ input = input.unsqueeze(0)
+
+ if len(input.shape) == 4 and B == input.shape[-4]:
+ # If the first dim matches within the batch_size, add a `C` dim
+ # Useful to handler Masks without `C` dimensions
+ input = input.unsqueeze(2)
+
+ if match_channel and C:
+ if not input.shape[-4] == C:
+ raise ValueError("The C dimension of tensor did not match with the reference tensor.")
+ elif match_channel and C is None:
+ raise ValueError("The reference tensor do not have a C dimension!")
+
+ return input
+
+
def _transform_input(input: Tensor) -> Tensor:
r"""Reshape an input tensor to be (*, C, H, W). Accept either (H, W), (C, H, W) or (*, C, H, W).
Args:
@@ -140,7 +196,9 @@ def _validate_input_dtype(input: Tensor, accepted_dtypes: List[torch.dtype]) ->
raise TypeError(f"Expected input of {accepted_dtypes}. Got {input.dtype}")
-def _transform_output_shape(output: Tensor, shape: Tuple[int, ...]) -> Tensor:
+def _transform_output_shape(
+ output: Tensor, shape: Tuple[int, ...], *, reference_shape: Optional[Tensor] = None
+) -> Tensor:
r"""Collapse the broadcasted batch dimensions an input tensor to be the specified shape.
Args:
input: Tensor
@@ -152,9 +210,12 @@ def _transform_output_shape(output: Tensor, shape: Tuple[int, ...]) -> Tensor:
out_tensor = output.clone()
for dim in range(len(out_tensor.shape) - len(shape)):
- if out_tensor.shape[0] != 1:
- raise AssertionError(f"Dimension {dim} of input is expected to be 1, got {out_tensor.shape[0]}")
- out_tensor = out_tensor.squeeze(0)
+ idx = 0
+ if reference_shape is not None and out_tensor.shape[0] == reference_shape[0] and len(shape) > 2:
+ idx = 1
+ if out_tensor.shape[idx] != 1:
+ raise AssertionError(f"Dimension {dim} of input is expected to be 1, got {out_tensor.shape[idx]}")
+ out_tensor = out_tensor.squeeze(idx)
return out_tensor
diff --git a/tests/augmentation/test_augmentation.py b/tests/augmentation/test_augmentation.py
index f9209308c..c7084ace5 100644
--- a/tests/augmentation/test_augmentation.py
+++ b/tests/augmentation/test_augmentation.py
@@ -98,13 +98,15 @@ class CommonTests(BaseTester):
self._test_smoke_call_implementation(params=param_set)
@pytest.mark.parametrize(
- "input_shape,expected_output_shape",
- [((4, 5), (1, 1, 4, 5)), ((3, 4, 5), (1, 3, 4, 5)), ((2, 3, 4, 5), (2, 3, 4, 5))],
+ "input_shape",
+ [(4, 5), (3, 4, 5), (2, 3, 4, 5)],
)
- def test_cardinality(self, input_shape, expected_output_shape):
- self._test_cardinality_implementation(
- input_shape=input_shape, expected_output_shape=expected_output_shape, params=self._default_param_set
- )
+ @pytest.mark.parametrize(
+ "keepdim",
+ [True, False],
+ )
+ def test_cardinality(self, input_shape, keepdim):
+ self._test_cardinality_implementation(input_shape=input_shape, keepdim=keepdim, params=self._default_param_set)
def test_random_p_0(self):
self._test_random_p_0_implementation(params=self._default_param_set)
@@ -190,20 +192,30 @@ class CommonTests(BaseTester):
assert output.shape[0] == batch_shape[0]
assert augmentation.transform_matrix.shape == expected_transformation_shape
- def _test_cardinality_implementation(self, input_shape, expected_output_shape, params):
+ def _test_cardinality_implementation(self, input_shape, params, keepdim=False, expected_output_shape=None):
# p==0.0
- augmentation = self._create_augmentation_from_params(**params, p=0.0)
+ augmentation = self._create_augmentation_from_params(**params, p=0.0, keepdim=keepdim)
test_input = torch.rand(input_shape, device=self.device, dtype=self.dtype)
output = augmentation(test_input)
- assert len(output.shape) == 4
- assert output.shape == torch.Size((1,) * (4 - len(input_shape)) + tuple(input_shape))
+
+ if keepdim:
+ assert output.shape == input_shape
+ else:
+ assert len(output.shape) == 4
+ assert output.shape == torch.Size((1,) * (4 - len(input_shape)) + tuple(input_shape))
# p==1.0
- augmentation = self._create_augmentation_from_params(**params, p=1.0)
+ augmentation = self._create_augmentation_from_params(**params, p=1.0, keepdim=keepdim)
test_input = torch.rand(input_shape, device=self.device, dtype=self.dtype)
output = augmentation(test_input)
- assert len(output.shape) == 4
- assert output.shape == expected_output_shape
+
+ if expected_output_shape:
+ assert len(output.shape) == 4
+ assert output.shape == expected_output_shape
+ elif keepdim:
+ assert output.shape == input_shape
+ else:
+ assert (*(1,) * (4 - len(input_shape)), *input_shape) == output.shape
def _test_random_p_0_implementation(self, params):
augmentation = self._create_augmentation_from_params(**params, p=0.0)
@@ -4162,11 +4174,17 @@ class TestRandomRain(BaseTester):
(err_msg_wrong_ch, (1, 2), (1, 2), torch.rand(2, 4, 5, device=device, dtype=dtype)),
]
- @pytest.mark.parametrize("batch_shape", [(1, 3, 5, 7), (1, 3, 6, 9)])
- def test_cardinality(self, batch_shape, device, dtype):
+ @pytest.mark.parametrize("batch_shape", [(1, 3, 5, 7), (1, 3, 6, 9), (5, 7)])
+ @pytest.mark.parametrize("keepdim", [True, False])
+ def test_cardinality(self, batch_shape, keepdim, device, dtype):
input_data = torch.rand(batch_shape, device=device, dtype=dtype)
- output_data = RandomRain(p=1.0, drop_height=(3, 4), drop_width=(2, 3), number_of_drops=(1, 3))(input_data)
- assert output_data.shape == batch_shape
+ output_data = RandomRain(p=1.0, drop_height=(3, 4), drop_width=(2, 3), number_of_drops=(1, 3), keepdim=keepdim)(
+ input_data
+ )
+ if keepdim:
+ assert output_data.shape == batch_shape
+ else:
+ assert (*(1,) * (4 - len(batch_shape)), *batch_shape) == output_data.shape
def test_smoke(self, device, dtype):
input_data = torch.rand(1, 3, 8, 9, device=device, dtype=dtype)
diff --git a/tests/augmentation/test_container.py b/tests/augmentation/test_container.py
index 72878ed93..5e8f32abd 100644
--- a/tests/augmentation/test_container.py
+++ b/tests/augmentation/test_container.py
@@ -522,6 +522,41 @@ class TestAugmentationSequential:
_, out_labels = aug(img, labels)
assert labels is out_labels
+ @pytest.mark.parametrize("B", [None, 1, 3, 5])
+ @pytest.mark.parametrize("C_i", [1, 3])
+ @pytest.mark.parametrize("C_m", [None, 1])
+ @pytest.mark.parametrize("keepdim", [True, False])
+ def test_masks_without_channel_dim(self, device, dtype, B, C_i, C_m, keepdim):
+ img_shape = (B, C_i, 1000, 500) if B else (C_i, 1000, 500)
+ mask_shape = tuple(x for x in (B, C_m, *img_shape[-2:]) if x)
+
+ inp = torch.randn(*img_shape, device=device, dtype=dtype)
+ mask = torch.randint(0, 5, mask_shape, device=device, dtype=dtype)
+
+ aug = K.AugmentationSequential(
+ # K.ImageSequential(K.RandomAffine(360, p=1.0)),
+ # K.AugmentationSequential(
+ # K.RandomAffine(360, p=1.0),
+ # data_keys=["input", "mask"],
+ # ),
+ K.RandomAffine(360, p=1.0),
+ K.RandomMixUpV2(p=1.0),
+ data_keys=["input", "mask"],
+ keepdim=keepdim,
+ )
+
+ aug.keepdim = keepdim # FIXME(@shijianjian): This shouldn't be necessary
+
+ out = aug(inp, mask)
+ if keepdim:
+ assert out[0].shape == img_shape
+ assert out[1].shape == mask_shape
+ else:
+ assert (*(1,) * (4 - len(img_shape)), *img_shape) == out[0].shape
+
+ out_mask_shape = tuple(x if x else 1 for x in (B, C_m, *img_shape[-2:]))
+ assert out[1].shape == out_mask_shape
+
@pytest.mark.slow
@pytest.mark.parametrize("random_apply", [1, (2, 2), (1, 2), (2,), 10, True, False])
def test_forward_and_inverse(self, random_apply, device, dtype):