π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(augmentation)!: stretch slice-mode RandomCrop annotations on the half-pixel grid (#5487)
εΊζ’η176b3f576949
diff --git a/changelog.d/5487.breaking.md b/changelog.d/5487.breaking.mdnew file mode 100644index 000000000..b5cfa3dee--- /dev/null+++ b/changelog.d/5487.breaking.md@@ -0,0 +1,5 @@+`RandomCrop(cropping_mode="slice")` now places bounding boxes and keypoints on the half-pixel grid of the slice resize+when the requested crop exceeds the padded input along an axis, `x' = (x + 0.5) * s - 0.5` for the stretch `s` (#5481).+Previously the transform matrix scaled about the origin, `x' = s * x`, so annotations sat `0.5 * (s - 1)` pixels before+the image content along that axis: 0.132 pixels at a 416 / 329 stretch and 0.5 pixels at a 2x stretch. Axes that fit,+resample mode and the image itself are unchanged.diff --git a/kornia/augmentation/_2d/geometric/crop.py b/kornia/augmentation/_2d/geometric/crop.pyindex e31208395..2c1c2a263 100644--- a/kornia/augmentation/_2d/geometric/crop.py+++ b/kornia/augmentation/_2d/geometric/crop.py@@ -90,8 +90,9 @@ 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>`_). 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.+ which the request exceeds the canvas, as its resize does, and on the resize's half-pixel grid:+ ``x' = (x + 0.5) * W_out / W_in - 0.5`` along a stretched axis (likewise for ``y``). 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 thisclass's ``resample`` and ``align_corners``. Resample mode uses the configured interpolation and@@ -229,10 +230,13 @@ class RandomCrop(GeometricAugmentationBase2D):w += padding[0] + padding[1]h_out, w_out = flags["size"]if flags["cropping_mode"] == "slice":+ # The slice resize of an oversized axis is on the half-pixel grid: x' = (x + 0.5) * scale - 0.5.if w_out > w:transform[:, 0, 0] *= w_out / w+ transform[:, 0, 2] += (w_out / w - 1) / 2if h_out > h:transform[:, 1, 1] *= h_out / h+ transform[:, 1, 2] += (h_out / h - 1) / 2elif h_out > h or w_out > w:transform[:, 0, 0] *= w_out / wtransform[:, 1, 1] *= h_out / h@@ -255,6 +259,9 @@ class RandomCrop(GeometricAugmentationBase2D):)transform[:, 0, 0] *= scale_wtransform[:, 1, 1] *= scale_h+ if flags["cropping_mode"] == "slice":+ transform[:, 0, 2] += (scale_w - 1) / 2+ transform[:, 1, 2] += (scale_h - 1) / 2return transformraise NotImplementedError(f"Not supported type: {flags['cropping_mode']}.")diff --git a/tests/augmentation/container/test_random_crop.py b/tests/augmentation/container/test_random_crop.pyindex 3303b89c0..b9da7cadb 100644--- a/tests/augmentation/container/test_random_crop.py+++ b/tests/augmentation/container/test_random_crop.py@@ -44,6 +44,46 @@ class TestRandomCropAnnotations(BaseTester):self.assert_close(out_boxes[0, 0, [0, 2]], boxes[0, 0, [0, 2]] - x_offset)+ @pytest.mark.parametrize(+ ("input_size", "size"),+ [((5, 12), (10, 8)), ((12, 5), (8, 10)), ((5, 6), (10, 9))],+ ids=["height", "width", "both"],+ )+ def test_slice_crop_annotations_sit_on_the_stretched_pixels_5481(self, input_size, size, device, dtype):+ """Sampling the output image at a transformed point must give back the point's source coordinates."""+ height, width = input_size+ ys, xs = torch.meshgrid(+ torch.arange(height, device=device, dtype=dtype),+ torch.arange(width, device=device, dtype=dtype),+ indexing="ij",+ )+ ramp = torch.stack([xs, ys])[None] # each pixel stores its own source (x, y)+ seq = K.AugmentationSequential(+ K.RandomCrop(size, p=1.0, cropping_mode="slice"), data_keys=["input", "keypoints", "bbox_xyxy"]+ )+ h, w = size+ # An oversized axis starts at 0 and is stretched; an axis that fits is cropped, here from 1.+ x0, y0 = float(w < width), float(h < height)+ x1, y1 = x0 + min(w, width) - 1, y0 + min(h, height) - 1+ params = seq.forward_parameters(ramp.shape)+ params[0].data["src"] = ramp.new_tensor(+ [[[x0, y0], [x0 + w - 1, y0], [x0 + w - 1, y0 + h - 1], [x0, y0 + h - 1]]]+ )+ points = ramp.new_tensor([[[x0 + 1, y0 + 1], [x1 - 1, y1 - 1]]])+ boxes = points.view(1, 1, 4)++ out, out_points, out_boxes = seq(ramp, points, boxes, params=params)++ self.assert_close(out_boxes[0, 0].view(2, 2), out_points[0])+ # The stored coordinates are separable, so read x along the first row and y down the first column.+ x_of_column, y_of_row = out[0, 0, 0], out[0, 1, :, 0]+ for (x, y), (px, py) in zip(points[0].tolist(), out_points[0].tolist()):+ assert 0 < px < size[1] - 1 and 0 < py < size[0] - 1 # inside the rows and columns the resize clamps+ x_lo, y_lo = int(px // 1), int(py // 1)+ sampled_x = torch.lerp(x_of_column[x_lo], x_of_column[x_lo + 1], px - x_lo)+ sampled_y = torch.lerp(y_of_row[y_lo], y_of_row[y_lo + 1], py - y_lo)+ self.assert_close(torch.stack((sampled_x, sampled_y)), ramp.new_tensor([x, y]), low_tolerance=True)+@staticmethoddef 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.pyindex 340f20654..ef5b98f09 100644--- a/tests/augmentation/test_augmentation.py+++ b/tests/augmentation/test_augmentation.py@@ -3640,6 +3640,34 @@ class TestRandomCrop(BaseTester):torch.diag(torch.tensor(expected_scale, device=device, dtype=dtype)),)+ @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)),+ ((5, 6), (10, 9), (1.5, 2.0)),+ ((500, 500), (416, 416), (1.0, 1.0)),+ ],+ )+ def test_slice_crop_transform_stretches_on_the_half_pixel_grid(+ self, input_size, size, expected_scale, exporting, device, dtype, monkeypatch+ ):+ """A stretched axis maps x to (x + 0.5) * scale - 0.5, as the slice resize does; a cropped one to x - x0."""+ 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)++ scale = torch.tensor(expected_scale, device=device, dtype=dtype)+ expected = torch.diag_embed(torch.cat((scale, scale.new_ones(1))))+ expected[:2, 2] = (scale - 1) / 2 - params["src"][0, 0].to(scale)+ self.assert_close(transform[0], expected)+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.pyindex dcc706dc9..3306b6496 100644--- a/tests/augmentation/test_conventions_geometric_crop.py+++ b/tests/augmentation/test_conventions_geometric_crop.py@@ -224,15 +224,19 @@ class TestGeometricCropConventions(BaseTester):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)# #5463: in slice mode only height exceeds the padded canvas; resample keeps its warp scaling.+ # #5481: the slice stretch is on the half-pixel grid, y' = (y + 0.5) * 6 / 5 - 0.5.scale_w = 1.0 if mode == "slice" else 4 / 5- point_x = 3.0 if mode == "slice" else 2.4+ point = (3.0, 3.7) if mode == "slice" else (2.4, 3.6)box_x = (2.0, 3.0) if mode == "slice" else (1.6, 2.4)+ box_y = (2.5, 3.7) if mode == "slice" else (2.4, 3.6)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([[[point_x, 3.6]]]))+ self.assert_close(out_points, image.new_tensor([[point]]))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]]]]),+ image.new_tensor(+ [[[[box_x[0], box_y[0]], [box_x[1], box_y[0]], [box_x[1], box_y[1]], [box_x[0], box_y[1]]]]]+ ),)expected_rows = {"slice": [@@ -268,7 +272,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_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)."""+ """Resample mode rescales both matrix axes (#4414); slice mode only the oversized one, as its resize (#5463),+ on the resize's half-pixel grid (#5481)."""image = torch.arange(48, device=device, dtype=dtype).reshape(1, 1, 6, 8) / 48crop = K.RandomCrop(size, cropping_mode=mode, p=1.0)params = crop.forward_parameters(image.shape)@@ -281,9 +286,11 @@ class TestGeometricCropConventions(BaseTester):needs_scale = h > 6 or w > 8scale_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)+ shift_x = (scale_w - 1) / 2 if mode == "slice" else 0.0+ shift_y = (scale_h - 1) / 2 if mode == "slice" else 0.0self.assert_close(crop.transform_matrix,- image.new_tensor([[[scale_w, 0, -left], [0, scale_h, -top], [0, 0, 1]]]),+ image.new_tensor([[[scale_w, 0, shift_x - left], [0, scale_h, shift_y - top], [0, 0, 1]]]),)# Explicit ramp rows distinguish the slice resize from the mis-scaled, zero-padded warp.rows = {