π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry): raise clear error in crop_by_indices for mismatched box sizes (#3777)
Dharshika Pugalenthia939a7bb1fe6
diff --git a/kornia/geometry/transform/crop2d.py b/kornia/geometry/transform/crop2d.pyindex 1ec96ac05..c20802755 100644--- a/kornia/geometry/transform/crop2d.py+++ b/kornia/geometry/transform/crop2d.py@@ -365,7 +365,12 @@ def crop_by_indices(if size is None:h, w = infer_bbox_shape(src)- size = h.unique(sorted=False), w.unique(sorted=False)+ if B > 0 and ((h != h[0]).any() | (w != w[0]).any()).item():+ raise ValueError(+ "All boxes in the batch must have the same height and width when `size` is None. "+ "Please pass `size` explicitly when box dimensions vary across the batch."+ )+ size = (int(h[0].item()), int(w[0].item())) if B > 0 else (0, 0)out = torch.empty(B, C, *size, device=input_tensor.device, dtype=input_tensor.dtype)# Find out the cropped shapes that need to be resized.for i in range(B):diff --git a/tests/geometry/transform/test_crop2d.py b/tests/geometry/transform/test_crop2d.pyindex 0a27d82cd..3d2c757f4 100644--- a/tests/geometry/transform/test_crop2d.py+++ b/tests/geometry/transform/test_crop2d.py@@ -303,6 +303,20 @@ class TestCropByIndices(BaseTester):expected = op(img, torch.tensor([[[0, 0], [1, 0], [1, 1], [0, 1]]]))self.assert_close(actual, expected, rtol=1e-4, atol=1e-4)+ def test_crop_by_indices_variable_sizes_exception(self, device, dtype):+ img = torch.rand(2, 3, 20, 20, device=device, dtype=dtype)+ src_box = torch.tensor(+ [+ [[0, 0], [4, 0], [4, 4], [0, 4]], # 5x5 box+ [[0, 0], [9, 0], [9, 9], [0, 9]], # 10x10 box+ ],+ dtype=dtype,+ device=device,+ )++ 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)+class TestCropSizeValidation:"""Tests that crop functions properly reject invalid size arguments."""