Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): support unbatched keypoints in Keypoints.pad and unpad (#5051)

Shiven Solanki20e0f210c7a1
diff --git a/changelog.d/5051.fixed.md b/changelog.d/5051.fixed.md
new file mode 100644
index 000000000..23e043660
--- /dev/null
+++ b/changelog.d/5051.fixed.md
@@ -0,0 +1 @@
+`Keypoints.pad` and `Keypoints.unpad` accept the unbatched `(N, 2)` container the class documents and constructs. Both added the `(B, 1)` padding column to the `(N,)` coordinate view in place, which broadcast to `(1, N)` and raised `RuntimeError: output with shape [N] doesn't match the broadcast shape [1, N]`, so `RandomCrop` failed on `(N, 2)` keypoints with and without `padding`. They now shape the padding to the container, as `Boxes.pad` does since #4372, and match the singleton-batch result; an unbatched container carries one image, so a padding with more than one row is rejected. `padding_size` is also moved to the keypoints' device. Batched results are unchanged (closes #5021).
diff --git a/kornia/geometry/keypoints.py b/kornia/geometry/keypoints.py
index d22840fa6..9c02d4181 100644
--- a/kornia/geometry/keypoints.py
+++ b/kornia/geometry/keypoints.py
@@ -142,8 +142,28 @@ class Keypoints:
obj._data = _data
return obj
+ def _broadcast_over_points(self, values: torch.torch.Tensor) -> torch.torch.Tensor:
+ """Shape a per-image ``(B, 1)`` column so it broadcasts over ``self._data[..., i]``.
+
+ The batched container indexes as ``(B, N)``, which a ``(B, 1)`` column already broadcasts over. The
+ unbatched ``(N, 2)`` form carries a single implicit image and indexes as ``(N,)``, so the column must
+ drop its batch axis, otherwise the in-place update would broadcast to ``(1, N)``.
+ """
+ if self._is_batched:
+ return values
+ if values.size(0) != 1:
+ raise RuntimeError(
+ f"Unbatched (N, 2) keypoints carry a single image, so a per-image tensor must have one row. "
+ f"Got {values.size(0)}."
+ )
+ return values[0]
+
def pad(self, padding_size: torch.torch.Tensor) -> "Keypoints":
- """Pad a bounding keypoints.
+ """Pad the keypoints in place.
+
+ ``padding_size`` is ordered as ``(left, right, top, bottom)``. Only ``left`` and ``top`` shift the
+ coordinate origin. Both the batched :math:`(B, N, 2)` and the unbatched :math:`(N, 2)` container are
+ supported; the unbatched form carries a single image, so ``padding_size`` must have exactly one row.
Args:
padding_size: (B, 4)
@@ -151,12 +171,15 @@ class Keypoints:
"""
if not (len(padding_size.shape) == 2 and padding_size.size(1) == 4):
raise RuntimeError(f"Expected padding_size as (B, 4). Got {padding_size.shape}.")
- self._data[..., 0] += padding_size[..., :1] # left padding
- self._data[..., 1] += padding_size[..., 2:3] # top padding
+ offset = padding_size.to(device=self._data.device)
+ self._data[..., 0] += self._broadcast_over_points(offset[..., :1]) # left padding
+ self._data[..., 1] += self._broadcast_over_points(offset[..., 2:3]) # top padding
return self
def unpad(self, padding_size: torch.torch.Tensor) -> "Keypoints":
- """Pad a bounding keypoints.
+ """Undo :meth:`pad` in place.
+
+ Accepts the same batched and unbatched containers and ``padding_size`` layout as :meth:`pad`.
Args:
padding_size: (B, 4)
@@ -164,8 +187,9 @@ class Keypoints:
"""
if not (len(padding_size.shape) == 2 and padding_size.size(1) == 4):
raise RuntimeError(f"Expected padding_size as (B, 4). Got {padding_size.shape}.")
- self._data[..., 0] -= padding_size[..., :1] # left padding
- self._data[..., 1] -= padding_size[..., 2:3] # top padding
+ offset = padding_size.to(device=self._data.device)
+ self._data[..., 0] -= self._broadcast_over_points(offset[..., :1]) # left padding
+ self._data[..., 1] -= self._broadcast_over_points(offset[..., 2:3]) # top padding
return self
def transform_keypoints(self, M: torch.torch.Tensor, inplace: bool = False) -> "Keypoints":
diff --git a/tests/augmentation/container/test_augmentation_sequential.py b/tests/augmentation/container/test_augmentation_sequential.py
index 86c355c04..aa2c71567 100644
--- a/tests/augmentation/container/test_augmentation_sequential.py
+++ b/tests/augmentation/container/test_augmentation_sequential.py
@@ -245,6 +245,26 @@ class TestAugmentationSequential:
assert out_bbox.shape == (batch_size, 1, 4)
assert torch.isfinite(out_bbox).all()
+ @pytest.mark.parametrize("padding", [None, 2])
+ def test_random_crop_accepts_unbatched_keypoints_5021(self, padding, device, dtype):
+ # kornia#5021: RandomCrop routes keypoints through Keypoints.pad, with or without padding. A
+ # rank-2 (N, 2) keypoints tensor for a single image builds an *unbatched* Keypoints container,
+ # which pad crashed on with "output with shape [2] doesn't match the broadcast shape [1, 2]".
+ # The same crop on the singleton-batch (1, N, 2) keypoints always worked and is the reference.
+ input = torch.rand(1, 1, 7, 11, device=device, dtype=dtype)
+ keypoints = torch.tensor([[8.0, 2.0], [3.0, 5.0]], device=device, dtype=dtype)
+ aug = K.AugmentationSequential(K.RandomCrop((5, 9), padding=padding, p=1.0), data_keys=["input", "keypoints"])
+
+ torch.manual_seed(0)
+ _, expected = aug(input, keypoints[None])
+ torch.manual_seed(0)
+ out_input, out_keypoints = aug(input, keypoints)
+
+ assert out_input.shape == (1, 1, 5, 9)
+ # the rank of the caller's keypoints is preserved on the way out
+ assert out_keypoints.shape == (2, 2)
+ assert_close(out_keypoints, expected[0])
+
def test_random_crops_and_flips(self, device, dtype):
width, height = 100, 100
crop_width, crop_height = 3, 3
diff --git a/tests/geometry/test_keypoints.py b/tests/geometry/test_keypoints.py
index 81c82bb3b..4734cae34 100644
--- a/tests/geometry/test_keypoints.py
+++ b/tests/geometry/test_keypoints.py
@@ -132,6 +132,33 @@ class TestKeypoints(BaseTester):
self.assert_close(kp.data[0, :, 0], torch.full((4,), 4.0, device=device, dtype=dtype))
self.assert_close(kp.data[0, :, 1], torch.full((4,), 3.0, device=device, dtype=dtype))
+ def test_pad_unpad_unbatched_5021(self, device, dtype):
+ # kornia#5021: an unbatched (N, 2) container indexes as (N,), so the (1, 1) padding column
+ # broadcast the in-place update to (1, N) and raised "output with shape [2] doesn't match the
+ # broadcast shape [1, 2]". The result must match the singleton-batch container.
+ data = torch.tensor([[8.0, 2.0], [3.0, 5.0]], device=device, dtype=dtype)
+ padding = torch.tensor([[3.0, 100.0, 7.0, 1000.0]], device=device, dtype=dtype)
+
+ padded = Keypoints(data.clone()).pad(padding)
+ self.assert_close(padded.data, torch.tensor([[11.0, 9.0], [6.0, 12.0]], device=device, dtype=dtype))
+ self.assert_close(padded.data, Keypoints(data[None].clone()).pad(padding).data[0])
+
+ unpadded = Keypoints(data.clone()).unpad(padding)
+ self.assert_close(unpadded.data, torch.tensor([[5.0, -5.0], [0.0, -2.0]], device=device, dtype=dtype))
+ self.assert_close(unpadded.data, Keypoints(data[None].clone()).unpad(padding).data[0])
+
+ self.assert_close(Keypoints(data.clone()).pad(padding).unpad(padding).data, data)
+
+ def test_pad_padding_on_cpu(self, device, dtype):
+ # kornia#5021: like Boxes.pad, the padding is moved to the keypoints' device, so a CPU
+ # padding_size works for keypoints on an accelerator.
+ padding = torch.tensor([[1.0, 0.0, 2.0, 0.0]], dtype=dtype)
+ for data in (torch.zeros(3, 2, device=device, dtype=dtype), torch.zeros(1, 3, 2, device=device, dtype=dtype)):
+ kp = Keypoints(data.clone()).pad(padding)
+ assert kp.device == device
+ self.assert_close(kp.data[..., 0], torch.full(data.shape[:-1], 1.0, device=device, dtype=dtype))
+ self.assert_close(kp.data[..., 1], torch.full(data.shape[:-1], 2.0, device=device, dtype=dtype))
+
def test_index_put(self, device, dtype):
data = torch.zeros(10, 2, device=device, dtype=dtype)
kp = Keypoints(data)
@@ -179,6 +206,16 @@ class TestKeypoints(BaseTester):
with pytest.raises(RuntimeError):
kp.pad(torch.zeros(2, 3, device=device, dtype=dtype))
+ # an unbatched container carries a single image, so it takes exactly one padding row
+ unbatched = Keypoints(torch.rand(4, 2, device=device, dtype=dtype))
+ with pytest.raises(RuntimeError, match="one row"):
+ unbatched.pad(torch.zeros(2, 4, device=device, dtype=dtype))
+ with pytest.raises(RuntimeError, match="one row"):
+ unbatched.unpad(torch.zeros(2, 4, device=device, dtype=dtype))
+ # zero rows as well: a `> 1` check would let it through to an IndexError instead
+ with pytest.raises(RuntimeError, match="one row"):
+ unbatched.pad(torch.zeros(0, 4, device=device, dtype=dtype))
+
def test_int_input_raises_by_default(self, device, dtype):
with pytest.raises(ValueError):
Keypoints(torch.ones(5, 2, device=device, dtype=torch.int32))