Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Precompute padding parameters when RandomCrop aug in container (#1494)

Miquel Martí676f772be1cd
diff --git a/kornia/augmentation/augmentation.py b/kornia/augmentation/augmentation.py
index d79af3f14..4eaf1678e 100644
--- a/kornia/augmentation/augmentation.py
+++ b/kornia/augmentation/augmentation.py
@@ -1072,28 +1072,47 @@ class RandomCrop(GeometricAugmentationBase2D):
padding_size = [0, 0, 0, 0]
return self.precrop_padding(out, padding_size)
+ def forward_parameters_precrop(self, batch_shape) -> Dict[str, torch.Tensor]:
+ input_pad = self.compute_padding(batch_shape)
+ batch_shape_new = (
+ *batch_shape[:2],
+ batch_shape[2] + input_pad[2] + input_pad[3], # original height + top + bottom padding
+ batch_shape[3] + input_pad[0] + input_pad[1] # original width + left + right padding
+ )
+ padding_size = torch.tensor(tuple(input_pad), dtype=torch.long).expand(batch_shape[0], -1)
+ _params = super().forward_parameters(batch_shape_new)
+ _params.update({"padding_size": padding_size})
+ return _params
+
def forward(
self,
input: TensorWithTransformMat,
params: Optional[Dict[str, torch.Tensor]] = None,
return_transform: Optional[bool] = None,
) -> TensorWithTransformMat:
+ padding_size = params.get("padding_size") if params else None
+ if padding_size is not None:
+ input_pad = padding_size.unique(dim=0).cpu().squeeze().numpy().tolist()
+ else:
+ input_pad = None
+
if isinstance(input, (tuple, list)):
input_temp = _transform_input(input[0])
- input_pad = self.compute_padding(input[0].shape)
+ input_pad = self.compute_padding(input[0].shape) if input_pad is None else input_pad
_input = (self.precrop_padding(input_temp, input_pad), input[1])
else:
input = cast(torch.Tensor, input) # TODO: weird that cast is not working under this context.
input_temp = _transform_input(input)
- input_pad = self.compute_padding(input_temp.shape)
+ input_pad = self.compute_padding(input_temp.shape) if input_pad is None else input_pad
_input = self.precrop_padding(input_temp, input_pad) # type: ignore
out = super().forward(_input, params, return_transform)
# Update the actual input size for inverse
- _padding_size = torch.tensor(tuple(input_pad), device=input_temp.device, dtype=torch.long).expand(
- input_temp.size(0), -1
- )
- self._params.update({"padding_size": _padding_size})
+ if "padding_size" not in self._params:
+ _padding_size = torch.tensor(tuple(input_pad), device=input_temp.device, dtype=torch.long).expand(
+ input_temp.size(0), -1
+ )
+ self._params.update({"padding_size": _padding_size})
if not self._params["batch_prob"].all():
# undo the pre-crop if nothing happened.
diff --git a/kornia/augmentation/container/image.py b/kornia/augmentation/container/image.py
index 4162a4624..c664d72f5 100644
--- a/kornia/augmentation/container/image.py
+++ b/kornia/augmentation/container/image.py
@@ -5,6 +5,7 @@ import torch
import torch.nn as nn
import kornia
+from kornia.augmentation import RandomCrop
from kornia.augmentation.base import (
_AugmentationBase,
GeometricAugmentationBase2D,
@@ -216,7 +217,10 @@ class ImageSequential(SequentialBase):
params: List[ParamItem] = []
mod_param: Union[dict, list]
for name, module in named_modules:
- if isinstance(module, (_AugmentationBase, MixAugmentationBase)):
+ if isinstance(module, RandomCrop):
+ mod_param = module.forward_parameters_precrop(batch_shape)
+ param = ParamItem(name, mod_param)
+ elif isinstance(module, (_AugmentationBase, MixAugmentationBase)):
mod_param = module.forward_parameters(batch_shape)
param = ParamItem(name, mod_param)
elif isinstance(module, ImageSequential):
diff --git a/kornia/augmentation/container/utils.py b/kornia/augmentation/container/utils.py
index e242012fa..181744030 100644
--- a/kornia/augmentation/container/utils.py
+++ b/kornia/augmentation/container/utils.py
@@ -290,8 +290,75 @@ class BBoxXYXYApplyInverse(ApplyInverseImpl):
apply_func = partial(transform_bbox, mode="xyxy", restore_coordinates=True)
+ @classmethod
+ def _get_padding_size(cls, module, param):
+ if isinstance(module, GeometricAugmentationBase2D): # TODO: Or only RandomCrop?
+ _param = cast(Dict[str, torch.Tensor], param.data) # type: ignore
+ return _param.get("padding_size")
+ else:
+ return None
+
+ @classmethod
+ def pad(cls, input, padding_size):
+ for i in range(len(padding_size)):
+ input[i, :, 0::2] += padding_size[i][0] # left padding
+ input[i, :, 1::2] += padding_size[i][2] # top padding
+ return input
+
+ @classmethod
+ def unpad(cls, input, padding_size):
+ for i in range(len(padding_size)):
+ input[i, :, 0::2] -= padding_size[i][0] # left padding
+ input[i, :, 1::2] -= padding_size[i][2] # top padding
+ return input
+
+ @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.
+ """
+ _input = input.clone()
+
+ padding_size = cls._get_padding_size(module, param)
+ if padding_size is not None:
+ _input = cls.pad(_input, padding_size)
+
+ _input, label = super().apply_trans(_input, label, module, param)
-class BBoxXYWHApplyInverse(ApplyInverseImpl):
+ # TODO: Filter/crop boxes outside crop (with negative or larger than crop size coords)?
+
+ 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.
+ """
+ inverse = super().inverse(input, module, param)
+
+ padding_size = cls._get_padding_size(module, param)
+ if padding_size is not None:
+ inverse = cls.unpad(inverse, padding_size)
+
+ return inverse
+
+
+class BBoxXYWHApplyInverse(BBoxXYXYApplyInverse):
"""Apply and inverse transformations for bounding box tensors.
This is for transform boxes in the format [xmin, ymin, width, height].
@@ -299,11 +366,28 @@ class BBoxXYWHApplyInverse(ApplyInverseImpl):
apply_func = partial(transform_bbox, mode="xywh", restore_coordinates=True)
+ @classmethod
+ def pad(cls, input, padding_size):
+ # pad only xy, not wh
+ for i in range(len(padding_size)):
+ input[i, :, 0] += padding_size[i][0] # left padding
+ input[i, :, 1] += padding_size[i][2] # top padding
+ return input
+
+ @classmethod
+ def unpad(cls, input, padding_size):
+ # unpad only xy, not wh
+ for i in range(len(padding_size)):
+ input[i, :, 0] -= padding_size[i][0] # left padding
+ input[i, :, 1] -= padding_size[i][2] # top padding
+ return input
+
-class KeypointsApplyInverse(ApplyInverseImpl):
+class KeypointsApplyInverse(BBoxXYWHApplyInverse):
"""Apply and inverse transformations for keypoints tensors."""
- apply_func = transform_points
+ # Hot fix for the typing mismatching
+ apply_func = partial(transform_points)
class ApplyInverse:
diff --git a/kornia/augmentation/container/video.py b/kornia/augmentation/container/video.py
index 752345b31..d3d89cc0d 100644
--- a/kornia/augmentation/container/video.py
+++ b/kornia/augmentation/container/video.py
@@ -4,6 +4,7 @@ import torch
import torch.nn as nn
import kornia
+from kornia.augmentation import RandomCrop
from kornia.augmentation.base import _AugmentationBase, MixAugmentationBase, TensorWithTransformMat
from kornia.augmentation.container.base import SequentialBase
from kornia.augmentation.container.utils import InputApplyInverse, MaskApplyInverse
@@ -180,7 +181,13 @@ class VideoSequential(ImageSequential):
params = []
for name, module in named_modules:
- if isinstance(module, (SequentialBase,)):
+ if isinstance(module, RandomCrop):
+ mod_param = module.forward_parameters_precrop(batch_shape)
+ if self.same_on_frame:
+ mod_param["src"] = mod_param["src"].repeat(frame_num, 1, 1)
+ mod_param["dst"] = mod_param["dst"].repeat(frame_num, 1, 1)
+ param = ParamItem(name, mod_param)
+ elif isinstance(module, (SequentialBase,)):
seq_param = module.forward_parameters(batch_shape)
if self.same_on_frame:
raise ValueError("Sequential is currently unsupported for ``same_on_frame``.")
diff --git a/test/augmentation/test_container.py b/test/augmentation/test_container.py
index 102d9910b..a1969e213 100644
--- a/test/augmentation/test_container.py
+++ b/test/augmentation/test_container.py
@@ -113,6 +113,7 @@ class TestVideoSequential:
'augmentations',
[
[K.RandomAffine(360, p=1.0)],
+ [K.RandomCrop((2, 2), padding=2)],
[K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0)],
[K.RandomAffine(360, p=0.0), K.ImageSequential(K.RandomAffine(360, p=0.0))],
],
@@ -134,7 +135,10 @@ class TestVideoSequential:
if data_format == 'BCTHW':
input = input.transpose(1, 2)
output_2 = aug_list_2(input.reshape(-1, 3, 5, 6))
- output_2 = output_2.view(2, 4, 3, 5, 6)
+ if any(isinstance(a, K.RandomCrop) for a in augmentations):
+ output_2 = output_2.view(2, 4, 3, 2, 2)
+ else:
+ output_2 = output_2.view(2, 4, 3, 5, 6)
if data_format == 'BCTHW':
output_2 = output_2.transpose(1, 2)
assert (output_1 == output_2).all(), dict(aug_list_1._params)
@@ -298,6 +302,52 @@ class TestAugmentationSequential:
assert_close(out_ver[1], expected_bbox_vertical_flip)
assert_close(out_hor[1], expected_bbox_horizontal_flip)
+ def test_random_crops(self, device, dtype):
+ input = torch.randn(3, 3, 3, 3, device=device, dtype=dtype)
+ bbox = torch.tensor(
+ [[[1.0, 1.0, 2.0, 2.0], [0.0, 0.0, 1.0, 2.0], [0.0, 0.0, 2.0, 1.0]]],
+ device=device, dtype=dtype).expand(3, -1, -1)
+ points = torch.tensor([[[0.0, 0.0], [1.0, 1.0]]], device=device, dtype=dtype).expand(3, -1, -1)
+ aug = K.AugmentationSequential(
+ K.RandomCrop((3, 3), padding=1, cropping_mode='resample', fill=0),
+ data_keys=["input", "mask", "bbox", "keypoints"]
+ )
+
+ reproducibility_test((input, input, bbox, points), aug)
+
+ _params = aug.forward_parameters(input.shape)
+ # specifying the crops allows us to compute by hand the expected outputs
+ _params[0].data['src'] = torch.tensor(
+ [[[1., 2.], [3., 2.], [3., 4.], [1., 4.]],
+ [[1., 1.], [3., 1.], [3., 3.], [1., 3.]],
+ [[2., 0.], [4., 0.], [4., 2.], [2., 2.]]],
+ device=_params[0].data['src'].device, dtype=_params[0].data['src'].dtype)
+
+ expected_out_bbox = torch.tensor(
+ [[[1., 0., 2., 1.], [0., -1., 1., 1.], [0., -1., 2., 0.]],
+ [[1., 1., 2., 2.], [0., 0., 1., 2.], [0., 0., 2., 1.]],
+ [[0., 2., 1., 3.], [-1., 1., 0., 3.], [-1., 1., 1., 2.]]], device=device, dtype=dtype)
+ expected_out_points = torch.tensor(
+ [[[0., -1.], [1., 0.]],
+ [[0., 0.], [1., 1.]],
+ [[-1., 1.], [0., 2.]]], device=device, dtype=dtype)
+
+ out = aug(input, input, bbox, points, params=_params)
+ assert out[0].shape == (3, 3, 3, 3)
+ assert_close(out[0], out[1], atol=1e-4, rtol=1e-4)
+ assert out[2].shape == bbox.shape
+ assert_close(out[2], expected_out_bbox, atol=1e-4, rtol=1e-4)
+ assert out[3].shape == points.shape
+ assert_close(out[3], expected_out_points, atol=1e-4, rtol=1e-4)
+
+ out_inv = aug.inverse(*out)
+ assert out_inv[0].shape == input.shape
+ assert_close(out_inv[0], out_inv[1], atol=1e-4, rtol=1e-4)
+ assert out_inv[2].shape == bbox.shape
+ assert_close(out_inv[2], bbox, atol=1e-4, rtol=1e-4)
+ assert out_inv[3].shape == points.shape
+ assert_close(out_inv[3], points, atol=1e-4, rtol=1e-4)
+
@pytest.mark.parametrize('random_apply', [1, (2, 2), (1, 2), (2,), 10, True, False])
@pytest.mark.parametrize('return_transform', [True, False])
def test_forward_and_inverse(self, random_apply, return_transform, device, dtype):
@@ -341,8 +391,9 @@ class TestAugmentationSequential:
bbox = torch.tensor([[[355, 10], [660, 10], [660, 250], [355, 250]]], device=device, dtype=dtype)
keypoints = torch.tensor([[[465, 115], [545, 116]]], device=device, dtype=dtype)
mask = bbox_to_mask(
- torch.tensor([[[155, 0], [900, 0], [900, 400], [155, 400]]], device=device, dtype=dtype), 1000, 500
+ torch.tensor([[[155, 0], [900, 0], [900, 400], [155, 400]]], device=device, dtype=dtype), 500, 1000
)[:, None].float()
+ crop_size = (200, 200)
aug = K.AugmentationSequential(
K.ImageSequential(
@@ -352,10 +403,23 @@ class TestAugmentationSequential:
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),
+ K.RandomCrop(crop_size, padding=1, cropping_mode='resample', fill=0),
data_keys=['input', 'mask', 'bbox', 'keypoints'],
)
reproducibility_test((inp, mask, bbox, keypoints), aug)
+ out = aug(inp, mask, bbox, keypoints)
+ assert out[0].shape == (*inp.shape[:2], *crop_size)
+ assert out[1].shape == (*mask.shape[:2], *crop_size)
+ assert out[2].shape == bbox.shape
+ assert out[3].shape == keypoints.shape
+
+ out_inv = aug.inverse(*out)
+ assert out_inv[0].shape == inp.shape
+ assert out_inv[1].shape == mask.shape
+ assert out_inv[2].shape == bbox.shape
+ assert out_inv[3].shape == keypoints.shape
+
aug = K.AugmentationSequential(K.RandomAffine(360, p=1.0, return_transform=True))
assert aug(inp, data_keys=['input'])[0].shape == inp.shape
aug = K.AugmentationSequential(K.RandomAffine(360, p=1.0, return_transform=False))