π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
feat(geometry): implement Keypoints3D.transform_keypoints and deprecate pad/unpad (#6326)
Aditya Sinhaaefa52fe452a
diff --git a/changelog.d/6326.added.md b/changelog.d/6326.added.mdnew file mode 100644index 000000000..15592670d--- /dev/null+++ b/changelog.d/6326.added.md@@ -0,0 +1 @@+`Keypoints3D.transform_keypoints` and `transform_keypoints_` are implemented and apply a `(4, 4)` or `(B, 4, 4)` matrix like their 2D counterparts. `Keypoints3D.pad` and `unpad`, which were never implemented and always raised `NotImplementedError`, are deprecated, now also emit a `DeprecationWarning`, and will be removed in a future release.diff --git a/docs/source/geometry.keypoints.rst b/docs/source/geometry.keypoints.rstindex 74f6319bf..2747a7902 100644--- a/docs/source/geometry.keypoints.rst+++ b/docs/source/geometry.keypoints.rst@@ -6,7 +6,7 @@ kornia.geometry.keypointsObject-oriented API for keypoints: :class:`~kornia.geometry.keypoints.Keypoints` wraps a tensor of 2D ``(x, y)``points and transforms and pads it; :class:`~kornia.geometry.keypoints.Keypoints3D` validates and stores 3D-``(x, y, z)`` points.+``(x, y, z)`` points and transforms them... autoclass:: kornia.geometry.keypoints.Keypoints:members:diff --git a/kornia/geometry/keypoints.py b/kornia/geometry/keypoints.pyindex b39f3dedc..e9889287b 100644--- a/kornia/geometry/keypoints.py+++ b/kornia/geometry/keypoints.py@@ -20,6 +20,7 @@ from typing import List, Optional, Tuple, Union, castimport torchfrom torch import Size+from kornia.core._compat import _emit_deprecation_warningfrom kornia.geometry import transform_points__all__ = ["Keypoints", "Keypoints3D"]@@ -56,9 +57,7 @@ class Keypoints:"""- def __init__(- self, keypoints: Union[torch.torch.Tensor, List[torch.torch.Tensor]], raise_if_not_floating_point: bool = True- ) -> None:+ def __init__(self, keypoints: torch.Tensor, raise_if_not_floating_point: bool = True) -> None:self._N: Optional[List[int]] = Noneif isinstance(keypoints, list):@@ -348,15 +347,13 @@ class Keypoints3D:it to ``float32``.Convention:- - Known defects: list input, :meth:`pad`, :meth:`unpad`, :meth:`transform_keypoints`,- :meth:`transform_keypoints_` and ``to_tensor(as_padded_sequence=True)`` raise ``NotImplementedError``+ - Known defects: list input and ``to_tensor(as_padded_sequence=True)`` raise ``NotImplementedError``;+ :meth:`pad` and :meth:`unpad` are deprecated and also raise it(`#5023 <https://github.com/kornia/kornia/issues/5023>`_)."""- def __init__(- self, keypoints: Union[torch.torch.Tensor, List[torch.torch.Tensor]], raise_if_not_floating_point: bool = True- ) -> None:+ def __init__(self, keypoints: torch.Tensor, raise_if_not_floating_point: bool = True) -> None:self._N: Optional[List[int]] = Noneif isinstance(keypoints, list):@@ -412,26 +409,52 @@ class Keypoints3D:return self._datadef pad(self, padding_size: torch.torch.Tensor) -> "Keypoints3D":- """Not implemented: raises ``NotImplementedError`` (`#5023 <https://github.com/kornia/kornia/issues/5023>`_)."""+ """Deprecated since 0.9.1 and never implemented: raises ``NotImplementedError``."""+ _emit_deprecation_warning(+ "Keypoints3D.pad",+ None,+ "0.9.1",+ "It has never been implemented: the padding layout of 3D keypoints is not defined (kornia#5023).",+ )raise NotImplementedError("`Keypoints3D.pad` is not implemented (kornia#5023).")def unpad(self, padding_size: torch.torch.Tensor) -> "Keypoints3D":- """Not implemented: raises ``NotImplementedError`` (`#5023 <https://github.com/kornia/kornia/issues/5023>`_)."""+ """Deprecated since 0.9.1 and never implemented: raises ``NotImplementedError``."""+ _emit_deprecation_warning(+ "Keypoints3D.unpad",+ None,+ "0.9.1",+ "It has never been implemented: the padding layout of 3D keypoints is not defined (kornia#5023).",+ )raise NotImplementedError("`Keypoints3D.unpad` is not implemented (kornia#5023).")def transform_keypoints(self, M: torch.Tensor, inplace: bool = False) -> "Keypoints3D":- """Not implemented: raises ``NotImplementedError`` (`#5023 <https://github.com/kornia/kornia/issues/5023>`_).+ r"""Apply a transformation matrix to the 3D keypoints.++ A point is mapped to :math:`M [x, y, z, 1]^\top` and converted back with+ :func:`~kornia.geometry.conversions.convert_points_from_homogeneous`.++ Args:+ M: The transformation matrix to be applied, shape of :math:`(4, 4)` or :math:`(B, 4, 4)`.+ inplace: ``True`` rebinds this object to the transformed tensor and returns it, without writing into the+ tensor it wrapped; ``False`` returns a new :class:`Keypoints3D`.++ Returns:+ The transformed keypoints.- Use :func:`~kornia.geometry.linalg.transform_points` on :attr:`data` instead."""- raise NotImplementedError(- "`Keypoints3D.transform_keypoints` is not implemented; use "- "`kornia.geometry.linalg.transform_points(M, keypoints.data)` with `M` of shape `(B, 4, 4)` matching "- "the batch of `data`, or `(1, 4, 4)` when `data` is `(N, 3)` (kornia#5023)."- )+ if not 2 <= M.ndim <= 3 or M.shape[-2:] != (4, 4):+ raise ValueError(f"The transformation matrix shape must be (4, 4) or (B, 4, 4). Got {M.shape}.")++ transformed = transform_points(M, self._data)+ if inplace:+ self._data = transformed+ return self++ return Keypoints3D(transformed, False)def transform_keypoints_(self, M: torch.Tensor) -> "Keypoints3D":- """Not implemented: raises ``NotImplementedError`` (`#5023 <https://github.com/kornia/kornia/issues/5023>`_)."""+ """Inplace version of :func:`Keypoints3D.transform_keypoints`."""return self.transform_keypoints(M, inplace=True)@classmethoddiff --git a/tests/geometry/test_keypoints.py b/tests/geometry/test_keypoints.pyindex ef57ac68d..83ef6954a 100644--- a/tests/geometry/test_keypoints.py+++ b/tests/geometry/test_keypoints.py@@ -20,6 +20,7 @@ import torchimport kornia.augmentation as Kfrom kornia.geometry.keypoints import Keypoints, Keypoints3D, VideoKeypoints+from kornia.geometry.linalg import transform_pointsfrom testing.base import BaseTester, supports_bilinear_2d_grid_sample@@ -409,16 +410,52 @@ class TestKeypoints3D(BaseTester):kp[:5] = new_kpself.assert_close(kp.data[:5], new_data)+ @pytest.mark.parametrize(+ "data_shape, matrix_shape",+ [((2, 5, 3), (2, 4, 4)), ((2, 5, 3), (4, 4)), ((5, 3), (4, 4)), ((5, 3), (1, 4, 4))],+ )+ def test_transform_keypoints(self, data_shape, matrix_shape, device, dtype):+ data = torch.rand(data_shape).to(device, dtype)+ M = torch.rand(matrix_shape).to(device, dtype)+ kp = Keypoints3D(data)+ kp_t = kp.transform_keypoints(M)+ assert kp_t is not kp+ assert kp_t.data.device == device+ assert kp_t.data.dtype == dtype+ self.assert_close(kp_t.data, transform_points(M, data), rtol=0, atol=0)++ def test_transform_keypoints_inplace(self, device, dtype):+ data = torch.rand(2, 5, 3).to(device, dtype)+ original = data.clone()+ M = torch.rand(2, 4, 4).to(device, dtype)+ expected = transform_points(M, data)++ kp = Keypoints3D(data)+ assert kp.transform_keypoints(M, inplace=True) is kp+ self.assert_close(kp.data, expected, rtol=0, atol=0)++ kp = Keypoints3D(data)+ assert kp.transform_keypoints_(M) is kp+ self.assert_close(kp.data, expected, rtol=0, atol=0)+ self.assert_close(data, original, rtol=0, atol=0)++ @pytest.mark.parametrize("method", ["pad", "unpad"])+ def test_pad_unpad_deprecated(self, method, device, dtype):+ kp = Keypoints3D(torch.rand(5, 3, device=device, dtype=dtype))+ with (+ pytest.warns(DeprecationWarning, match=rf"`Keypoints3D\.{method}` is deprecated") as record,+ pytest.raises(NotImplementedError, match=rf"`Keypoints3D\.{method}` is not implemented"),+ ):+ getattr(kp, method)(torch.zeros(1, 6, device=device, dtype=dtype))+ assert len(record) == 1+ assert record[0].filename == __file__+def test_not_implemented(self, device, dtype):kp = Keypoints3D(torch.rand(5, 3, device=device, dtype=dtype))with pytest.raises(NotImplementedError, match=r"`Keypoints3D\.pad` is not implemented"):kp.pad(torch.zeros(1, 6, device=device, dtype=dtype))with pytest.raises(NotImplementedError, match=r"`Keypoints3D\.unpad` is not implemented"):kp.unpad(torch.zeros(1, 6, device=device, dtype=dtype))- with pytest.raises(NotImplementedError, match="transform_points"):- kp.transform_keypoints(torch.eye(4, device=device, dtype=dtype))- with pytest.raises(NotImplementedError, match="transform_points"):- kp.transform_keypoints_(torch.eye(4, device=device, dtype=dtype))with pytest.raises(NotImplementedError, match="from a list of tensors is not implemented"):Keypoints3D([torch.rand(3, 3, device=device, dtype=dtype), torch.rand(5, 3, device=device, dtype=dtype)])with pytest.raises(NotImplementedError, match=r"`Keypoints3D\.to_tensor\(as_padded_sequence=True\)`"):@@ -434,16 +471,35 @@ class TestKeypoints3D(BaseTester):with pytest.raises(ValueError):Keypoints3D(torch.rand(3, 2, device=device, dtype=dtype))+ def test_transform_exception(self, device, dtype):+ kp = Keypoints3D(torch.rand(5, 3, device=device, dtype=dtype))+ with pytest.raises(ValueError, match=r"must be \(4, 4\) or \(B, 4, 4\)"):+ kp.transform_keypoints(torch.eye(3, device=device, dtype=dtype))+def test_int_input_converted_when_not_raising(self, device, dtype):data = torch.ones(5, 3, device=device, dtype=torch.int32)kp = Keypoints3D(data, raise_if_not_floating_point=False)assert kp.data.dtype == torch.float32def test_gradcheck(self, device):- pass # Keypoints3D transform ops are NotImplemented+ data = torch.rand(1, 5, 3, device=device, dtype=torch.float64, requires_grad=True)+ M = torch.eye(4, device=device, dtype=torch.float64).unsqueeze(0)+ M[0, 0, 3] = 1.0++ def fn(x):+ return Keypoints3D(x).transform_keypoints(M).data++ self.gradcheck(fn, (data,))def test_dynamo(self, device, dtype, torch_optimizer):- pass+ data = torch.rand(1, 5, 3, device=device, dtype=dtype)+ M = torch.eye(4, device=device, dtype=dtype).unsqueeze(0)++ def fn(x):+ return Keypoints3D(x).transform_keypoints(M).data++ op = torch_optimizer(fn)+ self.assert_close(op(data), fn(data))def test_smoke_jit(self, device, dtype):pass@@ -610,13 +666,11 @@ class TestConventionsKeypoints(BaseTester):"keypoints3d_to_tensor_padded_sequence","keypoints3d_pad","keypoints3d_unpad",- "keypoints3d_transform_keypoints",- "keypoints3d_transform_keypoints_",],)def test_wart_keypoints_documented_paths_not_implemented_5023(self, path, device, dtype):- # Wart pin (#5023): the API offers list input (the List[Tensor] annotation), to_tensor(as_padded_sequence=True)- # and the Keypoints3D pad / unpad / transform_keypoints methods, and every one of these paths raises+ # Wart pin (#5023): the API offers list input (the runtime list branch), to_tensor(as_padded_sequence=True)+ # and the deprecated Keypoints3D pad / unpad methods, and every one of these paths raises# NotImplementedError. Implementing a path, or removing it from the API, flips its case. The message is# not asserted, so rewording it leaves every case green.kp2d = torch.tensor([[[8.0, 2.0], [3.0, 5.0]]], device=device, dtype=dtype)@@ -630,12 +684,6 @@ class TestConventionsKeypoints(BaseTester):"keypoints3d_to_tensor_padded_sequence": lambda: Keypoints3D(kp3d).to_tensor(as_padded_sequence=True),"keypoints3d_pad": lambda: Keypoints3D(kp3d).pad(torch.zeros(1, 6, device=device, dtype=dtype)),"keypoints3d_unpad": lambda: Keypoints3D(kp3d).unpad(torch.zeros(1, 6, device=device, dtype=dtype)),- "keypoints3d_transform_keypoints": lambda: Keypoints3D(kp3d).transform_keypoints(- torch.eye(4, device=device, dtype=dtype)[None]- ),- "keypoints3d_transform_keypoints_": lambda: Keypoints3D(kp3d).transform_keypoints_(- torch.eye(4, device=device, dtype=dtype)[None]- ),}with pytest.raises(NotImplementedError):calls[path]()