Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Return boxes tensor directly if no boxes (#2196)

Miquel Martí8316ccf81947
diff --git a/kornia/geometry/boxes.py b/kornia/geometry/boxes.py
index 1b5c2c3ff..31da4e1e6 100644
--- a/kornia/geometry/boxes.py
+++ b/kornia/geometry/boxes.py
@@ -42,6 +42,8 @@ def _transform_boxes(boxes: torch.Tensor, M: torch.Tensor) -> torch.Tensor:
# Work with batch as kornia.transform_points only supports a batch of points.
boxes_per_batch, n_points_per_box, coordinates_dimension = boxes.shape[-3:]
+ if boxes_per_batch == 0:
+ return boxes
points = boxes.view(-1, n_points_per_box * boxes_per_batch, coordinates_dimension)
M = M if M.ndim == 3 else M.unsqueeze(0)
diff --git a/test/augmentation/test_container.py b/test/augmentation/test_container.py
index 59e26b7e1..1ebd38d72 100644
--- a/test/augmentation/test_container.py
+++ b/test/augmentation/test_container.py
@@ -447,26 +447,40 @@ class TestAugmentationSequential:
assert out_inv[3].shape == points.shape
assert_close(out_inv[3], points, atol=1e-4, rtol=1e-4)
- def test_bbox(self, device, dtype):
+ @pytest.mark.parametrize(
+ 'bbox',
+ [
+ [
+ torch.tensor([[1, 5, 2, 7], [0, 3, 9, 9]]),
+ torch.tensor([[1, 5, 2, 7], [0, 3, 9, 9], [0, 5, 8, 7]]),
+ torch.empty((0, 4)),
+ ],
+ torch.empty((3, 0, 4)),
+ torch.tensor([[[1, 5, 2, 7], [0, 3, 9, 9]], [[1, 5, 2, 7], [0, 3, 9, 9]], [[0, 5, 8, 7], [0, 2, 5, 5]]]),
+ ],
+ )
+ @pytest.mark.parametrize(
+ 'augmentation', [K.RandomCrop((30, 30), padding=1, cropping_mode='resample', fill=0), K.Resize((30, 30))]
+ )
+ def test_bbox(self, bbox, augmentation, device, dtype):
img = torch.rand((3, 3, 10, 10), device=device, dtype=dtype)
- bbox = [
- torch.tensor([[1, 5, 2, 7], [0, 3, 9, 9]], device=device, dtype=dtype),
- torch.tensor([[1, 5, 2, 7], [0, 3, 9, 9], [0, 5, 8, 7]], device=device, dtype=dtype),
- torch.empty((0, 4), device=device, dtype=dtype),
- ]
+ if isinstance(bbox, list):
+ for i, b in enumerate(bbox):
+ bbox[i] = b.to(device=device, dtype=dtype)
+ else:
+ bbox = bbox.to(device=device, dtype=dtype)
inputs = [img, bbox]
- aug = K.AugmentationSequential(K.Resize((30, 30)), data_keys=['input', 'bbox_xyxy'])
+ aug = K.AugmentationSequential(augmentation, data_keys=['input', 'bbox_xyxy'])
transformed = aug(*inputs)
assert len(transformed) == len(inputs)
bboxes_transformed = transformed[-1]
- assert len(bboxes_transformed) == len(bbox) and isinstance(bboxes_transformed, (list,))
- assert len(bboxes_transformed[0]) == 2
- assert len(bboxes_transformed[1]) == 3, bboxes_transformed[1]
- assert len(bboxes_transformed[2]) == 0
+ assert len(bboxes_transformed) == len(bbox) and bboxes_transformed.__class__ == bbox.__class__
+ for i in range(len(bbox)):
+ assert len(bboxes_transformed[i]) == len(bbox[i])
@pytest.mark.parametrize('random_apply', [1, (2, 2), (1, 2), (2,), 10, True, False])
def test_forward_and_inverse(self, random_apply, device, dtype):