π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Validate crop_by_indices shape compensation (#6403)
Vamsi-2581477123906d30
diff --git a/changelog.d/6403.fixed.md b/changelog.d/6403.fixed.mdnew file mode 100644index 000000000..9e33779c8--- /dev/null+++ b/changelog.d/6403.fixed.md@@ -0,0 +1 @@+`crop_by_indices` now rejects unsupported `shape_compensation` values instead of treating them as padding. The legacy `"F.pad"` alias remains supported.diff --git a/kornia/geometry/transform/crop2d.py b/kornia/geometry/transform/crop2d.pyindex 66c892263..3aedbf276 100644--- a/kornia/geometry/transform/crop2d.py+++ b/kornia/geometry/transform/crop2d.py@@ -603,8 +603,8 @@ def crop_by_indices(align_corners: interpolation flag.antialias: if True, then image will be filtered with Gaussian before downscaling.No effect for upscaling.- shape_compensation: if the cropped slice sizes are not exactly align `size`, the image can either be padded- or resized.+ shape_compensation: how to compensate when the cropped slice size differs from `size`: ``'resize'``+ resamples, while ``'pad'`` pads or trims. ``'F.pad'`` is a legacy alias for ``'pad'``.Returns:The cropped torch.Tensor with shape ``(B, C, h, w)``, where@@ -612,7 +612,8 @@ def crop_by_indices(from ``src_box``.Raises:- ValueError: if ``size`` is ``None`` and the boxes differ in size.+ ValueError: if ``shape_compensation`` is not ``'resize'``, ``'pad'`` or ``'F.pad'``, or ``size`` is ``None``+ and the boxes differ in size.See Also:- :func:`crop_and_resize`: resamples any four-corner box, differentiably with respect to its corners.@@ -635,6 +636,10 @@ def crop_by_indices("""KORNIA_CHECK_SHAPE(input_tensor, ["B", "C", "H", "W"])KORNIA_CHECK_SHAPE(src_box, ["B", "4", "2"])+ if shape_compensation not in ("resize", "pad", "F.pad"):+ raise ValueError(+ f"`shape_compensation` must be one of 'resize', 'pad', or 'F.pad'. Got {shape_compensation!r}."+ )B, C, _, _ = input_tensor.shape# Kept on the device ``src_box`` lives on: the coordinates are read back to Python below, which costs no devicediff --git a/tests/geometry/transform/test_crop2d.py b/tests/geometry/transform/test_crop2d.pyindex cced67193..ec1f9e10d 100644--- a/tests/geometry/transform/test_crop2d.py+++ b/tests/geometry/transform/test_crop2d.py@@ -834,6 +834,22 @@ class TestCropByIndices(BaseTester):with pytest.raises(ValueError, match="All boxes in the batch must have the same height and width"):kornia.geometry.transform.crop_by_indices(img, src_box, size=None)+ @pytest.mark.parametrize("shape_compensation", ["resise", "unknown"])+ def test_crop_by_indices_rejects_invalid_shape_compensation_6402(self, shape_compensation, device, dtype):+ inp = torch.rand(1, 1, 4, 4, device=device, dtype=dtype)+ src_box = torch.tensor([[[0, 0], [2, 0], [2, 2], [0, 2]]], device=device, dtype=torch.int64)++ with pytest.raises(ValueError, match=r"shape_compensation.*resize.*pad.*F\.pad"):+ kornia.geometry.transform.crop_by_indices(inp, src_box, size=(2, 2), shape_compensation=shape_compensation)++ def test_crop_by_indices_accepts_legacy_f_pad_shape_compensation_6402(self, device, dtype):+ inp = torch.arange(16.0, device=device, dtype=dtype).view(1, 1, 4, 4)+ src_box = torch.tensor([[[0, 0], [2, 0], [2, 2], [0, 2]]], device=device, dtype=torch.int64)++ actual = kornia.geometry.transform.crop_by_indices(inp, src_box, size=(4, 4), shape_compensation="F.pad")+ expected = torch.nn.functional.pad(inp[..., :3, :3], [0, 1, 0, 1])+ self.assert_close(actual, expected, atol=0.0, rtol=0.0)+def test_convention_shape_compensation_pad_vs_resize(self, device, dtype):# shape_compensation is pinned per the crop_by_indices Convention block: it applies# whenever the cropped slice does not match `size`, whether or not src_box is identical