Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

[feat] Add NamedPose (#2482)

Christie Jacob70e15be4b568
diff --git a/kornia/geometry/__init__.py b/kornia/geometry/__init__.py
index dadab871a..3f2d23838 100644
--- a/kornia/geometry/__init__.py
+++ b/kornia/geometry/__init__.py
@@ -8,6 +8,7 @@ from .homography import *
from .liegroup import *
from .linalg import *
from .line import *
+from .pose import *
from .ransac import *
from .solvers import *
from .subpix import *
diff --git a/kornia/geometry/liegroup/se2.py b/kornia/geometry/liegroup/se2.py
index 523124858..37ed5045a 100644
--- a/kornia/geometry/liegroup/se2.py
+++ b/kornia/geometry/liegroup/se2.py
@@ -91,6 +91,13 @@ class Se2(Module):
def __getitem__(self, idx: int | slice) -> Se2:
return Se2(self._rotation[idx], self._translation[idx])
+ def _mul_se2(self, right: Se2) -> Se2:
+ so2 = self.so2
+ t = self.t
+ _r = so2 * right.so2
+ _t = t + so2 * right.t
+ return Se2(_r, _t)
+
@overload
def __mul__(self, right: Se2) -> Se2:
...
@@ -112,9 +119,7 @@ class Se2(Module):
t = self.t
if isinstance(right, Se2):
KORNIA_CHECK_TYPE(right, Se2)
- _r = so2 * right.so2
- _t = t + so2 * right.t
- return Se2(_r, _t)
+ return self._mul_se2(right)
elif isinstance(right, (Vector2, Tensor)):
# TODO change to KORNIA_CHECK_SHAPE once there is multiple shape support
# _check_se2_r_t_shape(so2, risght)
diff --git a/kornia/geometry/liegroup/se3.py b/kornia/geometry/liegroup/se3.py
index 32240417b..16ff9fd41 100644
--- a/kornia/geometry/liegroup/se3.py
+++ b/kornia/geometry/liegroup/se3.py
@@ -88,6 +88,11 @@ class Se3(Module):
def __getitem__(self, idx: int | slice) -> Se3:
return Se3(self._rotation[idx], self._translation[idx])
+ def _mul_se3(self, right: Se3) -> Se3:
+ _r = self.r * right.r
+ _t = self.t + self.r * right.t
+ return Se3(_r, _t)
+
def __mul__(self, right: Se3) -> Se3 | Vector3 | Tensor:
"""Compose two Se3 transformations.
@@ -101,9 +106,7 @@ class Se3(Module):
t = self.t
if isinstance(right, Se3):
# https://github.com/strasdat/Sophus/blob/master/sympy/sophus/se3.py#L97
- _r = so3 * right.so3
- _t = t + so3 * right.t
- return Se3(_r, _t)
+ return self._mul_se3(right)
elif isinstance(right, (Vector3, Tensor)):
# KORNIA_CHECK_SHAPE(right, ["B", "N"]) # FIXME: resolve shape bugs. @edgarriba
return so3 * right + t.data
diff --git a/kornia/geometry/pose.py b/kornia/geometry/pose.py
new file mode 100644
index 000000000..0f753fb54
--- /dev/null
+++ b/kornia/geometry/pose.py
@@ -0,0 +1,223 @@
+from __future__ import annotations
+
+import uuid
+
+from kornia.core import Tensor, eye
+from kornia.geometry.liegroup import Se2, Se3, So2, So3
+from kornia.geometry.quaternion import Quaternion
+
+
+def check_matrix_shape(matrix: Tensor, matrix_type: str = "R") -> None:
+ target_shapes = []
+ if matrix_type == "R":
+ target_shapes = [[2, 2], [3, 3]]
+ elif matrix_type == "RT":
+ target_shapes = [[3, 3], [4, 4]]
+ if len(matrix.shape) > 3 or len(matrix.shape) < 2 or list(matrix.shape[-2:]) not in target_shapes:
+ raise ValueError(
+ f"{matrix_type} must be either {target_shapes[0]}x{target_shapes[0]} or \
+ {target_shapes[1]}x{target_shapes[1]}, got {matrix.shape}"
+ )
+
+
+class NamedPose:
+ r"""Class to represent a named pose between two frames.
+
+ Internally represented by either Se2 or Se3.
+
+ Example:
+ >>> b_from_a = NamedPose(Se3.identity(), frame_src="frame_a", frame_dst="frame_b")
+ >>> b_from_a
+ NamedPose(dst_from_src=rotation: Parameter containing:
+ tensor([1., 0., 0., 0.], requires_grad=True)
+ translation: x: 0.0
+ y: 0.0
+ z: 0.0,
+ frame_src: frame_a -> frame_dst: frame_b)
+ """
+
+ def __init__(self, dst_from_src: Se2 | Se3, frame_src: str | None = None, frame_dst: str | None = None) -> None:
+ """Constructor for NamedPose.
+
+ Args:
+ dst_from_src: Pose from source frame to destination frame.
+ src: Name of frame a.
+ dst: Name of frame b.
+ """
+ self._dst_from_src = dst_from_src
+ self._frame_src = frame_src or uuid.uuid4().hex
+ self._frame_dst = frame_dst or uuid.uuid4().hex
+
+ def __repr__(self) -> str:
+ return (
+ f"NamedPose(dst_from_src={self._dst_from_src},\n"
+ f"frame_src: {self._frame_src} -> frame_dst: {self._frame_dst})"
+ )
+
+ def __mul__(self, other: NamedPose) -> NamedPose:
+ """Compose two NamedPoses.
+
+ Args:
+ other: NamedPose to compose with.
+
+ Returns:
+ Composed NamedPose.
+
+ Example:
+ >>> b_from_a = NamedPose(Se3.identity(), frame_src="frame_a", frame_dst="frame_b")
+ >>> c_from_b = NamedPose(Se3.identity(), frame_src="frame_b", frame_dst="frame_c")
+ >>> c_from_b * b_from_a
+ NamedPose(dst_from_src=rotation: Parameter containing:
+ tensor([1., 0., 0., 0.], requires_grad=True)
+ translation: x: 0.0
+ y: 0.0
+ z: 0.0,
+ frame_src: frame_a -> frame_dst: frame_c)
+ """
+ if self._frame_src != other._frame_dst:
+ raise ValueError(f"Cannot compose {self} with {other}")
+ if isinstance(other.pose, Se2):
+ return NamedPose(self._dst_from_src._mul_se2(other.pose), other._frame_src, self._frame_dst)
+ elif isinstance(other.pose, Se3):
+ return NamedPose(self._dst_from_src._mul_se3(other.pose), other._frame_src, self._frame_dst)
+ else:
+ raise ValueError(f"Pose must be either Se2 or Se3, got {type(self._dst_from_src)}")
+
+ @property
+ def pose(self) -> Se2 | Se3:
+ """Pose from source frame to destination frame ."""
+ return self._dst_from_src
+
+ @property
+ def rotation(self) -> So3 | So2:
+ """Rotation part of the pose."""
+ return self._dst_from_src.rotation
+
+ @property
+ def translation(self) -> Tensor:
+ """Translation part of the pose."""
+ return self._dst_from_src.translation
+
+ @property
+ def frame_src(self) -> str:
+ """Name of the source frame."""
+ return self._frame_src
+
+ @property
+ def frame_dst(self) -> str:
+ """Name of the destination frame."""
+ return self._frame_dst
+
+ @classmethod
+ def from_rt(
+ cls,
+ rotation: So3 | So2 | Tensor | Quaternion,
+ translation: Tensor,
+ frame_src: str | None = None,
+ frame_dst: str | None = None,
+ ) -> NamedPose | None:
+ """Construct NamedPose from rotation and translation.
+
+ Args:
+ rotation: Rotation part of the pose.
+ translation: Translation part of the pose.
+ frame_src: Name of the source frame.
+ frame_dst: Name of the destination frame.
+
+ Returns:
+ NamedPose constructed from rotation and translation.
+
+ Example:
+ >>> b_from_a_rot = So3.identity()
+ >>> b_from_a_trans = torch.tensor([1., 2., 3.])
+ >>> b_from_a = NamedPose.from_rt(b_from_a_rot, b_from_a_trans, frame_src="frame_a", frame_dst="frame_b")
+ >>> b_from_a
+ NamedPose(dst_from_src=rotation: Parameter containing:
+ tensor([1., 0., 0., 0.], requires_grad=True)
+ translation: Parameter containing:
+ tensor([1., 2., 3.], requires_grad=True),
+ frame_src: frame_a -> frame_dst: frame_b)
+ """
+ if isinstance(rotation, (So3, Quaternion)):
+ return cls(Se3(rotation, translation), frame_src, frame_dst)
+ elif isinstance(rotation, So2):
+ return cls(Se2(rotation, translation), frame_src, frame_dst)
+ elif isinstance(rotation, Tensor):
+ check_matrix_shape(rotation)
+ dim = rotation.shape[-1]
+ RT = eye(dim + 1, device=rotation.device, dtype=rotation.dtype)
+ RT[..., :dim, :dim] = rotation
+ RT[..., :dim, dim] = translation
+ if dim == 2:
+ return cls(Se2.from_matrix(RT), frame_src, frame_dst)
+ elif dim == 3:
+ return cls(Se3.from_matrix(RT), frame_src, frame_dst)
+ else:
+ raise ValueError(f"R must be either So2, So3, Quaternion, or Tensor, got {type(rotation)}")
+ return None
+
+ @classmethod
+ def from_matrix(
+ cls, matrix: Tensor, frame_src: str | None = None, frame_dst: str | None = None
+ ) -> NamedPose | None:
+ """Construct NamedPose from a matrix.
+
+ Args:
+ matrix: Matrix representation of the pose.
+ frame_src: Name of the source frame.
+ frame_dst: Name of the destination frame.
+
+ Returns:
+ NamedPose constructed from a matrix.
+
+ Example:
+ >>> b_from_a_matrix = Se3.identity().matrix()
+ >>> b_from_a = NamedPose.from_matrix(b_from_a_matrix, frame_src="frame_a", frame_dst="frame_b")
+ >>> b_from_a
+ NamedPose(dst_from_src=rotation: Parameter containing:
+ tensor([1., 0., 0., 0.], requires_grad=True)
+ translation: Parameter containing:
+ tensor([0., 0., 0.], requires_grad=True),
+ frame_src: frame_a -> frame_dst: frame_b)
+ """
+ check_matrix_shape(matrix, matrix_type="RT")
+ dim = matrix.shape[-1]
+ if dim == 3:
+ return cls(Se2.from_matrix(matrix), frame_src, frame_dst)
+ elif dim == 4:
+ return cls(Se3.from_matrix(matrix), frame_src, frame_dst)
+ return None
+
+ def inverse(self) -> NamedPose:
+ """Inverse of the NamedPose.
+
+ Returns:
+ Inverse of the NamedPose.
+
+ Example:
+ >>> b_from_a = NamedPose(Se3.identity(), frame_src="frame_a", frame_dst="frame_b")
+ >>> b_from_a.inverse()
+ NamedPose(dst_from_src=rotation: Parameter containing:
+ tensor([1., -0., -0., -0.], requires_grad=True)
+ translation: x: 0.0
+ y: 0.0
+ z: 0.0,
+ frame_src: frame_b -> frame_dst: frame_a)
+ """
+ return NamedPose(self._dst_from_src.inverse(), self._frame_dst, self._frame_src)
+
+ def transform_points(self, points_in_src: Tensor) -> Tensor:
+ """Transform points from source frame to destination frame.
+
+ Args:
+ points_in_src: Points in source frame.
+
+ Returns:
+ Points in destination frame.
+
+ Example:
+ >>> b_from_a = NamedPose(Se3.identity(), frame_src="frame_a", frame_dst="frame_b")
+ >>> b_from_a.transform_points(torch.tensor([1., 2., 3.]))
+ tensor([1., 2., 3.], grad_fn=<AddBackward0>)
+ """
+ return self._dst_from_src * points_in_src
diff --git a/test/geometry/test_pose.py b/test/geometry/test_pose.py
new file mode 100644
index 000000000..e76e9ba99
--- /dev/null
+++ b/test/geometry/test_pose.py
@@ -0,0 +1,113 @@
+import pytest
+import torch
+
+from kornia.geometry import NamedPose
+from kornia.geometry.liegroup import Se2, Se3, So2, So3
+from kornia.testing import BaseTester
+
+
+class TestNamedPose(BaseTester):
+ def test_smoke(self, device, dtype):
+ b_from_a = Se3.identity(device=device, dtype=dtype)
+ pose = NamedPose(b_from_a, frame_src="frame_a", frame_dst="frame_b")
+ assert isinstance(pose, NamedPose)
+ assert isinstance(pose.pose, Se3)
+
+ @pytest.mark.skip(reason="not implemented yet")
+ def test_cardinality(self, device, dtype):
+ pass
+
+ @pytest.mark.skip(reason="not implemented yet")
+ def test_jit(self, device, dtype):
+ pass
+
+ @pytest.mark.skip(reason="not implemented yet")
+ def test_exception(self, device, dtype):
+ pass
+
+ @pytest.mark.skip(reason="not implemented yet")
+ def test_module(self, device, dtype):
+ pass
+
+ @pytest.mark.skip(reason="not implemented yet")
+ def test_gradcheck(self, device):
+ pass
+
+ def test_mul(self, device, dtype):
+ b_from_a = NamedPose(
+ Se3.trans_x(torch.tensor([1.0], device=device, dtype=dtype)), frame_src="frame_a", frame_dst="frame_b"
+ )
+ c_from_b = NamedPose(
+ Se3.trans_y(torch.tensor([1.0], device=device, dtype=dtype)), frame_src="frame_b", frame_dst="frame_c"
+ )
+ c_from_a = c_from_b * b_from_a
+ assert isinstance(c_from_a, NamedPose)
+ assert isinstance(c_from_a.pose, Se3)
+ assert c_from_a.frame_src == "frame_a"
+ assert c_from_a.frame_dst == "frame_c"
+
+ def test_from_rt(self, device, dtype):
+ b_from_a_rotation = So3.random(device=device, dtype=dtype)
+ b_from_a_translation = torch.tensor([1.0, 2.0, 3.0], device=device, dtype=dtype)
+ b_from_a = NamedPose.from_rt(b_from_a_rotation, b_from_a_translation, frame_src="frame_a", frame_dst="frame_b")
+ assert isinstance(b_from_a, NamedPose)
+ assert isinstance(b_from_a.pose, Se3)
+
+ b_from_a_rotation = So2.random(device=device, dtype=dtype)
+ b_from_a_translation = torch.tensor([1.0, 2.0], device=device, dtype=dtype)
+ b_from_a = NamedPose.from_rt(b_from_a_rotation, b_from_a_translation, frame_src="frame_a", frame_dst="frame_b")
+ assert isinstance(b_from_a, NamedPose)
+ assert isinstance(b_from_a.pose, Se2)
+
+ b_from_a_rotation = torch.eye(3, device=device, dtype=dtype)
+ b_from_a_translation = torch.tensor([1.0, 2.0, 3.0], device=device, dtype=dtype)
+ b_from_a = NamedPose.from_rt(b_from_a_rotation, b_from_a_translation, frame_src="frame_a", frame_dst="frame_b")
+ assert isinstance(b_from_a, NamedPose)
+ assert isinstance(b_from_a.pose, Se3)
+
+ b_from_a_rotation = torch.eye(2, device=device, dtype=dtype)
+ b_from_a_translation = torch.tensor([1.0, 2.0], device=device, dtype=dtype)
+ b_from_a = NamedPose.from_rt(b_from_a_rotation, b_from_a_translation, frame_src="frame_a", frame_dst="frame_b")
+ assert isinstance(b_from_a, NamedPose)
+ assert isinstance(b_from_a.pose, Se2)
+
+ def test_from_matrix(self, device, dtype):
+ b_from_a_matrix = Se3.identity(device=device, dtype=dtype).matrix()
+ b_from_a = NamedPose.from_matrix(b_from_a_matrix, frame_src="frame_a", frame_dst="frame_b")
+ point_in_a = torch.tensor([1.0, 2.0, 3.0], device=device, dtype=dtype)
+ point_in_b = b_from_a.transform_points(point_in_a)
+ self.assert_close(point_in_b, point_in_a)
+ assert isinstance(b_from_a, NamedPose)
+ assert isinstance(b_from_a.pose, Se3)
+
+ b_from_a_matrix = torch.eye(3, device=device, dtype=dtype)
+ b_from_a = NamedPose.from_matrix(b_from_a_matrix, frame_src="frame_a", frame_dst="frame_b")
+ point_in_a = torch.tensor([1.0, 2.0], device=device, dtype=dtype)
+ point_in_b = b_from_a.transform_points(point_in_a)
+ self.assert_close(point_in_b, point_in_a)
+ assert isinstance(b_from_a, NamedPose)
+ assert isinstance(b_from_a.pose, Se2)
+
+ def test_inverse(self, device, dtype):
+ b_from_a = NamedPose(
+ Se3.trans_x(torch.tensor([1.0], device=device, dtype=dtype)), frame_src="frame_a", frame_dst="frame_b"
+ )
+ a_from_b = b_from_a.inverse()
+ assert isinstance(a_from_b, NamedPose)
+ assert isinstance(a_from_b.pose, Se3)
+ assert a_from_b.frame_src == "frame_b"
+ assert a_from_b.frame_dst == "frame_a"
+
+ @pytest.mark.parametrize("batch_size", (None, 1, 2, 5))
+ def transform_points(self, device, dtype, batch_size):
+ if batch_size is None:
+ points_in_a = torch.randn(3, device=device, dtype=dtype)
+ b_from_a_se3 = Se3.trans_x(torch.tensor(1.0, device=device, dtype=dtype))
+ else:
+ points_in_a = torch.randn(batch_size, 3, device=device, dtype=dtype)
+ b_from_a_se3 = Se3.trans_x(torch.tensor([1.0], device=device, dtype=dtype))
+ b_from_a = NamedPose(b_from_a_se3, frame_src="frame_a", frame_dst="frame_b")
+ a_from_b = b_from_a.inverse()
+ points_in_b = b_from_a.transform_points(points_in_a)
+ assert points_in_b.shape == points_in_a.shape
+ self.assert_close(a_from_b.transform_points(points_in_b), points_in_a)