Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Quaternion from axis angle representation (#1917)

Christie Jacob09ebcc4a377f
diff --git a/kornia/geometry/quaternion.py b/kornia/geometry/quaternion.py
index 82e92b466..b2c64c58d 100644
--- a/kornia/geometry/quaternion.py
+++ b/kornia/geometry/quaternion.py
@@ -8,6 +8,7 @@ from typing import Tuple, Union
from kornia.core import Module, Parameter, Tensor, as_tensor, concatenate, rand, stack
from kornia.geometry.conversions import (
QuaternionCoeffOrder,
+ angle_axis_to_quaternion,
normalize_quaternion,
quaternion_to_rotation_matrix,
rotation_matrix_to_quaternion,
@@ -244,6 +245,22 @@ class Quaternion(Module):
"""
return cls(rotation_matrix_to_quaternion(matrix, order=QuaternionCoeffOrder.WXYZ))
+ @classmethod
+ def from_axis_angle(cls, axis_angle: Tensor) -> 'Quaternion':
+ """Create a quaternion from axis-angle representation.
+
+ Args:
+ axis_angle: rotation vector of shape :math:`(B,3)`.
+
+ Example:
+ >>> axis_angle = torch.tensor([[1., 0., 0.]])
+ >>> q = Quaternion.from_axis_angle(axis_angle)
+ >>> q.data
+ Parameter containing:
+ tensor([[0.8776, 0.4794, 0.0000, 0.0000]], requires_grad=True)
+ """
+ return cls(angle_axis_to_quaternion(axis_angle, order=QuaternionCoeffOrder.WXYZ))
+
@classmethod
def identity(cls, batch_size: int) -> 'Quaternion':
"""Create a quaternion representing an identity rotation.
diff --git a/test/geometry/test_quaternion.py b/test/geometry/test_quaternion.py
index 0a9eb351d..a44db4c02 100644
--- a/test/geometry/test_quaternion.py
+++ b/test/geometry/test_quaternion.py
@@ -186,3 +186,14 @@ class TestQuaternion:
for i in range(batch_size):
q1 = q[i]
self.assert_close(q1.data[0], q.data[i])
+
+ @pytest.mark.parametrize("batch_size", (1, 2, 5))
+ def test_axis_angle(self, device, dtype, batch_size):
+ q1 = Quaternion.random(batch_size)
+ q1 = q1.to(device, dtype)
+ angle = 2 * q1.scalar.arccos()
+ axis = q1.vec / (angle / 2).sin()
+ axis_angle = axis * angle
+ q2 = Quaternion.from_axis_angle(axis_angle)
+ q2 = q2.to(device, dtype)
+ self.assert_close(q1, q2)