Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation): scale slice crop axes independently (#5466)

Karnajeet Gosavi5df6bdc42a49
diff --git a/changelog.d/5466.fixed.md b/changelog.d/5466.fixed.md
new file mode 100644
index 000000000..843ed681b
--- /dev/null
+++ b/changelog.d/5466.fixed.md
@@ -0,0 +1 @@
+`RandomCrop(cropping_mode="slice")` now scales bounding boxes and keypoints only along axes where the requested crop exceeds the padded input, matching the image resize.
diff --git a/kornia/augmentation/_2d/geometric/crop.py b/kornia/augmentation/_2d/geometric/crop.py
index c5d834554..e31208395 100644
--- a/kornia/augmentation/_2d/geometric/crop.py
+++ b/kornia/augmentation/_2d/geometric/crop.py
@@ -89,7 +89,8 @@ class RandomCrop(GeometricAugmentationBase2D):
With ``pad_if_needed=False``, an oversized request does not raise: slice mode resizes the available slice,
and resample mode uses a mis-scaled warp that rescales both matrix axes and can blend in zero padding
- (`#4414 <https://github.com/kornia/kornia/issues/4414>`_). The scale is computed against the padded canvas,
+ (`#4414 <https://github.com/kornia/kornia/issues/4414>`_). Slice mode scales only the matrix axes along
+ which the request exceeds the canvas, as its resize does. The scale is computed against the padded canvas,
so a crop that fits after explicit padding gets no scale correction.
Slice mode uses :func:`~kornia.geometry.transform.crop_by_indices` with its own defaults and ignores this
@@ -227,7 +228,12 @@ class RandomCrop(GeometricAugmentationBase2D):
h += padding[2] + padding[3]
w += padding[0] + padding[1]
h_out, w_out = flags["size"]
- if h_out > h or w_out > w:
+ if flags["cropping_mode"] == "slice":
+ if w_out > w:
+ transform[:, 0, 0] *= w_out / w
+ if h_out > h:
+ transform[:, 1, 1] *= h_out / h
+ elif h_out > h or w_out > w:
transform[:, 0, 0] *= w_out / w
transform[:, 1, 1] *= h_out / h
return transform
@@ -238,12 +244,12 @@ class RandomCrop(GeometricAugmentationBase2D):
h_out, w_out = flags["size"]
needs_scale = (h_out > padded_h) | (w_out > padded_w)
scale_w = torch.where(
- needs_scale,
+ (w_out > padded_w) if flags["cropping_mode"] == "slice" else needs_scale,
torch.full_like(padded_w, w_out, dtype=transform.dtype) / padded_w.to(dtype=transform.dtype),
torch.ones_like(padded_w, dtype=transform.dtype),
)
scale_h = torch.where(
- needs_scale,
+ (h_out > padded_h) if flags["cropping_mode"] == "slice" else needs_scale,
torch.full_like(padded_h, h_out, dtype=transform.dtype) / padded_h.to(dtype=transform.dtype),
torch.ones_like(padded_h, dtype=transform.dtype),
)
diff --git a/tests/augmentation/container/test_random_crop.py b/tests/augmentation/container/test_random_crop.py
index 2d5bd35f3..3303b89c0 100644
--- a/tests/augmentation/container/test_random_crop.py
+++ b/tests/augmentation/container/test_random_crop.py
@@ -31,6 +31,19 @@ from testing.base import DYNAMO_UNAVAILABLE_REASON, BaseTester, dynamo_is_availa
class TestRandomCropAnnotations(BaseTester):
+ def test_slice_crop_boxes_match_pixels_when_only_height_is_oversized(self, device, dtype):
+ height, width, size = 329, 1209, 416
+ x = torch.arange(width, device=device, dtype=dtype).view(1, 1, 1, width).expand(1, 1, height, width)
+ boxes = torch.tensor([[[600.0, 100.0, 700.0, 200.0]]], device=device, dtype=dtype)
+ seq = K.AugmentationSequential(
+ K.RandomCrop((size, size), p=1.0, cropping_mode="slice"), data_keys=["input", "bbox_xyxy"]
+ )
+
+ out, out_boxes = seq(x, boxes)
+ x_offset = out[0, 0, 0, 0]
+
+ self.assert_close(out_boxes[0, 0, [0, 2]], boxes[0, 0, [0, 2]] - x_offset)
+
@staticmethod
def inputs(batch_size, device, dtype):
# Each pixel identifies its position and image, independently of the crop's matrix.
diff --git a/tests/augmentation/test_augmentation.py b/tests/augmentation/test_augmentation.py
index 784f5937d..843fcdbc0 100644
--- a/tests/augmentation/test_augmentation.py
+++ b/tests/augmentation/test_augmentation.py
@@ -3603,6 +3603,33 @@ class TestRandomRotation(BaseTester):
class TestRandomCrop(BaseTester):
+ @pytest.mark.parametrize("exporting", [False, True])
+ @pytest.mark.parametrize(
+ ("input_size", "size", "expected_scale"),
+ [
+ ((329, 1209), (416, 416), (1.0, 416 / 329)),
+ ((1209, 329), (416, 416), (416 / 329, 1.0)),
+ ((329, 329), (416, 416), (416 / 329, 416 / 329)),
+ ((500, 500), (416, 416), (1.0, 1.0)),
+ ],
+ )
+ def test_slice_crop_transform_scales_each_oversized_axis_independently(
+ self, input_size, size, expected_scale, exporting, device, dtype, monkeypatch
+ ):
+ from kornia.augmentation._2d.geometric import crop as crop_module
+
+ image = torch.zeros(1, 1, *input_size, device=device, dtype=dtype)
+ aug = RandomCrop(size, cropping_mode="slice", p=1.0)
+ params = aug.forward_parameters(image.shape)
+ monkeypatch.setattr(crop_module, "is_exporting", lambda: exporting)
+
+ transform = aug.compute_transformation(image, params, aug.flags)
+
+ self.assert_close(
+ transform[0, :2, :2],
+ torch.diag(torch.tensor(expected_scale, device=device, dtype=dtype)),
+ )
+
def test_fill_accepts_one_value_per_channel(self, device, dtype):
image = torch.zeros(1, 3, 2, 2, device=device, dtype=dtype)
fill = (0.25, 0.5, 0.75)
diff --git a/tests/augmentation/test_conventions_geometric_crop.py b/tests/augmentation/test_conventions_geometric_crop.py
index 4397972d2..dcc706dc9 100644
--- a/tests/augmentation/test_conventions_geometric_crop.py
+++ b/tests/augmentation/test_conventions_geometric_crop.py
@@ -223,10 +223,17 @@ class TestGeometricCropConventions(BaseTester):
params[0].data["src"] = image.new_tensor([[[0, 0], [3, 0], [3, 5], [0, 5]]])
params[0].data["dst"] = image.new_tensor([[[0, 0], [3, 0], [3, 5], [0, 5]]])
output, out_points, out_boxes = seq(image, points, boxes, params=params)
- self.assert_close(seq.transform_matrix[..., 0, 0], image.new_tensor([4 / 5]))
+ # #5463: in slice mode only height exceeds the padded canvas; resample keeps its warp scaling.
+ scale_w = 1.0 if mode == "slice" else 4 / 5
+ point_x = 3.0 if mode == "slice" else 2.4
+ box_x = (2.0, 3.0) if mode == "slice" else (1.6, 2.4)
+ self.assert_close(seq.transform_matrix[..., 0, 0], image.new_tensor([scale_w]))
self.assert_close(seq.transform_matrix[..., 1, 1], image.new_tensor([6 / 5]))
- self.assert_close(out_points, image.new_tensor([[[2.4, 3.6]]]))
- self.assert_close(out_boxes, image.new_tensor([[[[1.6, 2.4], [2.4, 2.4], [2.4, 3.6], [1.6, 3.6]]]]))
+ self.assert_close(out_points, image.new_tensor([[[point_x, 3.6]]]))
+ self.assert_close(
+ out_boxes,
+ image.new_tensor([[[[box_x[0], 2.4], [box_x[1], 2.4], [box_x[1], 3.6], [box_x[0], 3.6]]]]),
+ )
expected_rows = {
"slice": [
[0.0, 0.0, 0.0, 0.0],
@@ -260,7 +267,8 @@ class TestGeometricCropConventions(BaseTester):
@pytest.mark.parametrize("mode", ["slice", "resample"])
@pytest.mark.parametrize("size", [(10, 10), (10, 4), (4, 10)])
- def test_wart_random_crop_oversized_rescales_both_matrix_axes_4414(self, device, dtype, mode, size):
+ def test_wart_random_crop_oversized_rescales_matrix_axes_4414(self, device, dtype, mode, size):
+ """Resample mode rescales both matrix axes (#4414); slice mode only the oversized one, as its resize (#5463)."""
image = torch.arange(48, device=device, dtype=dtype).reshape(1, 1, 6, 8) / 48
crop = K.RandomCrop(size, cropping_mode=mode, p=1.0)
params = crop.forward_parameters(image.shape)
@@ -270,7 +278,13 @@ class TestGeometricCropConventions(BaseTester):
[[[left, top], [left + w - 1, top], [left + w - 1, top + h - 1], [left, top + h - 1]]]
)
output = crop(image, params=params)
- self.assert_close(crop.transform_matrix, image.new_tensor([[[w / 8, 0, -left], [0, h / 6, -top], [0, 0, 1]]]))
+ needs_scale = h > 6 or w > 8
+ scale_w = (w / 8 if w > 8 else 1.0) if mode == "slice" else (w / 8 if needs_scale else 1.0)
+ scale_h = (h / 6 if h > 6 else 1.0) if mode == "slice" else (h / 6 if needs_scale else 1.0)
+ self.assert_close(
+ crop.transform_matrix,
+ image.new_tensor([[[scale_w, 0, -left], [0, scale_h, -top], [0, 0, 1]]]),
+ )
# Explicit ramp rows distinguish the slice resize from the mis-scaled, zero-padded warp.
rows = {
((10, 10), "slice"): [40, 40.7, 41.5, 42.3, 43.1, 43.9, 44.7, 45.5, 46.3, 47],