π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry): handle non-contiguous and empty video keypoints (#5840)
NIKHILa89295c0c8b5
diff --git a/changelog.d/5840.fixed.md b/changelog.d/5840.fixed.mdnew file mode 100644index 000000000..ed252f9f0--- /dev/null+++ b/changelog.d/5840.fixed.md@@ -0,0 +1 @@+`AugmentationSequential` with a `VideoSequential` child accepts non-contiguous video keypoint and box tensors, clips with no keypoints or boxes, and empty batches, and `VideoKeypoints`/`VideoBoxes` keep those shapes through `from_tensor` and `to_tensor`. Each of these used to raise a `view`/`reshape` `RuntimeError`.diff --git a/kornia/geometry/boxes.py b/kornia/geometry/boxes.pyindex bdf616aae..6a5bb04c4 100644--- a/kornia/geometry/boxes.py+++ b/kornia/geometry/boxes.py@@ -1125,7 +1125,7 @@ class VideoBoxes(Boxes):temporal_channel_size = boxes.size(1)quadrilaterals = _boxes_to_quadrilaterals(- boxes.view(boxes.size(0) * boxes.size(1), -1, boxes.size(3), boxes.size(4)),+ boxes.reshape(boxes.size(0) * boxes.size(1), boxes.size(2), boxes.size(3), boxes.size(4)),mode="vertices_plus",validate_boxes=validate_boxes,)@@ -1179,8 +1179,9 @@ class VideoBoxes(Boxes)::attr:`temporal_channel_size`."""out = super().to_tensor(mode, as_padded_sequence=as_padded_sequence)+ batch_size = self._data.shape[0] // self.temporal_channel_sizeif isinstance(out, torch.Tensor):- return out.view(-1, self.temporal_channel_size, *out.shape[1:])+ return out.reshape(batch_size, self.temporal_channel_size, *out.shape[1:])# If returns a list of boxes.return [_out.view(-1, self.temporal_channel_size, *_out.shape[1:]) for _out in out]diff --git a/kornia/geometry/keypoints.py b/kornia/geometry/keypoints.pyindex b3d381530..ed81d994e 100644--- a/kornia/geometry/keypoints.py+++ b/kornia/geometry/keypoints.py@@ -293,6 +293,12 @@ class Keypoints:class VideoKeypoints(Keypoints):+ """Video keypoints shaped ``(B, T, N, 2)``, stored internally as ``(B * T, N, 2)``.++ Non-contiguous inputs are copied only when flattening requires it. Empty batches and point sets+ retain their shape on conversion back to a tensor; the temporal dimension must be nonzero.+ """+temporal_channel_size: int@classmethod@@ -306,14 +312,15 @@ class VideoKeypoints(Keypoints):# Due to some torch.jit.script bug (at least <= 1.9), you need to pass all arguments to __init__ when# constructing the class from inside of a method.- out = cls(boxes.view(boxes.size(0) * boxes.size(1), -1, boxes.size(3)))+ out = cls(boxes.reshape(boxes.size(0) * boxes.size(1), boxes.size(2), boxes.size(3)))out.temporal_channel_size = temporal_channel_sizereturn outdef to_tensor(self) -> torch.torch.Tensor: # type: ignore[override]out = super().to_tensor(as_padded_sequence=False)out = cast(torch.torch.Tensor, out)- return out.view(-1, self.temporal_channel_size, *out.shape[1:])+ batch_size = out.shape[0] // self.temporal_channel_size+ return out.reshape(batch_size, self.temporal_channel_size, *out.shape[1:])def transform_keypoints(self, M: torch.torch.Tensor, inplace: bool = False) -> "VideoKeypoints":out = super().transform_keypoints(M, inplace=inplace)diff --git a/tests/augmentation/container/test_augmentation_sequential.py b/tests/augmentation/container/test_augmentation_sequential.pyindex c373bf876..b34e3e34a 100644--- a/tests/augmentation/container/test_augmentation_sequential.py+++ b/tests/augmentation/container/test_augmentation_sequential.py@@ -1215,6 +1215,45 @@ class TestAugmentationSequential:class TestConventionAugmentationSequential(BaseTester):"""Convention checks and pins for documented `AugmentationSequential` limitations."""+ @pytest.mark.parametrize("num_points", [0, 2])+ def test_video_keypoints_noncontiguous_and_empty(self, num_points, device, dtype):+ image = torch.arange(36, device=device, dtype=dtype).reshape(1, 1, 1, 6, 6).expand(2, 3, -1, -1, -1)+ points = torch.arange(3 * 2 * num_points * 2, device=device, dtype=dtype).reshape(3, 2, num_points, 2)+ points = (points % 6).transpose(0, 1)+ expected = points.clone()+ expected[..., 0] = 5 - expected[..., 0]+ aug = K.AugmentationSequential(+ K.VideoSequential(K.RandomHorizontalFlip(p=1.0), data_format="BTCHW"),+ data_keys=["input", "keypoints"],+ )++ out_image, out_points = aug(image, points)+ self.assert_close(out_image, image.flip(-1))+ assert out_points.shape == points.shape+ self.assert_close(out_points, expected)+ _, restored = aug.inverse(out_image, out_points)+ self.assert_close(restored, points)++ @pytest.mark.parametrize("num_boxes", [0, 2])+ def test_video_boxes_noncontiguous_and_empty(self, num_boxes, device, dtype):+ image = torch.arange(36, device=device, dtype=dtype).reshape(1, 1, 1, 6, 6).expand(2, 3, -1, -1, -1)+ corners = torch.tensor([[1.0, 1.0], [3.0, 1.0], [3.0, 4.0], [1.0, 4.0]], device=device, dtype=dtype)+ shift = torch.arange(6, device=device, dtype=dtype).reshape(3, 2, 1, 1, 1) * 0.25+ boxes = (corners + shift).expand(3, 2, num_boxes, 4, 2).transpose(0, 1)+ expected = boxes.clone()+ expected[..., 0] = 5 - expected[..., 0]+ expected = expected[..., [1, 0, 3, 2], :]+ aug = K.AugmentationSequential(+ K.VideoSequential(K.RandomHorizontalFlip(p=1.0), data_format="BTCHW"),+ data_keys=["input", "bbox"],+ )++ out_image, out_boxes = aug(image, boxes)+ assert out_boxes.shape == boxes.shape+ self.assert_close(out_boxes, expected)+ _, restored = aug.inverse(out_image, out_boxes)+ self.assert_close(restored, boxes)+@pytest.mark.parametrize("batch_size", [2, 3])@pytest.mark.parametrize("keepdim,child_keepdim", [(True, False), (None, True), (False, True)])@pytest.mark.parametrize("mask_layout", ["BHW", "BCHW"])diff --git a/tests/geometry/test_boxes.py b/tests/geometry/test_boxes.pyindex 0e8b6772c..f0e42de49 100644--- a/tests/geometry/test_boxes.py+++ b/tests/geometry/test_boxes.py@@ -2202,6 +2202,17 @@ class TestVideoBoxes(BaseTester):assert isinstance(out, torch.Tensor)assert out.shape == boxes.shape+ @pytest.mark.parametrize("shape", [(3, 2, 2), (2, 3, 0), (0, 3, 2)])+ def test_noncontiguous_and_empty_roundtrip(self, shape, device, dtype):+ # (3, 2, 2) is built time-major and transposed into a non-contiguous (2, 3, 2, 4, 2) video.+ boxes = self._sample_video_boxes(device, dtype, batch=shape[0], time=shape[1], n_boxes=shape[2])+ if shape == (3, 2, 2):+ boxes = (boxes + torch.arange(6, device=device, dtype=dtype).view(3, 2, 1, 1, 1)).transpose(0, 1)+ video_boxes = VideoBoxes.from_tensor(boxes)+ assert video_boxes.data.shape == (boxes.size(0) * boxes.size(1), boxes.size(2), 4, 2)+ self.assert_close(video_boxes.to_tensor(), boxes, atol=0.0, rtol=0.0)+ assert video_boxes.to_tensor("xyxy").shape == (*boxes.shape[:3], 4)+def test_roundtrip_and_clone(self, device, dtype):boxes = self._sample_video_boxes(device, dtype)video_boxes = VideoBoxes.from_tensor(boxes)diff --git a/tests/geometry/test_keypoints.py b/tests/geometry/test_keypoints.pyindex 2bfa13738..ef57ac68d 100644--- a/tests/geometry/test_keypoints.py+++ b/tests/geometry/test_keypoints.py@@ -261,6 +261,29 @@ class TestKeypoints(BaseTester):class TestVideoKeypoints(BaseTester):+ @pytest.mark.parametrize("layout", ["transposed", "expanded", "strided"])+ def test_noncontiguous_roundtrip(self, layout, device, dtype):+ data = torch.arange(48, device=device, dtype=dtype).reshape(2, 3, 4, 2)+ if layout == "transposed":+ data = data.transpose(0, 1)+ elif layout == "expanded":+ data = data[:1].expand(2, -1, -1, -1)+ else:+ data = data[:, ::2]+ assert not data.is_contiguous()++ keypoints = VideoKeypoints.from_tensor(data)+ self.assert_close(keypoints.data, data.reshape(-1, 4, 2))+ self.assert_close(keypoints.to_tensor(), data)++ @pytest.mark.parametrize("shape", [(2, 3, 0, 2), (0, 3, 4, 2)])+ def test_empty_roundtrip(self, shape, device, dtype):+ data = torch.empty(shape, device=device, dtype=dtype)+ keypoints = VideoKeypoints.from_tensor(data)+ assert keypoints.data.shape == (shape[0] * shape[1], shape[2], 2)+ assert keypoints.clone().to_tensor().shape == data.shape+ self.assert_close(keypoints.to_tensor(), data)+def test_smoke(self, device, dtype):data = torch.rand(2, 5, 10, 2, device=device, dtype=dtype)vkp = VideoKeypoints.from_tensor(data)@@ -305,10 +328,21 @@ class TestVideoKeypoints(BaseTester):VideoKeypoints.from_tensor(torch.rand(2, 5, 10, 3, device=device, dtype=dtype))def test_gradcheck(self, device):- pass # VideoKeypoints ops not differentiable through from_tensor reshape+ data = torch.rand(3, 2, 2, 2, device=device, dtype=torch.float64)+ matrix = torch.eye(3, device=device, dtype=torch.float64)[None]++ def transform(x):+ return VideoKeypoints.from_tensor(x.transpose(0, 1)).transform_keypoints(matrix).to_tensor()++ self.gradcheck(transform, (data,))def test_dynamo(self, device, dtype, torch_optimizer):- pass # VideoKeypoints uses reshape; not straightforward to dynamo+ data = torch.rand(3, 2, 4, 2, device=device, dtype=dtype)++ def roundtrip(x):+ return VideoKeypoints.from_tensor(x.transpose(0, 1)).to_tensor()++ self.assert_close(torch_optimizer(roundtrip, fullgraph=True)(data), data.transpose(0, 1))def test_smoke_jit(self, device, dtype):pass