π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry): index VideoKeypoints by video and keep temporal_channel_size (#6376)
Saksham Sharma95280ccb8f72
diff --git a/changelog.d/6376.breaking.md b/changelog.d/6376.breaking.mdnew file mode 100644index 000000000..88bd509c0--- /dev/null+++ b/changelog.d/6376.breaking.md@@ -0,0 +1 @@+Indexing and assigning a `kornia.geometry.keypoints.VideoKeypoints` now select whole videos on the video-batch axis, as `VideoBoxes` does: `vk[i]` is the `i`-th video, a `VideoKeypoints` of `(T, N, 2)` frames that keeps `temporal_channel_size`, and `vk[key] = value` writes whole videos (a `VideoKeypoints` value with a different `temporal_channel_size` raises `ValueError`). Previously both indexed the flattened `(B * T, N, 2)` frames: `vk[i]` returned frame `i` of the flattened batch, without `temporal_channel_size`, and `vk[key] = value` wrote frames. A boolean mask now has length `B`: a length-`B * T` mask, which used to select frames, raises `IndexError`. Code that read single frames as `vk[i].data` gets a whole video now; index the frames with `vk.data[i]` instead.diff --git a/changelog.d/6376.fixed.md b/changelog.d/6376.fixed.mdnew file mode 100644index 000000000..84310b09f--- /dev/null+++ b/changelog.d/6376.fixed.md@@ -0,0 +1 @@+`VideoKeypoints` indexing results support `to_tensor()`: `vk[0].to_tensor()` returns `(1, T, N, 2)`, where it used to raise `AttributeError` because the result had no `temporal_channel_size`. An `AugmentationSequential` with a `VideoSequential` now also accepts a `VideoKeypoints` object for its keypoints and returns one; it used to raise `TypeError` in `torch.is_floating_point`. `VideoSequential` hands its children frame-level keypoints, so augmenting video keypoints gives the same result as before.diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.pyindex 9f3523f60..4f89909f3 100644--- a/kornia/augmentation/container/augment.py+++ b/kornia/augmentation/container/augment.py@@ -1231,6 +1231,13 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):dtype = Noneif self.contains_video_sequential:+ if isinstance(arg, VideoKeypoints):+ return arg+ if isinstance(arg, Keypoints):+ raise TypeError(+ "A VideoSequential pipeline needs VideoKeypoints or a (B, T, N, 2) tensor for its keypoints, which"+ " carry the number of frames per video. Got Keypoints."+ )arg = cast(Union[torch.Tensor, List[torch.Tensor]], arg)if isinstance(arg, list):if not torch.is_floating_point(arg[0]):diff --git a/kornia/augmentation/container/video.py b/kornia/augmentation/container/video.pyindex b14adf1e9..8df390ea5 100644--- a/kornia/augmentation/container/video.py+++ b/kornia/augmentation/container/video.py@@ -24,9 +24,9 @@ import kornia.augmentation as Kfrom kornia.augmentation.base import _AugmentationBasefrom kornia.augmentation.container.base import SequentialBasefrom kornia.augmentation.container.image import ImageSequential, _get_new_batch_shape-from kornia.augmentation.utils.helpers import _frame_boxes, _video_boxes+from kornia.augmentation.utils.helpers import _frame_boxes, _frame_keypoints, _video_boxes, _video_keypointsfrom kornia.geometry.boxes import Boxes, VideoBoxes-from kornia.geometry.keypoints import Keypoints+from kornia.geometry.keypoints import Keypoints, VideoKeypointsfrom .params import ParamItem@@ -517,6 +517,10 @@ class VideoSequential(ImageSequential):input = Keypoints(input.reshape(batchsize * frame_num, input.size(2), input.size(3)))input = super().transform_keypoints(input, params, extra_args=extra_args)input = input.data.reshape(batchsize, frame_num, input.data.size(1), 2)+ elif isinstance(input, VideoKeypoints):+ # The children index frames; VideoKeypoints indexes videos (#6375).+ frames = super().transform_keypoints(_frame_keypoints(input), params, extra_args=extra_args)+ input = _video_keypoints(frames, input.temporal_channel_size)else:input = super().transform_keypoints(input, params, extra_args=extra_args)return input@@ -540,6 +544,9 @@ class VideoSequential(ImageSequential):input = Keypoints(input.reshape(batchsize * frame_num, input.size(2), input.size(3)))input = super().inverse_keypoints(input, params, extra_args=extra_args)input = input.data.reshape(batchsize, frame_num, input.data.size(1), 2)+ elif isinstance(input, VideoKeypoints):+ frames = super().inverse_keypoints(_frame_keypoints(input), params, extra_args=extra_args)+ input = _video_keypoints(frames, input.temporal_channel_size)else:input = super().inverse_keypoints(input, params, extra_args=extra_args)return inputdiff --git a/kornia/augmentation/utils/helpers.py b/kornia/augmentation/utils/helpers.pyindex 06d04326f..6723337c4 100644--- a/kornia/augmentation/utils/helpers.py+++ b/kornia/augmentation/utils/helpers.py@@ -26,7 +26,7 @@ from torch.distributions import Beta, Uniformfrom kornia.core.ops import _constant_tensor, _flatten_constant # noqa: F401from kornia.core.utils import _extract_device_dtypefrom kornia.geometry.boxes import Boxes, VideoBoxes-from kornia.geometry.keypoints import Keypoints+from kornia.geometry.keypoints import Keypoints, VideoKeypointsdef _pad_with_fill(@@ -107,6 +107,25 @@ def _video_boxes(frames: Boxes, temporal_channel_size: int) -> VideoBoxes:return boxes+def _frame_keypoints(keypoints: VideoKeypoints) -> Keypoints:+ r"""View :class:`VideoKeypoints` as the frame-level :class:`Keypoints` of its :math:`(B \cdot T, N, 2)` storage.++ As :func:`_frame_boxes` does for boxes: the children of :class:`VideoSequential` index frames, and+ ``VideoKeypoints`` indexes whole videos. The view shares the storage.+ """+ frames = Keypoints(keypoints._data, False)+ frames._is_batched = keypoints._is_batched+ return frames+++def _video_keypoints(frames: Keypoints, temporal_channel_size: int) -> VideoKeypoints:+ """Wrap frame-level :class:`Keypoints` back into :class:`VideoKeypoints` with ``temporal_channel_size`` frames."""+ keypoints = VideoKeypoints(frames._data, False)+ keypoints._is_batched = frames._is_batched+ keypoints.temporal_channel_size = temporal_channel_size+ return keypoints++def _validate_input(f: Callable[..., Any]) -> Callable[..., Any]:r"""Validate the 2D input of the wrapped function.diff --git a/kornia/geometry/keypoints.py b/kornia/geometry/keypoints.pyindex f6e7b894e..a9c821d4d 100644--- a/kornia/geometry/keypoints.py+++ b/kornia/geometry/keypoints.py@@ -297,6 +297,10 @@ class VideoKeypoints(Keypoints):Non-contiguous inputs are copied only when flattening requires it. Empty batches and point setsretain their shape on conversion back to a tensor; the temporal dimension must be nonzero.++ Indexing and item assignment select whole videos on the video-batch axis, as for+ :class:`~kornia.geometry.boxes.VideoBoxes`: ``vk[i]`` is a one-video :class:`VideoKeypoints` whose+ :meth:`to_tensor` is ``(1, T, N, 2)``, and a boolean mask has length ``B``. Index frames with ``vk.data``."""temporal_channel_size: int@@ -316,6 +320,36 @@ class VideoKeypoints(Keypoints):out.temporal_channel_size = temporal_channel_sizereturn out+ def __getitem__(self, key: Union[slice, int, torch.torch.Tensor]) -> "VideoKeypoints":+ r"""Select videos while preserving the temporal axis, as :meth:`VideoBoxes.__getitem__` does.++ An integer or scalar tensor keeps a singleton video-batch dimension. Slices, integer tensors, and boolean+ tensors follow the corresponding PyTorch indexing behavior on the video-batch axis.+ """+ batch_size = self._data.shape[0] // self.temporal_channel_size+ selected = self._data.view(batch_size, self.temporal_channel_size, *self._data.shape[1:])[key]+ if selected.ndim == self._data.ndim:+ selected = selected.unsqueeze(0)+ out = type(self)(selected.flatten(0, 1), False)+ out.temporal_channel_size = self.temporal_channel_size+ return out++ def __setitem__(self, key: Union[slice, int, torch.torch.Tensor], value: "Keypoints") -> "VideoKeypoints":+ r"""Write whole videos, selected by ``key`` on the video-batch axis as in :meth:`__getitem__`.++ A :class:`VideoKeypoints` value must have the same ``temporal_channel_size``: otherwise its frames would be+ regrouped into videos of another length.+ """+ size = self.temporal_channel_size+ if isinstance(value, VideoKeypoints) and value.temporal_channel_size != size:+ raise ValueError(+ f"Cannot assign videos of {value.temporal_channel_size} frames to videos of {size} frames."+ )+ # Explicit video counts: a clip with no points has 0 elements, so a -1 in the view would be ambiguous.+ n, m = self._data.shape[0] // size, value.data.shape[0] // size+ self._data.view(n, size, *self._data.shape[1:])[key] = value.data.view(m, size, *value.data.shape[1:])+ return self+def to_tensor(self) -> torch.torch.Tensor:out = super().to_tensor(as_padded_sequence=False)out = cast(torch.torch.Tensor, out)diff --git a/tests/augmentation/container/test_video_sequential.py b/tests/augmentation/container/test_video_sequential.pyindex ebf1d0ad8..f846caabb 100644--- a/tests/augmentation/container/test_video_sequential.py+++ b/tests/augmentation/container/test_video_sequential.py@@ -578,3 +578,55 @@ class TestVideoSequential:assert aug(video).shape == video.shapeassert aug(video, params=aug._params).shape == video.shape++ @pytest.mark.parametrize("same_on_frame", [False, True])+ def test_partial_gate_keypoints_round_trip_6375(self, same_on_frame, device, dtype):+ # Keypoints reach VideoSequential as VideoKeypoints, which index whole videos (#6375), while a partially+ # applied child gates frames. VideoSequential hands its children frame-level Keypoints, as it does for boxes+ # (#6173), so the inverse of a partial gate restores every frame's points.+ affine = K.RandomAffine(30.0, translate=(0.1, 0.1), p=0.5)+ aug = K.AugmentationSequential(+ K.VideoSequential(affine, same_on_frame=same_on_frame), data_keys=["input", "keypoints"]+ )+ video = torch.rand(3, 4, 3, 16, 16, device=device, dtype=dtype)+ points = torch.rand(3, 4, 5, 2, device=device, dtype=dtype) * 15+ # A forward and inverse warp rounds 15 px coordinates to about the dtype's spacing there (0.125 in bfloat16).+ tol = {torch.float16: 1e-2, torch.bfloat16: 0.125}.get(dtype, 1e-4)+ partial = False+ for seed in range(4):+ torch.manual_seed(seed)+ out_video, out_points = aug(video, points)+ applied = aug._params[0].data[0].data["batch_prob"] > 0.5+ partial |= bool(applied.any()) and not bool(applied.all())+ # The gate is per frame: a skipped frame's points are unchanged and an applied frame's points move.+ moved = (out_points - points).abs().flatten(0, 1).amax((-1, -2)) > tol+ assert_close(moved, applied.to(moved.device)) # the gate is drawn on the CPU+ _, restored = aug.inverse(out_video, out_points)+ assert out_points.shape == points.shape+ assert_close(restored, points, atol=tol, rtol=0.0)+ assert partial++ def test_video_keypoints_object_input_6375(self, device, dtype):+ # A VideoKeypoints object goes through a VideoSequential pipeline and comes back as VideoKeypoints, equal to+ # the output for the same points as a (B, T, N, 2) tensor. It used to raise a TypeError in is_floating_point.+ # Plain Keypoints carry no frame count, so they are rejected with a message that says so.+ from kornia.geometry.keypoints import Keypoints, VideoKeypoints++ aug = K.AugmentationSequential(+ K.VideoSequential(K.RandomAffine(30.0, p=0.5), K.RandomHorizontalFlip(p=0.5)),+ data_keys=["input", "keypoints"],+ )+ video = torch.rand(3, 4, 3, 16, 16, device=device, dtype=dtype)+ points = torch.rand(3, 4, 5, 2, device=device, dtype=dtype) * 15+ torch.manual_seed(0)+ out_video, dense = aug(video, points)+ torch.manual_seed(0)+ _, wrapped = aug(video, VideoKeypoints.from_tensor(points.clone()))+ assert isinstance(wrapped, VideoKeypoints)+ assert_close(wrapped.to_tensor(), dense)+ _, restored = aug.inverse(out_video, wrapped)+ assert isinstance(restored, VideoKeypoints)+ assert_close(restored.to_tensor(), aug.inverse(out_video, dense)[1])++ with pytest.raises(TypeError, match="VideoKeypoints or a"):+ aug(video, Keypoints(points.flatten(0, 1)))diff --git a/tests/geometry/test_keypoints.py b/tests/geometry/test_keypoints.pyindex 83ef6954a..4bc927e45 100644--- a/tests/geometry/test_keypoints.py+++ b/tests/geometry/test_keypoints.py@@ -321,6 +321,39 @@ class TestVideoKeypoints(BaseTester):assert isinstance(out, VideoKeypoints)assert out.temporal_channel_size == T+ @pytest.mark.parametrize(+ "key, videos",+ [(0, [0]), (-1, [2]), (slice(0, 2), [0, 1]), (slice(1, None), [1, 2]), ("index", [2, 0]), ("mask", [0, 2])],+ )+ def test_getitem_selects_videos_6375(self, key, videos, device, dtype):+ # As VideoBoxes (#4249): indexing selects whole videos on the video-batch axis and keeps the temporal axis.+ # The inherited Keypoints.__getitem__ indexed frames and dropped temporal_channel_size, so to_tensor() raised.+ data = torch.arange(3 * 4 * 5 * 2, device=device, dtype=dtype).reshape(3, 4, 5, 2)+ vkp = VideoKeypoints.from_tensor(data)+ if key == "index":+ key = torch.tensor([2, 0], device=device)+ elif key == "mask":+ key = torch.tensor([True, False, True], device=device)+ out = vkp[key]+ assert isinstance(out, VideoKeypoints)+ assert out.temporal_channel_size == 4+ self.assert_close(out.to_tensor(), data[videos])++ def test_setitem_writes_videos_6375(self, device, dtype):+ # from_tensor shares the storage of a contiguous tensor, so build the expected values before writing.+ data = torch.zeros(3, 4, 5, 2, device=device, dtype=dtype)+ expected = data.clone()+ expected[1] = 1+ vkp = VideoKeypoints.from_tensor(data.clone())+ vkp[1] = VideoKeypoints.from_tensor(torch.ones(1, 4, 5, 2, device=device, dtype=dtype))+ self.assert_close(vkp.to_tensor(), expected)+ vkp[torch.tensor([True, False, True], device=device)] = vkp[torch.tensor([1, 1], device=device)]+ self.assert_close(vkp.to_tensor(), torch.ones_like(data))++ # A value with another number of frames per video is rejected rather than regrouped.+ with pytest.raises(ValueError, match="4 frames"):+ vkp[0] = VideoKeypoints.from_tensor(torch.ones(2, 2, 5, 2, device=device, dtype=dtype))+def test_exception(self, device, dtype):with pytest.raises(ValueError):VideoKeypoints.from_tensor(torch.rand(5, 2, device=device, dtype=dtype))