Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

add quaternion to euler conversion (#1994)

Edgar Riba3c469499ecd8
diff --git a/docs/source/geometry.conversions.rst b/docs/source/geometry.conversions.rst
index 002cbaa95..92934d3c7 100644
--- a/docs/source/geometry.conversions.rst
+++ b/docs/source/geometry.conversions.rst
@@ -54,6 +54,12 @@ Angle Axis
.. autofunction:: angle_axis_to_quaternion
.. autofunction:: angle_axis_to_rotation_matrix
+Euler Angles
+------------
+
+.. autofuction:: quaternion_from_euler
+.. autofuction:: euler_from_quaternion
+
Pose
----------
diff --git a/kornia/geometry/conversions.py b/kornia/geometry/conversions.py
index c88712aa0..b1a490f77 100644
--- a/kornia/geometry/conversions.py
+++ b/kornia/geometry/conversions.py
@@ -7,7 +7,7 @@ import torch.nn.functional as F
from kornia.constants import pi
from kornia.core import Tensor, concatenate, stack, tensor
-from kornia.testing import KORNIA_CHECK_SHAPE
+from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_SHAPE
from kornia.utils.helpers import _torch_inverse_cast
__all__ = [
@@ -27,6 +27,8 @@ __all__ = [
"quaternion_to_rotation_matrix",
"quaternion_log_to_exp",
"quaternion_exp_to_log",
+ "quaternion_from_euler",
+ "euler_from_quaternion",
"denormalize_pixel_coordinates",
"normalize_pixel_coordinates",
"normalize_quaternion",
@@ -852,6 +854,79 @@ def angle_axis_to_quaternion(angle_axis: Tensor, order: QuaternionCoeffOrder = Q
return quaternion
+# inspired by: https://stackoverflow.com/questions/56207448/efficient-quaternions-to-euler-transformation
+
+
+def euler_from_quaternion(w: Tensor, x: Tensor, y: Tensor, z: Tensor) -> Tuple[Tensor, Tensor, Tensor]:
+ """Convert a quaternion coefficients to Euler angles.
+
+ Returned angles are in radians in XYZ convention.
+
+ Args:
+ w: quaternion :math:`q_w` coefficient.
+ x: quaternion :math:`q_x` coefficient.
+ y: quaternion :math:`q_y` coefficient.
+ z: quaternion :math:`q_z` coefficient.
+
+ Return:
+ A tuple with euler angles`roll`, `pitch`, `yaw`.
+ """
+ KORNIA_CHECK(w.shape == x.shape)
+ KORNIA_CHECK(x.shape == y.shape)
+ KORNIA_CHECK(y.shape == z.shape)
+
+ yy = y * y
+
+ sinr_cosp = 2.0 * (w * x + y * z)
+ cosr_cosp = 1.0 - 2.0 * (x * x + yy)
+ roll = sinr_cosp.atan2(cosr_cosp)
+
+ sinp = 2.0 * (w * y - z * x)
+ sinp = sinp.clamp(min=-1.0, max=1.0)
+ pitch = sinp.asin()
+
+ siny_cosp = 2.0 * (w * z + x * y)
+ cosy_cosp = 1.0 - 2.0 * (yy + z * z)
+ yaw = siny_cosp.atan2(cosy_cosp)
+
+ return roll, pitch, yaw
+
+
+def quaternion_from_euler(roll: Tensor, pitch: Tensor, yaw: Tensor) -> Tuple[Tensor, Tensor, Tensor, Tensor]:
+ """Convert Euler angles to quaternion coefficients.
+
+ Euler angles are assumed to be in radians in XYZ convention.
+
+ Args:
+ roll: the roll euler angle.
+ pitch: the pitch euler angle.
+ yaw: the yaw euler angle.
+
+ Return:
+ A tuple with quaternion coefficients in order of `wxyz`.
+ """
+ KORNIA_CHECK(roll.shape == pitch.shape)
+ KORNIA_CHECK(pitch.shape == yaw.shape)
+
+ roll_half = roll * 0.5
+ pitch_half = pitch * 0.5
+ yaw_half = yaw * 0.5
+
+ cy = yaw_half.cos()
+ sy = yaw_half.sin()
+ cp = pitch_half.cos()
+ sp = pitch_half.sin()
+ cr = roll_half.cos()
+ sr = roll_half.sin()
+
+ qw = cy * cp * cr + sy * sp * sr
+ qx = cy * cp * sr - sy * sp * cr
+ qy = sy * cp * sr + cy * sp * cr
+ qz = sy * cp * cr - cy * sp * sr
+
+ return qw, qx, qy, qz
+
+
# based on:
# https://github.com/ClementPinard/SfmLearner-Pytorch/blob/master/inverse_warp.py#L65-L71
diff --git a/kornia/geometry/quaternion.py b/kornia/geometry/quaternion.py
index 858f52dad..b56c976f9 100644
--- a/kornia/geometry/quaternion.py
+++ b/kornia/geometry/quaternion.py
@@ -314,6 +314,8 @@ class Quaternion(Module):
"""
return cls(as_tensor([[w, x, y, z]]))
+ # TODO: update signature
+ # def random(cls, shape: Optional[List] = None, device = None, dtype = None) -> 'Quaternion':
@classmethod
def random(cls, batch_size: int) -> 'Quaternion':
"""Create a random unit quaternion of shape :math:`(B,4)`.
diff --git a/test/geometry/test_conversions.py b/test/geometry/test_conversions.py
index f441b81ce..7caa727fa 100644
--- a/test/geometry/test_conversions.py
+++ b/test/geometry/test_conversions.py
@@ -15,10 +15,13 @@ from kornia.geometry.conversions import (
camtoworld_to_worldtocam_Rt,
camtoworld_vision_to_graphics_4x4,
camtoworld_vision_to_graphics_Rt,
+ euler_from_quaternion,
matrix4x4_to_Rt,
+ quaternion_from_euler,
worldtocam_to_camtoworld_Rt,
)
-from kornia.testing import assert_close, create_eye_batch, tensor_to_gradcheck_var
+from kornia.geometry.quaternion import Quaternion
+from kornia.testing import BaseTester, assert_close, create_eye_batch, tensor_to_gradcheck_var
@pytest.fixture
@@ -1631,3 +1634,140 @@ class TestCARKitToColmap:
assert_close(angles_colmap, expected_angles, rtol=1e-4, atol=1e-5)
assert_close(t_colmap, expected_t, rtol=1e-4, atol=1e-5)
+
+
+class TestEulerFromQuaternion(BaseTester):
+ def test_smoke(self, device, dtype):
+ q = Quaternion.random(batch_size=1)
+ q = q.to(device, dtype)
+ roll, pitch, yaw = euler_from_quaternion(q.w, q.x, q.y, q.z)
+ assert roll.shape == pitch.shape
+ assert pitch.shape == yaw.shape
+
+ @pytest.mark.parametrize("batch_size", ((1, 3, 4)))
+ def test_cardinality(self, device, dtype, batch_size):
+ q = Quaternion.random(batch_size=batch_size)
+ q = q.to(device, dtype)
+ roll, pitch, yaw = euler_from_quaternion(q.w, q.x, q.y, q.z)
+ assert roll.shape[0] == batch_size
+ assert pitch.shape[0] == batch_size
+ assert yaw.shape[0] == batch_size
+
+ def test_exception(self, device, dtype):
+ q = Quaternion.random(batch_size=2)
+ q = q.to(device, dtype)
+ with pytest.raises(Exception):
+ euler_from_quaternion(q.w, torch.rand(1), q.y, q.z)
+
+ def test_gradcheck(self, device):
+ q = Quaternion.random(batch_size=1).to(device, torch.float64)
+ assert gradcheck(euler_from_quaternion, (q.w, q.x, q.y, q.z), raise_exception=True)
+
+ def test_module(self, device, dtype):
+ pass
+
+ def test_jit(self, device, dtype):
+ q = Quaternion.random(batch_size=1)
+ q = q.to(device, dtype)
+ op = euler_from_quaternion
+ op_jit = torch.jit.script(op)
+ assert_close(op(q.w, q.x, q.y, q.z), op_jit(q.w, q.x, q.y, q.z))
+
+ def test_forth_and_back(self, device, dtype):
+ q = Quaternion.random(batch_size=2)
+ q = q.to(device, dtype)
+ roll, pitch, yaw = euler_from_quaternion(q.w, q.x, q.y, q.z)
+ qw, qx, qy, qz = quaternion_from_euler(roll, pitch, yaw)
+ # TODO: check hwo to prevent getting inverted angles sometimes
+ assert_close(q.w.abs(), qw.abs())
+ assert_close(q.x.abs(), qx.abs())
+ assert_close(q.y.abs(), qy.abs())
+ assert_close(q.z.abs(), qz.abs())
+
+
+class TestQuaternionFromEuler(BaseTester):
+ def test_smoke(self, device, dtype):
+ roll, pitch, yaw = torch.rand(3, device=device, dtype=dtype)
+ qw, qx, qy, qz = quaternion_from_euler(roll, pitch, yaw)
+ assert qw.shape == qx.shape
+ assert qx.shape == qy.shape
+ assert qy.shape == qz.shape
+
+ @pytest.mark.parametrize("batch_size", ((1, 3, 4)))
+ def test_cardinality(self, device, dtype, batch_size):
+ roll, pitch, yaw = torch.rand(3, batch_size, device=device, dtype=dtype)
+ qw, qx, qy, qz = quaternion_from_euler(roll, pitch, yaw)
+ assert qw.shape[0] == batch_size
+ assert qx.shape[0] == batch_size
+ assert qy.shape[0] == batch_size
+ assert qz.shape[0] == batch_size
+
+ def test_exception(self, device, dtype):
+ _, pitch, yaw = torch.rand(3, 2, device=device, dtype=dtype)
+ with pytest.raises(Exception):
+ quaternion_from_euler(torch.rand(1), pitch, yaw)
+
+ def test_gradcheck(self, device):
+ roll, pitch, yaw = torch.rand(3, 2, device=device, dtype=torch.float64, requires_grad=True)
+ assert gradcheck(quaternion_from_euler, (roll, pitch, yaw), raise_exception=True)
+
+ def test_module(self, device, dtype):
+ pass
+
+ @pytest.mark.skip()
+ def test_jit(self, device, dtype):
+ roll, pitch, yaw = torch.rand(3, 2, device=device, dtype=dtype)
+ op = quaternion_from_euler
+ op_jit = torch.jit.script(op)
+ assert_close(op(roll, pitch, yaw), op_jit(roll, pitch, yaw))
+
+ def test_forth_and_back(self, device, dtype):
+ roll, pitch, yaw = torch.rand(3, 2, device=device, dtype=dtype)
+ qw, qx, qy, qz = quaternion_from_euler(roll, pitch, yaw)
+ roll_new, pitch_new, yaw_new = euler_from_quaternion(qw, qx, qy, qz)
+ assert_close(roll, roll_new)
+ assert_close(pitch, pitch_new)
+ assert_close(yaw, yaw_new)
+
+ def test_values(self, device, dtype):
+ # num_samples = 5
+ # data = 2 * torch.rand(3, num_samples, device=device, dtype=dtype) - 1
+ # roll, pitch, yaw = torch.pi * data
+ roll = torch.tensor(
+ [2.6518599987, 0.0612506270, 1.2417907715, 2.8829660416, -1.9961174726], device=device, dtype=dtype
+ )
+
+ pitch = torch.tensor(
+ [2.3267219067, -2.7309591770, -1.4011553526, -2.1962766647, 2.1454355717], device=device, dtype=dtype
+ )
+
+ yaw = torch.tensor(
+ [-0.8856627345, 0.2605336905, 0.4579202533, -1.3095731735, 0.6096843481], device=device, dtype=dtype
+ )
+
+ euler_expected = torch.tensor(
+ [
+ [-0.4897327125, 0.8148705959, 2.2559301853],
+ [-3.0803420544, -0.4106334746, -2.8810589314],
+ [1.2417914867, -1.4011553526, 0.4579201937],
+ [-0.2586266696, -0.9453159571, 1.8320195675],
+ [1.1454752684, 0.9961569905, -2.5319085121],
+ ],
+ device=device,
+ dtype=dtype,
+ )
+
+ qw, qx, qy, qz = quaternion_from_euler(roll, pitch, yaw)
+ euler = euler_from_quaternion(qw, qx, qy, qz)
+ euler = torch.stack(euler, -1)
+
+ self.assert_close(euler, euler_expected, 1e-4, 1e-4)
+
+ # this test is passing: pip install transforms3d
+ # import transforms3d as tf3
+ # out = [tf3.euler.euler2quat(roll[i], pitch[i], yaw[i]) for i in range(num_samples)]
+ # out = torch.tensor(out, device=device, dtype=dtype)
+ # self.assert_close(torch.stack((qw, qx, qy, qz), -1), out)
+
+ # out = [tf3.euler.quat2euler((qw[i], qx[i], qy[i], qz[i])) for i in range(num_samples)]
+ # out = torch.tensor(out, device=device, dtype=dtype)