Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Update batch shape when augmentations change size of image (#1609)

Miquel Martí8cb8947274a4
diff --git a/kornia/augmentation/_2d/geometric/resize.py b/kornia/augmentation/_2d/geometric/resize.py
index 52bcb8f6e..66c274080 100644
--- a/kornia/augmentation/_2d/geometric/resize.py
+++ b/kornia/augmentation/_2d/geometric/resize.py
@@ -37,7 +37,7 @@ class Resize(GeometricAugmentationBase2D):
self.flags = dict(size=size, side=side, resample=Resample.get(resample), align_corners=align_corners)
def compute_transformation(self, input: Tensor, params: Dict[str, Tensor]) -> Tensor:
- if params["resize_to"] == input.shape[-2:]:
+ if params["output_size"] == input.shape[-2:]:
return eye_like(3, input)
transform: Tensor = get_perspective_transform(params["src"], params["dst"])
@@ -48,7 +48,7 @@ class Resize(GeometricAugmentationBase2D):
self, input: Tensor, params: Dict[str, Tensor], transform: Optional[Tensor] = None
) -> Tensor:
B, C, _, _ = input.shape
- out_size = tuple(params["resize_to"].tolist())
+ out_size = tuple(params["output_size"][0].tolist())
out = torch.empty(B, C, *out_size, device=input.device, dtype=input.dtype)
for i in range(B):
x1 = int(params["src"][i, 0, 0])
diff --git a/kornia/augmentation/container/image.py b/kornia/augmentation/container/image.py
index 44277043d..392547eeb 100644
--- a/kornia/augmentation/container/image.py
+++ b/kornia/augmentation/container/image.py
@@ -220,17 +220,12 @@ class ImageSequential(SequentialBase):
if isinstance(module, RandomCrop):
mod_param = module.forward_parameters_precrop(batch_shape)
param = ParamItem(name, mod_param)
- cropped_batch_shape = list(batch_shape)
- cropped_batch_shape[-2:] = module.flags['size']
- batch_shape = torch.Size(cropped_batch_shape)
- elif isinstance(module, (_AugmentationBase, MixAugmentationBase)):
- mod_param = module.forward_parameters(batch_shape)
- param = ParamItem(name, mod_param)
- elif isinstance(module, ImageSequential):
+ elif isinstance(module, (_AugmentationBase, MixAugmentationBase, ImageSequential)):
mod_param = module.forward_parameters(batch_shape)
param = ParamItem(name, mod_param)
else:
param = ParamItem(name, None)
+ batch_shape = _get_new_batch_shape(param, batch_shape)
params.append(param)
return params
@@ -373,3 +368,25 @@ class ImageSequential(SequentialBase):
param = ParamItem(param.name, None)
self.update_params(param)
return self.__packup_output__(input, label)
+
+
+def _get_new_batch_shape(param: ParamItem, batch_shape: torch.Size) -> torch.Size:
+ """Get the new batch shape if the augmentation changes the image size.
+
+ Note:
+ Augmentations that change the image size must provide the parameter `output_size`.
+ """
+ if param.data is None:
+ return batch_shape
+ if isinstance(param.data, list):
+ for p in param.data:
+ batch_shape = _get_new_batch_shape(p, batch_shape)
+ elif 'output_size' in param.data:
+ if not param.data['batch_prob'][0]:
+ # Augmentations that change the image size must be applied equally to all elements in batch.
+ # If the augmentation is not applied, return the same batch shape.
+ return batch_shape
+ new_batch_shape = list(batch_shape)
+ new_batch_shape[-2:] = param.data['output_size'][0]
+ batch_shape = torch.Size(new_batch_shape)
+ return batch_shape
diff --git a/kornia/augmentation/container/video.py b/kornia/augmentation/container/video.py
index 83cff3392..7bfec176e 100644
--- a/kornia/augmentation/container/video.py
+++ b/kornia/augmentation/container/video.py
@@ -8,7 +8,7 @@ from kornia.augmentation import RandomCrop
from kornia.augmentation._2d.mix.base import MixAugmentationBase
from kornia.augmentation.base import _AugmentationBase
from kornia.augmentation.container.base import SequentialBase
-from kornia.augmentation.container.image import ImageSequential, ParamItem
+from kornia.augmentation.container.image import ImageSequential, ParamItem, _get_new_batch_shape
from kornia.augmentation.container.utils import InputApplyInverse, MaskApplyInverse
__all__ = ["VideoSequential"]
@@ -205,6 +205,7 @@ class VideoSequential(ImageSequential):
param = ParamItem(name, mod_param)
else:
param = ParamItem(name, None)
+ batch_shape = _get_new_batch_shape(param, batch_shape)
params.append(param)
return params
diff --git a/kornia/augmentation/random_generator/_2d/crop.py b/kornia/augmentation/random_generator/_2d/crop.py
index e10ec2006..1e21ef99d 100644
--- a/kornia/augmentation/random_generator/_2d/crop.py
+++ b/kornia/augmentation/random_generator/_2d/crop.py
@@ -101,6 +101,7 @@ class CropGenerator(RandomGeneratorBase):
size[:, 1],
size[:, 0],
)
+ _output_size = size.to(dtype=torch.long)
else:
if not (
len(self.resize_to) == 2
@@ -122,10 +123,11 @@ class CropGenerator(RandomGeneratorBase):
device=_device,
dtype=_dtype,
).repeat(batch_size, 1, 1)
+ _output_size = torch.tensor(self.resize_to, device=_device, dtype=torch.long).expand(batch_size, -1)
_input_size = torch.tensor(input_size, device=_device, dtype=torch.long).expand(batch_size, -1)
- return dict(src=crop_src, dst=crop_dst, input_size=_input_size)
+ return dict(src=crop_src, dst=crop_dst, input_size=_input_size, output_size=_output_size)
class ResizedCropGenerator(CropGenerator):
@@ -515,5 +517,6 @@ def center_crop_generator(
).expand(batch_size, -1, -1)
_input_size = torch.tensor((height, width), device=device, dtype=torch.long).expand(batch_size, -1)
+ _output_size = torch.tensor(size, device=device, dtype=torch.long).expand(batch_size, -1)
- return dict(src=points_src, dst=points_dst, input_size=_input_size)
+ return dict(src=points_src, dst=points_dst, input_size=_input_size, output_size=_output_size)
diff --git a/kornia/augmentation/random_generator/_2d/resize.py b/kornia/augmentation/random_generator/_2d/resize.py
index 507534fb0..3d39a40db 100644
--- a/kornia/augmentation/random_generator/_2d/resize.py
+++ b/kornia/augmentation/random_generator/_2d/resize.py
@@ -30,13 +30,13 @@ class ResizeGenerator(RandomGeneratorBase):
def __init__(self, resize_to: Union[int, Tuple[int, int]], side: str = "short") -> None:
super().__init__()
- self.resize_to = resize_to
+ self.output_size = resize_to
self.side = side
self.device: Optional[torch.device] = None
self.dtype: Optional[torch.dtype] = None
def __repr__(self) -> str:
- repr = f"resize_to={self.resize_to}"
+ repr = f"output_size={self.output_size}"
return repr
def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
@@ -65,26 +65,27 @@ class ResizeGenerator(RandomGeneratorBase):
torch.tensor(input_size[0], device=_device, dtype=_dtype),
).repeat(batch_size, 1, 1)
- if isinstance(self.resize_to, int):
+ if isinstance(self.output_size, int):
aspect_ratio = w / h
- self.resize_to = _side_to_image_size(self.resize_to, aspect_ratio, self.side)
+ self.output_size = _side_to_image_size(self.output_size, aspect_ratio, self.side)
if not (
- len(self.resize_to) == 2
- and isinstance(self.resize_to[0], (int,))
- and isinstance(self.resize_to[1], (int,))
- and self.resize_to[0] > 0
- and self.resize_to[1] > 0
+ len(self.output_size) == 2
+ and isinstance(self.output_size[0], (int,))
+ and isinstance(self.output_size[1], (int,))
+ and self.output_size[0] > 0
+ and self.output_size[1] > 0
):
- raise AssertionError(f"`resize_to` must be a tuple of 2 positive integers. Got {self.resize_to}.")
+ raise AssertionError(f"`resize_to` must be a tuple of 2 positive integers. Got {self.output_size}.")
dst = bbox_generator(
torch.tensor(0, device=_device, dtype=_dtype),
torch.tensor(0, device=_device, dtype=_dtype),
- torch.tensor(self.resize_to[1], device=_device, dtype=_dtype),
- torch.tensor(self.resize_to[0], device=_device, dtype=_dtype),
+ torch.tensor(self.output_size[1], device=_device, dtype=_dtype),
+ torch.tensor(self.output_size[0], device=_device, dtype=_dtype),
).repeat(batch_size, 1, 1)
_input_size = torch.tensor(input_size, device=_device, dtype=torch.long).expand(batch_size, -1)
+ _output_size = torch.tensor(self.output_size, device=_device, dtype=torch.long).expand(batch_size, -1)
- return dict(src=src, dst=dst, input_size=_input_size, resize_to=torch.as_tensor(self.resize_to))
+ return dict(src=src, dst=dst, input_size=_input_size, output_size=_output_size)
diff --git a/test/augmentation/test_random_generator.py b/test/augmentation/test_random_generator.py
index a6f849ca8..6cbb89cf4 100644
--- a/test/augmentation/test_random_generator.py
+++ b/test/augmentation/test_random_generator.py
@@ -410,6 +410,7 @@ class TestRandomCropGen(RandomGeneratorBaseTests):
dtype=dtype,
),
input_size=torch.tensor([[100, 100], [100, 100]], device=device, dtype=torch.long),
+ output_size=torch.tensor([[200, 200], [200, 200]], device=device, dtype=torch.long)
)
assert res.keys() == expected.keys()
assert_close(res['src'], expected['src'])
@@ -432,6 +433,7 @@ class TestRandomCropGen(RandomGeneratorBaseTests):
dtype=dtype,
),
input_size=torch.tensor([[100, 100], [100, 100]], device=device, dtype=torch.long),
+ output_size=torch.tensor([[200, 200], [200, 200]], device=device, dtype=torch.long)
)
assert res.keys() == expected.keys()
assert_close(res['src'], expected['src'])
@@ -500,6 +502,7 @@ class TestRandomCropSizeGen(RandomGeneratorBaseTests):
device=device,
dtype=torch.int64,
),
+ output_size=torch.tensor([[100, 100], [100, 100]], device=device, dtype=torch.long)
)
assert res.keys() == expected.keys()
assert_close(res['src'], expected['src'])
@@ -535,6 +538,7 @@ class TestRandomCropSizeGen(RandomGeneratorBaseTests):
device=device,
dtype=torch.int64,
),
+ output_size=torch.tensor([[100, 100], [100, 100]], device=device, dtype=torch.long)
)
assert res.keys() == expected.keys()
assert_close(res['src'], expected['src'])
@@ -671,6 +675,7 @@ class TestCenterCropGen(RandomGeneratorBaseTests):
dtype=torch.long,
),
input_size=torch.tensor([[200, 200], [200, 200]], device=device, dtype=torch.long),
+ output_size=torch.tensor([[120, 150], [120, 150]], device=device, dtype=torch.long)
)
assert res.keys() == expected.keys()
assert_close(res['src'].to(device=device), expected['src'])