Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation): add crop_if_exceeds option to PadTo to avoid silent cropping (#3964)

Buland Choudharybf4fa1eb2c3a
diff --git a/changelog.d/3964.added.md b/changelog.d/3964.added.md
new file mode 100644
index 000000000..e2115b49a
--- /dev/null
+++ b/changelog.d/3964.added.md
@@ -0,0 +1 @@
+`PadTo` takes `crop_if_exceeds`. The default `True` keeps the existing behavior: an input larger than `size` on an axis is cropped to `size` there. With `crop_if_exceeds=False` that axis passes through unchanged, so the output is at least `size` on each axis and boxes and keypoints stay inside the image. Closes #3518.
diff --git a/kornia/augmentation/_2d/geometric/pad.py b/kornia/augmentation/_2d/geometric/pad.py
index 062320dbb..887aaaec0 100644
--- a/kornia/augmentation/_2d/geometric/pad.py
+++ b/kornia/augmentation/_2d/geometric/pad.py
@@ -36,6 +36,9 @@ class PadTo(GeometricAugmentationBase2D):
pad_value: fill value for 'constant' padding applied to the image
keepdim: whether to keep the output shape the same as input (True) or broadcast it
to the batch form (False).
+ crop_if_exceeds: if True (default), an input dimension larger than ``size`` is cropped to ``size``. If
+ False, that dimension passes through unchanged, so the output is at least ``size`` on each axis and its
+ shape depends on the input.
Shape:
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
@@ -46,9 +49,10 @@ class PadTo(GeometricAugmentationBase2D):
Convention:
See :class:`~kornia.augmentation.GeometricAugmentationBase2D` for coordinates, defaults and inverse.
- This operation always runs and pads on the right and bottom, using ``pad_mode`` and ``pad_value``. A
- target smaller than the input crops that axis instead, so a target can pad one axis while cropping the
- other (`#4410 <https://github.com/kornia/kornia/issues/4410>`_).
+ This operation always runs and pads on the right and bottom, using ``pad_mode`` and ``pad_value``. With the
+ default ``crop_if_exceeds=True``, a target smaller than the input crops that axis instead, so a target can pad
+ one axis while cropping the other (`#4410 <https://github.com/kornia/kornia/issues/4410>`_). With
+ ``crop_if_exceeds=False``, that axis passes through unchanged.
:meth:`inverse` slices to the prior input size. It exactly removes right/bottom padding, but after a crop it
returns the cropped result unchanged rather than restoring discarded pixels. The transformation matrix is
@@ -71,13 +75,27 @@ class PadTo(GeometricAugmentationBase2D):
[0., 0., 0.],
[0., 0., 0.]]]])
+ >>> img_large = torch.zeros(1, 1, 4, 4)
+ >>> PadTo((2, 2), crop_if_exceeds=False)(img_large).shape
+ torch.Size([1, 1, 4, 4])
+
"""
def __init__(
- self, size: Tuple[int, int], pad_mode: str = "constant", pad_value: float = 0, keepdim: bool = False
+ self,
+ size: Tuple[int, int],
+ pad_mode: str = "constant",
+ pad_value: float = 0,
+ keepdim: bool = False,
+ crop_if_exceeds: bool = True,
) -> None:
super().__init__(p=1.0, same_on_batch=True, p_batch=1.0, keepdim=keepdim)
- self.flags = {"size": size, "pad_mode": pad_mode, "pad_value": pad_value}
+ self.flags = {
+ "size": size,
+ "pad_mode": pad_mode,
+ "pad_value": pad_value,
+ "crop_if_exceeds": crop_if_exceeds,
+ }
# TODO: It is incorrect to return identity
# TODO: Having a resampled version with ``warp_affine``
@@ -90,6 +108,10 @@ class PadTo(GeometricAugmentationBase2D):
_, _, height, width = input.shape
height_pad: int = flags["size"][0] - height
width_pad: int = flags["size"][1] - width
+ # A PadTo pickled before ``crop_if_exceeds`` existed has no such flag and keeps cropping.
+ if not flags.get("crop_if_exceeds", True):
+ height_pad = max(height_pad, 0)
+ width_pad = max(width_pad, 0)
return torch.nn.functional.pad(
input, [0, width_pad, 0, height_pad], mode=flags["pad_mode"], value=flags["pad_value"]
)
diff --git a/kornia/augmentation/container/image.py b/kornia/augmentation/container/image.py
index 0ad2cdd49..48e25f624 100644
--- a/kornia/augmentation/container/image.py
+++ b/kornia/augmentation/container/image.py
@@ -503,7 +503,8 @@ def _get_new_batch_shape(param: ParamItem, batch_shape: torch.Size, module: Opti
Note:
Augmentations that change the spatial size provide `output_size` with shape (B, spatial_dims).
- `PadTo` and `RandomMosaic(output_size=...)` provide none, so their configured size is used.
+ `PadTo` and `RandomMosaic(output_size=...)` provide none, so their configured size is used; with
+ `crop_if_exceeds=False`, `PadTo` keeps a dimension that is already larger.
Empty crops and resizes have no sampled
output-size rows, so their configured size is used only when the image forward path
always applies the transform. Other probability branches retain the current empty-gate
@@ -539,13 +540,18 @@ def _get_new_batch_shape(param: ParamItem, batch_shape: torch.Size, module: Opti
batch_shape = _get_new_batch_shape(p, batch_shape, children.get(p.name))
return batch_shape
- # PadTo and RandomMosaic(output_size=...) always return their configured size but emit no ``output_size``.
+ # PadTo and RandomMosaic(output_size=...) return their configured size (PadTo(crop_if_exceeds=False): at least
+ # the input size) but emit no ``output_size``.
# No branch below matches them, so the final return passes the updated shape on.
if isinstance(module, (K.PadTo, K.RandomMosaic)):
size = module.flags["size" if isinstance(module, K.PadTo) else "output_size"]
if size is not None:
new_batch_shape = list(batch_shape)
- new_batch_shape[-len(size) :] = [operator.index(dim) for dim in size]
+ dims = [operator.index(dim) for dim in size]
+ if isinstance(module, K.PadTo) and not module.flags.get("crop_if_exceeds", True):
+ # A dimension already larger than the target is kept, not cropped.
+ dims = [max(old, dim) for old, dim in zip(new_batch_shape[-len(dims) :], dims)]
+ new_batch_shape[-len(dims) :] = dims
batch_shape = torch.Size(new_batch_shape)
if (
diff --git a/tests/augmentation/container/test_augmentation_sequential.py b/tests/augmentation/container/test_augmentation_sequential.py
index 9df82f736..42b22aa87 100644
--- a/tests/augmentation/container/test_augmentation_sequential.py
+++ b/tests/augmentation/container/test_augmentation_sequential.py
@@ -3185,8 +3185,12 @@ class TestCrop3DShapePropagation(BaseTester):
class TestPadToMosaicShapePropagation(BaseTester):
@pytest.mark.parametrize(
"make_first",
- [lambda: K.PadTo((40, 48)), lambda: K.RandomMosaic(output_size=(20, 30), p=1.0)],
- ids=["PadTo", "RandomMosaic"],
+ [
+ lambda: K.PadTo((40, 48)),
+ lambda: K.PadTo((16, 48), crop_if_exceeds=False), # keeps the larger input height, pads the width
+ lambda: K.RandomMosaic(output_size=(20, 30), p=1.0),
+ ],
+ ids=["PadTo", "PadTo-no-crop", "RandomMosaic"],
)
@pytest.mark.parametrize(
"make_second",
@@ -3213,6 +3217,7 @@ class TestPadToMosaicShapePropagation(BaseTester):
cases = [
(K.PadTo((40, 48)), (40, 48)),
(K.PadTo((16, 48)), (16, 48)), # a target below the input height crops it
+ (K.PadTo((16, 48), crop_if_exceeds=False), (24, 48)), # keeps the larger input height
(K.RandomMosaic(output_size=(20, 30), p=0.0), (20, 30)),
(K.RandomMosaic(p=1.0), (24, 40)),
]
diff --git a/tests/augmentation/test_augmentation.py b/tests/augmentation/test_augmentation.py
index 35269a462..68a9fead3 100644
--- a/tests/augmentation/test_augmentation.py
+++ b/tests/augmentation/test_augmentation.py
@@ -5495,6 +5495,54 @@ class TestPadTo(BaseTester):
assert out.shape == (1, 1, 4, 5)
self.assert_close(aug.inverse(out), img)
+ def test_crop_if_exceeds_true_crops_larger_input(self, device, dtype):
+ img = torch.rand(1, 1, 6, 6, device=device, dtype=dtype)
+ aug = PadTo(size=(4, 5), crop_if_exceeds=True)
+ out = aug(img)
+ assert out.shape == (1, 1, 4, 5)
+ self.assert_close(out, img[..., :4, :5])
+
+ def test_crop_if_exceeds_false_keeps_larger_input_unchanged(self, device, dtype):
+ img = torch.rand(1, 1, 6, 6, device=device, dtype=dtype)
+ aug = PadTo(size=(4, 5), crop_if_exceeds=False)
+ out = aug(img)
+ assert out.shape == (1, 1, 6, 6)
+ self.assert_close(out, img)
+ self.assert_close(aug.inverse(out), img)
+
+ def test_crop_if_exceeds_false_mixed_dims(self, device, dtype):
+ # height (6) exceeds target (4); width (2) is below target (5)
+ img = torch.rand(1, 1, 6, 2, device=device, dtype=dtype)
+ aug = PadTo(size=(4, 5), crop_if_exceeds=False)
+ out = aug(img)
+ assert out.shape == (1, 1, 6, 5)
+ # the exceeding height dimension is left untouched, and the original
+ # content is preserved with zeros padded onto the short width dimension
+ self.assert_close(out[..., :2], img)
+ self.assert_close(out[..., 2:], torch.zeros(1, 1, 6, 3, device=device, dtype=dtype))
+ self.assert_close(aug.inverse(out), img)
+
+ def test_default_crops_larger_input(self, device, dtype):
+ img = torch.rand(1, 1, 6, 6, device=device, dtype=dtype)
+ out = PadTo(size=(4, 5))(img)
+ assert out.shape == (1, 1, 4, 5)
+ self.assert_close(out, img[..., :4, :5])
+
+ def test_flags_without_crop_if_exceeds_keep_cropping(self, device, dtype):
+ # A PadTo pickled before ``crop_if_exceeds`` existed unpickles with no such key in ``flags``.
+ aug = PadTo(size=(4, 5), crop_if_exceeds=False)
+ del aug.flags["crop_if_exceeds"]
+ img = torch.rand(1, 1, 6, 6, device=device, dtype=dtype)
+ self.assert_close(aug(img), img[..., :4, :5])
+
+ @pytest.mark.parametrize("crop_if_exceeds", [True, False])
+ def test_dynamo(self, device, dtype, torch_optimizer, crop_if_exceeds):
+ # The input is taller and narrower than the target: one call crops (or keeps) the height and pads the width.
+ img = torch.rand(2, 3, 6, 2, device=device, dtype=dtype)
+ aug = PadTo(size=(4, 5), crop_if_exceeds=crop_if_exceeds)
+ compiled = torch_optimizer(aug, fullgraph=True)
+ self.assert_close(compiled(img), aug(img))
+
class TestResize:
def test_smoke(self, device, dtype):
diff --git a/tests/augmentation/test_torch_export.py b/tests/augmentation/test_torch_export.py
index 6e5c84458..8d364e5de 100644
--- a/tests/augmentation/test_torch_export.py
+++ b/tests/augmentation/test_torch_export.py
@@ -67,12 +67,18 @@ def _pad_to() -> torch.nn.Module:
return K.PadTo((40, 40))
+def _pad_to_no_crop() -> torch.nn.Module:
+ # The 32 x 32 input is taller than the target, so its height passes through and its width is padded.
+ return K.PadTo((16, 40), crop_if_exceeds=False)
+
+
TORCH_EXPORT_DETERMINISTIC: list[Tuple[str, Callable[[], torch.nn.Module]]] = [
("Normalize", _normalize),
("Denormalize", _denormalize),
("Resize", _resize),
("CenterCrop", _center_crop),
("PadTo", _pad_to),
+ ("PadTo[no-crop]", _pad_to_no_crop),
]