π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(augmentation): include padding in crop transforms (#4588)
Dex Hunter8c71df9a0a31
diff --git a/changelog.d/4588.fixed.md b/changelog.d/4588.fixed.mdnew file mode 100644index 000000000..1d587315b--- /dev/null+++ b/changelog.d/4588.fixed.md@@ -0,0 +1 @@+RandomCrop now uses the effective pre-crop canvas for oversized requests. With `RandomCrop((10, 10), padding=1)` on a 3-by-3 input, the scale changes from `10/3` to `10/5`; the no-padding behavior tracked in #4414 is unchanged.diff --git a/kornia/augmentation/_2d/geometric/crop.py b/kornia/augmentation/_2d/geometric/crop.pyindex 03574c83b..891932231 100644--- a/kornia/augmentation/_2d/geometric/crop.py+++ b/kornia/augmentation/_2d/geometric/crop.py@@ -89,10 +89,11 @@ class RandomCrop(GeometricAugmentationBase2D):With ``pad_if_needed=False``, an oversized request does not raise. Slice mode resizes the available sliceto the requested size. Resample mode instead uses a mis-scaled warp that can blend in zero padding; wheneither axis is oversized, both matrix axes are rescaled, including an axis that would fit. This wart is- tracked in `#4414 <https://github.com/kornia/kornia/issues/4414>`_. The same correction compares against the- unpadded input even when explicit padding makes the crop fit: slice-mode images then disagree with the- matrix-transformed keypoints and boxes, and resample-mode images are also distorted. This explicit-padding- defect is tracked in `#4542 <https://github.com/kornia/kornia/issues/4542>`_.+ tracked in `#4414 <https://github.com/kornia/kornia/issues/4414>`_. With explicit padding, the transform+ dimensions include the pre-crop padded canvas, so a crop that fits after padding avoids a spurious scale+ correction while retaining its sampled translation. The no-padding oversized behavior tracked in #4414 remains+ unchanged. With explicit padding, ``RandomCrop((10, 10), padding=1)`` on a 3-by-3 input scales against the+ padded canvas, changing ``10/3`` to ``10/5``.Slice mode calls ``crop_by_indices`` with thatfunction's bilinear/``align_corners=None`` defaults, ignoring this class's ``resample`` and@@ -201,13 +202,37 @@ class RandomCrop(GeometricAugmentationBase2D):dst = params["dst"].to(input)transform: torch.Tensor = get_perspective_transform(src, dst)- # Fast scaling correction when output exceeds input and padding disabled- if not flags.get("pad_if_needed", False):+ # Scale against the canvas represented by the effective replay parameters.+ # During export, retain the static-shape path rather than reading padding_size back to host.+ padding_size = params.get("padding_size")+ if is_exporting() or not isinstance(padding_size, torch.Tensor):h, w = input.shape[-2:]+ padding = self.compute_padding(tuple(input.shape))+ h += padding[2] + padding[3]+ w += padding[0] + padding[1]h_out, w_out = flags["size"]if h_out > h or w_out > w:transform[:, 0, 0] *= w_out / wtransform[:, 1, 1] *= h_out / h+ return transform++ padding_size = padding_size.to(device=input.device)+ padded_h = input.shape[-2] + padding_size[:, 2] + padding_size[:, 3]+ padded_w = input.shape[-1] + padding_size[:, 0] + padding_size[:, 1]+ h_out, w_out = flags["size"]+ needs_scale = (h_out > padded_h) | (w_out > padded_w)+ scale_w = torch.where(+ 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,+ torch.full_like(padded_h, h_out, dtype=transform.dtype) / padded_h.to(dtype=transform.dtype),+ torch.ones_like(padded_h, dtype=transform.dtype),+ )+ transform[:, 0, 0] *= scale_w+ transform[:, 1, 1] *= scale_hreturn transformraise NotImplementedError(f"Not supported type: {flags['cropping_mode']}.")diff --git a/tests/augmentation/test_conventions_geometric_crop.py b/tests/augmentation/test_conventions_geometric_crop.pyindex 35cfae34c..45d97d6e5 100644--- a/tests/augmentation/test_conventions_geometric_crop.py+++ b/tests/augmentation/test_conventions_geometric_crop.py@@ -116,7 +116,7 @@ class TestGeometricCropConventions(BaseTester):assert any(not gate.any() for gate in gates)@pytest.mark.parametrize("mode", ["slice", "resample"])- def test_wart_random_crop_explicit_padding_scales_matrix_4542(self, device, dtype, mode):+ def test_random_crop_explicit_padding_preserves_matrix_4542(self, device, dtype, mode):image = torch.arange(9, device=device, dtype=dtype).reshape(1, 1, 3, 3) / 8crop = K.RandomCrop((4, 4), padding=1, cropping_mode=mode, p=1.0)seq = K.AugmentationSequential(crop, data_keys=["input", "keypoints", "bbox"])@@ -125,17 +125,115 @@ class TestGeometricCropConventions(BaseTester):points = image.new_tensor([[[2, 2]]])boxes = image.new_tensor([[[[1, 1], [2, 1], [2, 2], [1, 2]]]])output, out_points, out_boxes = seq(image, points, boxes, params=params)- self.assert_close(crop.transform_matrix, image.new_tensor([[[4 / 3, 0, 0], [0, 4 / 3, 0], [0, 0, 1]]]))- self.assert_close(out_points, image.new_tensor([[[4, 4]]]))- self.assert_close(out_boxes, (boxes + 1) * (4 / 3))- # Slice mode puts the original (2, 2) pixel at (3, 3); resampling also distorts its value.- expected = (- [[0, 0, 0, 0], [0, 0, 1, 2], [0, 3, 4, 5], [0, 6, 7, 8]]- if mode == "slice"- else [[0, 0, 0, 0], [0, 0, 0.375, 0.9375], [0, 1.125, 2, 2.75], [0, 2.8125, 4.25, 5]]- )+ self.assert_close(crop.transform_matrix, image.new_tensor([[[1, 0, 0], [0, 1, 0], [0, 0, 1]]]))+ self.assert_close(out_points, image.new_tensor([[[3, 3]]]))+ self.assert_close(out_boxes, boxes + 1)+ expected = [[0, 0, 0, 0], [0, 0, 1, 2], [0, 3, 4, 5], [0, 6, 7, 8]]self.assert_close(output, image.new_tensor(expected).reshape(1, 1, 4, 4) / 8)+ @pytest.mark.parametrize("mode", ["slice", "resample"])+ def test_random_crop_explicit_asymmetric_padding_replays_and_skips_4542(self, device, dtype, mode):+ image = torch.arange(9, device=device, dtype=dtype).reshape(1, 1, 3, 3) / 8+ padding = (2, 1, 1, 2)+ crop = K.RandomCrop((4, 4), padding=padding, cropping_mode=mode, p=1.0)+ seq = K.AugmentationSequential(crop, data_keys=["input", "keypoints", "bbox"])+ params = seq.forward_parameters(image.shape)+ params[0].data["src"] = image.new_tensor([[[0, 0], [3, 0], [3, 3], [0, 3]]])+ points = image.new_tensor([[[2, 2]]])+ boxes = image.new_tensor([[[[1, 1], [2, 1], [2, 2], [1, 2]]]])+ output, out_points, out_boxes = seq(image, points, boxes, params=params)+ expected = image.new_tensor([[0, 0, 0, 0], [0, 0, 0, 1], [0, 0, 3, 4], [0, 0, 6, 7]]).reshape(1, 1, 4, 4) / 8+ self.assert_close(crop.transform_matrix, image.new_tensor([[[1, 0, 0], [0, 1, 0], [0, 0, 1]]]))+ self.assert_close(output, expected)+ self.assert_close(out_points, image.new_tensor([[[4, 3]]]))+ self.assert_close(out_boxes, boxes + image.new_tensor([2, 1]))+ replay, replay_points, replay_boxes = seq(image, points, boxes, params=params)+ self.assert_close(replay, output)+ self.assert_close(replay_points, out_points)+ self.assert_close(replay_boxes, out_boxes)++ skip = K.AugmentationSequential(+ K.RandomCrop((4, 4), padding=padding, cropping_mode=mode, p=0.0),+ data_keys=["input", "keypoints", "bbox"],+ )+ skipped, skipped_points, skipped_boxes = skip(image, points, boxes)+ self.assert_close(skipped, image)+ self.assert_close(skipped_points, points)+ self.assert_close(skipped_boxes, boxes)++ @pytest.mark.parametrize("mode", ["slice", "resample"])+ def test_random_crop_explicit_padding_replay_uses_stored_canvas_under_flag_overrides(self, device, dtype, mode):+ image = torch.arange(9, device=device, dtype=dtype).reshape(1, 1, 3, 3) / 8+ crop = K.RandomCrop((4, 4), padding=1, cropping_mode=mode, p=1.0)+ params = crop.forward_parameters(image.shape)+ params["src"] = image.new_tensor([[[0, 0], [3, 0], [3, 3], [0, 3]]])+ crop.flags["padding"] = 0+ output = crop(image, params=params)+ self.assert_close(crop.transform_matrix, image.new_tensor([[[1, 0, 0], [0, 1, 0], [0, 0, 1]]]))+ expected = image.new_tensor([[[[0, 0, 0, 0], [0, 0, 1, 2], [0, 3, 4, 5], [0, 6, 7, 8]]]]) / 8+ self.assert_close(output, expected)++ @pytest.mark.parametrize("mode", ["slice", "resample"])+ def test_random_crop_explicit_padding_recomputes_static_canvas_without_saved_padding(self, device, dtype, mode):+ image = torch.arange(9, device=device, dtype=dtype).reshape(1, 1, 3, 3) / 8+ crop = K.RandomCrop((4, 4), padding=1, cropping_mode=mode, p=1.0)+ params = crop.forward_parameters(image.shape)+ params["src"] = image.new_tensor([[[0, 0], [3, 0], [3, 3], [0, 3]]])+ params.pop("padding_size")+ output = crop(image, params=params)+ self.assert_close(crop.transform_matrix, image.new_tensor([[[1, 0, 0], [0, 1, 0], [0, 0, 1]]]))+ expected = image.new_tensor([[[[0, 0, 0, 0], [0, 0, 1, 2], [0, 3, 4, 5], [0, 6, 7, 8]]]]) / 8+ self.assert_close(output, expected)++ @pytest.mark.parametrize("mode", ["slice", "resample"])+ def test_random_crop_explicit_padding_partial_fit_uses_padded_canvas_4542(self, device, dtype, mode):+ image = torch.arange(9, device=device, dtype=dtype).reshape(1, 1, 3, 3) / 8+ points = image.new_tensor([[[2, 2]]])+ boxes = image.new_tensor([[[[1, 1], [2, 1], [2, 2], [1, 2]]]])+ crop = K.RandomCrop((6, 4), padding=1, cropping_mode=mode, p=1.0)+ seq = K.AugmentationSequential(crop, data_keys=["input", "keypoints", "bbox"])+ params = seq.forward_parameters(image.shape)+ 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]))+ 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]]]]))+ expected_rows = {+ "slice": [+ [0.0, 0.0, 0.0, 0.0],+ [0.0, 0.0, 0.09375, 0.1875],+ [0.0, 0.21875, 0.34375, 0.46875],+ [0.0, 0.53125, 0.65625, 0.78125],+ [0.0, 0.5625, 0.65625, 0.75],+ [0.0, 0.0, 0.0, 0.0],+ ],+ "resample": [+ [0.0, 0.0, 0.0, 0.0],+ [0.0, 5 / 192, 0.15625, 5 / 96],+ [0.0, 0.28125, 0.4375, 0.125],+ [0.0, 0.59375, 0.75, 0.203125],+ [0.0, 25 / 48, 0.625, 1 / 6],+ [0.0, 0.0, 0.0, 0.0],+ ],+ }+ if dtype == torch.float16 and mode == "resample":+ # Captured from the published corrected implementation on CPU/PyTorch 2.9.1; the matrix remains+ # independently pinned.+ expected_rows["resample"] = [+ [0.0, 0.0, 0.0, 0.0],+ [0.0, 0.0260009765625, 0.15625, 0.051605224609375],+ [0.0, 0.281005859375, 0.4375, 0.1239013671875],+ [0.0, 0.59375, 0.75, 0.2015380859375],+ [0.0, 0.5205078125, 0.62451171875, 0.1651611328125],+ [0.0, 0.0, 0.0, 0.0],+ ]+ expected = image.new_tensor(expected_rows[mode]).reshape(1, 1, 6, 4)+ self.assert_close(output, expected)+ self.assert_close(output[0, 0, 0], image.new_tensor([0, 0, 0, 0]))+ assert output.shape == (1, 1, 6, 4)+@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):