Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): transform_points returns empty unchanged for 0 points (#3855)

Edgar Ribac783ce076bc2
diff --git a/kornia/geometry/linalg.py b/kornia/geometry/linalg.py
index 7e14f4c6f..0c8d5875a 100644
--- a/kornia/geometry/linalg.py
+++ b/kornia/geometry/linalg.py
@@ -209,6 +209,12 @@ def transform_points(trans_01: torch.Tensor, points_1: torch.Tensor) -> torch.Te
if not trans_01.shape[-1] == (points_1.shape[-1] + 1):
raise ValueError(f"Last input dimensions must differ by one unit Got{trans_01} and {points_1}")
+ # No points to transform (e.g. an image chip with no annotations): transforming an empty set
+ # yields the same empty set. Return early β€” the reshape below cannot infer ``-1`` from a
+ # 0-element tensor, so this also avoids a spurious crash on valid empty inputs.
+ if points_1.shape[-2] == 0:
+ return points_1
+
# We reshape to BxNxD in case we get more dimensions, e.g., MxBxNxD
shape_inp = list(points_1.shape)
points_1 = points_1.reshape(-1, points_1.shape[-2], points_1.shape[-1])
diff --git a/tests/geometry/test_linalg.py b/tests/geometry/test_linalg.py
index a0d7ef116..83375bd9e 100644
--- a/tests/geometry/test_linalg.py
+++ b/tests/geometry/test_linalg.py
@@ -49,6 +49,16 @@ class TestTransformPoints(BaseTester):
atol = 1e-3 if (device.type == "cuda" and dtype == torch.float32) else 1e-4
self.assert_close(points_src, points_dst_to_src, atol=atol, rtol=1e-4)
+ @pytest.mark.parametrize("num_dims", [2, 3])
+ def test_transform_points_empty(self, num_dims, device, dtype):
+ # No points to transform (e.g. an image chip with no annotations) must return an empty
+ # tensor of the same shape rather than crashing on the internal reshape.
+ points = torch.zeros(2, 0, num_dims, device=device, dtype=dtype)
+ trans = torch.eye(num_dims + 1, device=device, dtype=dtype).expand(2, -1, -1)
+ out = kgl.transform_points(trans, points)
+ assert out.shape == points.shape
+ self.assert_close(out, points)
+
def test_gradcheck(self, device):
# generate input data
batch_size, num_points, num_dims = 2, 3, 2