Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Fixes angle axis to quaternion order bug (#926)

Aron Monszpart5c191482ed3e
diff --git a/kornia/geometry/conversions.py b/kornia/geometry/conversions.py
index f987bfbff..3abbac627 100644
--- a/kornia/geometry/conversions.py
+++ b/kornia/geometry/conversions.py
@@ -1,7 +1,9 @@
+import warnings
from typing import Tuple
import torch
import torch.nn as nn
import torch.nn.functional as F
+import enum
from kornia.constants import pi
@@ -31,6 +33,11 @@ __all__ = [
]
+class QuaternionCoeffOrder(enum.Enum):
+ XYZW = 'xyzw'
+ WXYZ = 'wxyz'
+
+
def rad2deg(tensor: torch.Tensor) -> torch.Tensor:
r"""Function that converts angles from radians to degrees.
@@ -96,7 +103,8 @@ def pol2cart(rho: torch.Tensor, phi: torch.Tensor) -> Tuple[torch.Tensor, torch.
return x, y
-def cart2pol(x: torch.Tensor, y: torch.Tensor, eps: float = 1e-8) -> Tuple[torch.Tensor, torch.Tensor]:
+def cart2pol(x: torch.Tensor, y: torch.Tensor,
+ eps: float = 1.e-8) -> Tuple[torch.Tensor, torch.Tensor]:
"""Function that converts cartesian coordinates to polar coordinates.
Args:
@@ -291,8 +299,7 @@ def angle_axis_to_rotation_matrix(angle_axis: torch.Tensor) -> torch.Tensor:
return rotation_matrix # Nx3x3
-def rotation_matrix_to_angle_axis(
- rotation_matrix: torch.Tensor) -> torch.Tensor:
+def rotation_matrix_to_angle_axis(rotation_matrix: torch.Tensor) -> torch.Tensor:
r"""Convert 3x3 rotation matrix to Rodrigues vector.
Args:
@@ -310,26 +317,31 @@ def rotation_matrix_to_angle_axis(
>>> output = rotation_matrix_to_angle_axis(input) # Nx3
"""
if not isinstance(rotation_matrix, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}".format(
- type(rotation_matrix)))
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(rotation_matrix)}")
if not rotation_matrix.shape[-2:] == (3, 3):
- raise ValueError(
- "Input size must be a (*, 3, 3) tensor. Got {}".format(
- rotation_matrix.shape))
- quaternion: torch.Tensor = rotation_matrix_to_quaternion(rotation_matrix)
- return quaternion_to_angle_axis(quaternion)
+ raise ValueError(f"Input size must be a (*, 3, 3) tensor. Got {rotation_matrix.shape}")
+ quaternion: torch.Tensor = rotation_matrix_to_quaternion(rotation_matrix,
+ order=QuaternionCoeffOrder.WXYZ)
+ return quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.WXYZ)
def rotation_matrix_to_quaternion(
rotation_matrix: torch.Tensor,
- eps: float = 1e-8) -> torch.Tensor:
+ eps: float = 1.e-8,
+ order: QuaternionCoeffOrder = QuaternionCoeffOrder.XYZW) -> torch.Tensor:
r"""Convert 3x3 rotation matrix to 4d quaternion vector.
- The quaternion vector has components in (x, y, z, w) format.
+
+ The quaternion vector has components in (w, x, y, z) or (x, y, z, w) format.
+
+ .. note::
+ The (x, y, z, w) order is going to be deprecated in favor of efficiency.
Args:
rotation_matrix (torch.Tensor): the rotation matrix to convert.
eps (float): small value to avoid zero division. Default: 1e-8.
+ order (QuaternionCoeffOrder): quaternion coefficient order. Default: 'xyzw'.
+ Note: 'xyzw' will be deprecated in favor of 'wxyz'.
Return:
torch.Tensor: the rotation in quaternion.
@@ -340,16 +352,23 @@ def rotation_matrix_to_quaternion(
Example:
>>> input = torch.rand(4, 3, 3) # Nx3x3
- >>> output = rotation_matrix_to_quaternion(input) # Nx4
+ >>> output = rotation_matrix_to_quaternion(input, eps=torch.finfo(input.dtype).eps,
+ ... order=QuaternionCoeffOrder.WXYZ) # Nx4
"""
if not isinstance(rotation_matrix, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}".format(
- type(rotation_matrix)))
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(rotation_matrix)}")
if not rotation_matrix.shape[-2:] == (3, 3):
- raise ValueError(
- "Input size must be a (*, 3, 3) tensor. Got {}".format(
- rotation_matrix.shape))
+ raise ValueError(f"Input size must be a (*, 3, 3) tensor. Got {rotation_matrix.shape}")
+
+ if not torch.jit.is_scripting():
+ if order.name not in QuaternionCoeffOrder.__members__.keys():
+ raise ValueError(f"order must be one of {QuaternionCoeffOrder.__members__.keys()}")
+
+ if order == QuaternionCoeffOrder.XYZW:
+ warnings.warn("`XYZW` quaternion coefficient order is deprecated and"
+ " will be removed after > 0.6. "
+ "Please use `QuaternionCoeffOrder.WXYZ` instead.")
def safe_zero_division(numerator: torch.Tensor,
denominator: torch.Tensor) -> torch.Tensor:
@@ -370,7 +389,10 @@ def rotation_matrix_to_quaternion(
qx = safe_zero_division(m21 - m12, sq)
qy = safe_zero_division(m02 - m20, sq)
qz = safe_zero_division(m10 - m01, sq)
- return torch.cat([qx, qy, qz, qw], dim=-1)
+ if order == QuaternionCoeffOrder.XYZW:
+ return torch.cat((qx, qy, qz, qw), dim=-1)
+ else:
+ return torch.cat((qw, qx, qy, qz), dim=-1)
def cond_1():
sq = torch.sqrt(1.0 + m00 - m11 - m22 + eps) * 2. # sq = 4 * qx.
@@ -378,7 +400,10 @@ def rotation_matrix_to_quaternion(
qx = 0.25 * sq
qy = safe_zero_division(m01 + m10, sq)
qz = safe_zero_division(m02 + m20, sq)
- return torch.cat([qx, qy, qz, qw], dim=-1)
+ if order == QuaternionCoeffOrder.XYZW:
+ return torch.cat((qx, qy, qz, qw), dim=-1)
+ else:
+ return torch.cat((qw, qx, qy, qz), dim=-1)
def cond_2():
sq = torch.sqrt(1.0 + m11 - m00 - m22 + eps) * 2. # sq = 4 * qy.
@@ -386,7 +411,10 @@ def rotation_matrix_to_quaternion(
qx = safe_zero_division(m01 + m10, sq)
qy = 0.25 * sq
qz = safe_zero_division(m12 + m21, sq)
- return torch.cat([qx, qy, qz, qw], dim=-1)
+ if order == QuaternionCoeffOrder.XYZW:
+ return torch.cat((qx, qy, qz, qw), dim=-1)
+ else:
+ return torch.cat((qw, qx, qy, qz), dim=-1)
def cond_3():
sq = torch.sqrt(1.0 + m22 - m00 - m11 + eps) * 2. # sq = 4 * qz.
@@ -394,20 +422,22 @@ def rotation_matrix_to_quaternion(
qx = safe_zero_division(m02 + m20, sq)
qy = safe_zero_division(m12 + m21, sq)
qz = 0.25 * sq
- return torch.cat([qx, qy, qz, qw], dim=-1)
+ if order == QuaternionCoeffOrder.XYZW:
+ return torch.cat((qx, qy, qz, qw), dim=-1)
+ else:
+ return torch.cat((qw, qx, qy, qz), dim=-1)
where_2 = torch.where(m11 > m22, cond_2(), cond_3())
- where_1 = torch.where(
- (m00 > m11) & (m00 > m22), cond_1(), where_2)
+ where_1 = torch.where((m00 > m11) & (m00 > m22), cond_1(), where_2)
- quaternion: torch.Tensor = torch.where(
- trace > 0., trace_positive_cond(), where_1)
+ quaternion: torch.Tensor = torch.where(trace > 0., trace_positive_cond(), where_1)
return quaternion
def normalize_quaternion(quaternion: torch.Tensor,
- eps: float = 1e-12) -> torch.Tensor:
+ eps: float = 1.e-12) -> torch.Tensor:
r"""Normalizes a quaternion.
+
The quaternion should be in (x, y, z, w) format.
Args:
@@ -420,7 +450,7 @@ def normalize_quaternion(quaternion: torch.Tensor,
torch.Tensor: the normalized quaternion of shape :math:`(*, 4)`.
Example:
- >>> quaternion = torch.tensor([1., 0., 1., 0.])
+ >>> quaternion = torch.tensor((1., 0., 1., 0.))
>>> normalize_quaternion(quaternion)
tensor([0.7071, 0.0000, 0.7071, 0.0000])
"""
@@ -439,37 +469,52 @@ def normalize_quaternion(quaternion: torch.Tensor,
# https://github.com/matthew-brett/transforms3d/blob/8965c48401d9e8e66b6a8c37c65f2fc200a076fa/transforms3d/quaternions.py#L101
# https://github.com/tensorflow/graphics/blob/master/tensorflow_graphics/geometry/transformation/rotation_matrix_3d.py#L247
-def quaternion_to_rotation_matrix(quaternion: torch.Tensor) -> torch.Tensor:
+def quaternion_to_rotation_matrix(
+ quaternion: torch.Tensor,
+ order: QuaternionCoeffOrder = QuaternionCoeffOrder.XYZW) -> torch.Tensor:
r"""Converts a quaternion to a rotation matrix.
- The quaternion should be in (x, y, z, w) format.
+
+ The quaternion should be in (x, y, z, w) or (w, x, y, z) format.
Args:
quaternion (torch.Tensor): a tensor containing a quaternion to be
converted. The tensor can be of shape :math:`(*, 4)`.
+ order (QuaternionCoeffOrder): quaternion coefficient order. Default: 'xyzw'.
+ Note: 'xyzw' will be deprecated in favor of 'wxyz'.
Return:
torch.Tensor: the rotation matrix of shape :math:`(*, 3, 3)`.
Example:
- >>> quaternion = torch.tensor([0., 0., 1., 0.])
- >>> quaternion_to_rotation_matrix(quaternion)
+ >>> quaternion = torch.tensor((0., 0., 0., 1.))
+ >>> quaternion_to_rotation_matrix(quaternion, order=QuaternionCoeffOrder.WXYZ)
tensor([[-1., 0., 0.],
[ 0., -1., 0.],
[ 0., 0., 1.]])
"""
if not isinstance(quaternion, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}".format(
- type(quaternion)))
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(quaternion)}")
if not quaternion.shape[-1] == 4:
- raise ValueError(
- "Input must be a tensor of shape (*, 4). Got {}".format(
- quaternion.shape))
+ raise ValueError(f"Input must be a tensor of shape (*, 4). Got {quaternion.shape}")
+
+ if not torch.jit.is_scripting():
+ if order.name not in QuaternionCoeffOrder.__members__.keys():
+ raise ValueError(f"order must be one of {QuaternionCoeffOrder.__members__.keys()}")
+
+ if order == QuaternionCoeffOrder.XYZW:
+ warnings.warn("`XYZW` quaternion coefficient order is deprecated and"
+ " will be removed after > 0.6. "
+ "Please use `QuaternionCoeffOrder.WXYZ` instead.")
+
# normalize the input quaternion
quaternion_norm: torch.Tensor = normalize_quaternion(quaternion)
# unpack the normalized quaternion components
- x, y, z, w = torch.chunk(quaternion_norm, chunks=4, dim=-1)
+ if order == QuaternionCoeffOrder.XYZW:
+ x, y, z, w = torch.chunk(quaternion_norm, chunks=4, dim=-1)
+ else:
+ w, x, y, z = torch.chunk(quaternion_norm, chunks=4, dim=-1)
# compute the actual conversion
tx: torch.Tensor = 2.0 * x
@@ -486,25 +531,30 @@ def quaternion_to_rotation_matrix(quaternion: torch.Tensor) -> torch.Tensor:
tzz: torch.Tensor = tz * z
one: torch.Tensor = torch.tensor(1.)
- matrix: torch.Tensor = torch.stack([
+ matrix: torch.Tensor = torch.stack((
one - (tyy + tzz), txy - twz, txz + twy,
txy + twz, one - (txx + tzz), tyz - twx,
txz - twy, tyz + twx, one - (txx + tyy)
- ], dim=-1).view(-1, 3, 3)
+ ), dim=-1).view(-1, 3, 3)
if len(quaternion.shape) == 1:
matrix = torch.squeeze(matrix, dim=0)
return matrix
-def quaternion_to_angle_axis(quaternion: torch.Tensor) -> torch.Tensor:
+def quaternion_to_angle_axis(
+ quaternion: torch.Tensor,
+ order: QuaternionCoeffOrder = QuaternionCoeffOrder.XYZW) -> torch.Tensor:
"""Convert quaternion vector to angle axis of rotation.
- The quaternion should be in (x, y, z, w) format.
+
+ The quaternion should be in (x, y, z, w) or (w, x, y, z) format.
Adapted from ceres C++ library: ceres-solver/include/ceres/rotation.h
Args:
quaternion (torch.Tensor): tensor with quaternions.
+ order (QuaternionCoeffOrder): quaternion coefficient order. Default: 'xyzw'.
+ Note: 'xyzw' will be deprecated in favor of 'wxyz'.
Return:
torch.Tensor: tensor with angle axis of rotation.
@@ -518,24 +568,42 @@ def quaternion_to_angle_axis(quaternion: torch.Tensor) -> torch.Tensor:
>>> angle_axis = quaternion_to_angle_axis(quaternion) # Nx3
"""
if not torch.is_tensor(quaternion):
- raise TypeError("Input type is not a torch.Tensor. Got {}".format(
- type(quaternion)))
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(quaternion)}")
if not quaternion.shape[-1] == 4:
- raise ValueError(
- "Input must be a tensor of shape Nx4 or 4. Got {}".format(
- quaternion.shape))
+ raise ValueError(f"Input must be a tensor of shape Nx4 or 4. Got {quaternion.shape}")
+
+ if not torch.jit.is_scripting():
+ if order.name not in QuaternionCoeffOrder.__members__.keys():
+ raise ValueError(f"order must be one of {QuaternionCoeffOrder.__members__.keys()}")
+
+ if order == QuaternionCoeffOrder.XYZW:
+ warnings.warn("`XYZW` quaternion coefficient order is deprecated and"
+ " will be removed after > 0.6. "
+ "Please use `QuaternionCoeffOrder.WXYZ` instead.")
# unpack input and compute conversion
- q1: torch.Tensor = quaternion[..., 1]
- q2: torch.Tensor = quaternion[..., 2]
- q3: torch.Tensor = quaternion[..., 3]
+ q1: torch.Tensor = torch.tensor([])
+ q2: torch.Tensor = torch.tensor([])
+ q3: torch.Tensor = torch.tensor([])
+ cos_theta: torch.Tensor = torch.tensor([])
+
+ if order == QuaternionCoeffOrder.XYZW:
+ q1 = quaternion[..., 0]
+ q2 = quaternion[..., 1]
+ q3 = quaternion[..., 2]
+ cos_theta = quaternion[..., 3]
+ else:
+ cos_theta = quaternion[..., 0]
+ q1 = quaternion[..., 1]
+ q2 = quaternion[..., 2]
+ q3 = quaternion[..., 3]
+
sin_squared_theta: torch.Tensor = q1 * q1 + q2 * q2 + q3 * q3
sin_theta: torch.Tensor = torch.sqrt(sin_squared_theta)
- cos_theta: torch.Tensor = quaternion[..., 0]
- two_theta: torch.Tensor = 2.0 * torch.where(
- cos_theta < 0.0, torch.atan2(-sin_theta, -cos_theta),
- torch.atan2(sin_theta, cos_theta))
+ two_theta: torch.Tensor = 2.0 * torch.where(cos_theta < 0.0,
+ torch.atan2(-sin_theta, -cos_theta),
+ torch.atan2(sin_theta, cos_theta))
k_pos: torch.Tensor = two_theta / sin_theta
k_neg: torch.Tensor = 2.0 * torch.ones_like(sin_theta)
@@ -548,73 +616,110 @@ def quaternion_to_angle_axis(quaternion: torch.Tensor) -> torch.Tensor:
return angle_axis
-def quaternion_log_to_exp(quaternion: torch.Tensor,
- eps: float = 1e-8) -> torch.Tensor:
+def quaternion_log_to_exp(
+ quaternion: torch.Tensor,
+ eps: float = 1.e-8,
+ order: QuaternionCoeffOrder = QuaternionCoeffOrder.XYZW) -> torch.Tensor:
r"""Applies exponential map to log quaternion.
- The quaternion should be in (x, y, z, w) format.
+
+ The quaternion should be in (x, y, z, w) or (w, x, y, z) format.
Args:
quaternion (torch.Tensor): a tensor containing a quaternion to be
converted. The tensor can be of shape :math:`(*, 3)`.
+ order (QuaternionCoeffOrder): quaternion coefficient order. Default: 'xyzw'.
+ Note: 'xyzw' will be deprecated in favor of 'wxyz'.
Return:
torch.Tensor: the quaternion exponential map of shape :math:`(*, 4)`.
Example:
- >>> quaternion = torch.tensor([0., 0., 0.])
- >>> quaternion_log_to_exp(quaternion)
- tensor([0., 0., 0., 1.])
+ >>> quaternion = torch.tensor((0., 0., 0.))
+ >>> quaternion_log_to_exp(quaternion, eps=torch.finfo(quaternion.dtype).eps,
+ ... order=QuaternionCoeffOrder.WXYZ)
+ tensor([1., 0., 0., 0.])
"""
if not isinstance(quaternion, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}".format(
- type(quaternion)))
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(quaternion)}")
if not quaternion.shape[-1] == 3:
- raise ValueError(
- "Input must be a tensor of shape (*, 3). Got {}".format(
- quaternion.shape))
+ raise ValueError(f"Input must be a tensor of shape (*, 3). Got {quaternion.shape}")
+
+ if not torch.jit.is_scripting():
+ if order.name not in QuaternionCoeffOrder.__members__.keys():
+ raise ValueError(f"order must be one of {QuaternionCoeffOrder.__members__.keys()}")
+
+ if order == QuaternionCoeffOrder.XYZW:
+ warnings.warn("`XYZW` quaternion coefficient order is deprecated and"
+ " will be removed after > 0.6. "
+ "Please use `QuaternionCoeffOrder.WXYZ` instead.")
+
# compute quaternion norm
- norm_q: torch.Tensor = torch.norm(
- quaternion, p=2, dim=-1, keepdim=True).clamp(min=eps)
+ norm_q: torch.Tensor = torch.norm(quaternion, p=2, dim=-1, keepdim=True).clamp(min=eps)
# compute scalar and vector
quaternion_vector: torch.Tensor = quaternion * torch.sin(norm_q) / norm_q
quaternion_scalar: torch.Tensor = torch.cos(norm_q)
# compose quaternion and return
- quaternion_exp: torch.Tensor = torch.cat(
- [quaternion_vector, quaternion_scalar], dim=-1)
+ quaternion_exp: torch.Tensor = torch.tensor([])
+ if order == QuaternionCoeffOrder.XYZW:
+ quaternion_exp = torch.cat((quaternion_vector, quaternion_scalar), dim=-1)
+ else:
+ quaternion_exp = torch.cat((quaternion_scalar, quaternion_vector), dim=-1)
+
return quaternion_exp
-def quaternion_exp_to_log(quaternion: torch.Tensor,
- eps: float = 1e-8) -> torch.Tensor:
+def quaternion_exp_to_log(
+ quaternion: torch.Tensor,
+ eps: float = 1.e-8,
+ order: QuaternionCoeffOrder = QuaternionCoeffOrder.XYZW) -> torch.Tensor:
r"""Applies the log map to a quaternion.
+
The quaternion should be in (x, y, z, w) format.
Args:
quaternion (torch.Tensor): a tensor containing a quaternion to be
converted. The tensor can be of shape :math:`(*, 4)`.
+ eps (float): A small number for clamping.
+ order (QuaternionCoeffOrder): quaternion coefficient order. Default: 'xyzw'.
+ Note: 'xyzw' will be deprecated in favor of 'wxyz'.
Return:
torch.Tensor: the quaternion log map of shape :math:`(*, 3)`.
Example:
- >>> quaternion = torch.tensor([0., 0., 0., 1.])
- >>> quaternion_exp_to_log(quaternion)
+ >>> quaternion = torch.tensor((1., 0., 0., 0.))
+ >>> quaternion_exp_to_log(quaternion, eps=torch.finfo(quaternion.dtype).eps,
+ ... order=QuaternionCoeffOrder.WXYZ)
tensor([0., 0., 0.])
"""
if not isinstance(quaternion, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}".format(
- type(quaternion)))
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(quaternion)}")
if not quaternion.shape[-1] == 4:
- raise ValueError(
- "Input must be a tensor of shape (*, 4). Got {}".format(
- quaternion.shape))
+ raise ValueError(f"Input must be a tensor of shape (*, 4). Got {quaternion.shape}")
+
+ if not torch.jit.is_scripting():
+ if order.name not in QuaternionCoeffOrder.__members__.keys():
+ raise ValueError(f"order must be one of {QuaternionCoeffOrder.__members__.keys()}")
+
+ if order == QuaternionCoeffOrder.XYZW:
+ warnings.warn("`XYZW` quaternion coefficient order is deprecated and"
+ " will be removed after > 0.6. "
+ "Please use `QuaternionCoeffOrder.WXYZ` instead.")
+
# unpack quaternion vector and scalar
- quaternion_vector: torch.Tensor = quaternion[..., 0:3]
- quaternion_scalar: torch.Tensor = quaternion[..., 3:4]
+ quaternion_vector: torch.Tensor = torch.tensor([])
+ quaternion_scalar: torch.Tensor = torch.tensor([])
+
+ if order == QuaternionCoeffOrder.XYZW:
+ quaternion_vector = quaternion[..., 0:3]
+ quaternion_scalar = quaternion[..., 3:4]
+ else:
+ quaternion_scalar = quaternion[..., 0:1]
+ quaternion_vector = quaternion[..., 1:4]
# compute quaternion norm
norm_q: torch.Tensor = torch.norm(
@@ -623,6 +728,7 @@ def quaternion_exp_to_log(quaternion: torch.Tensor,
# apply log map
quaternion_log: torch.Tensor = quaternion_vector * torch.acos(
torch.clamp(quaternion_scalar, min=-1.0, max=1.0)) / norm_q
+
return quaternion_log
@@ -630,14 +736,19 @@ def quaternion_exp_to_log(quaternion: torch.Tensor,
# https://github.com/facebookresearch/QuaterNet/blob/master/common/quaternion.py#L138
-def angle_axis_to_quaternion(angle_axis: torch.Tensor) -> torch.Tensor:
+def angle_axis_to_quaternion(
+ angle_axis: torch.Tensor,
+ order: QuaternionCoeffOrder = QuaternionCoeffOrder.XYZW) -> torch.Tensor:
r"""Convert an angle axis to a quaternion.
- The quaternion vector has components in (x, y, z, w) format.
+
+ The quaternion vector has components in (x, y, z, w) or (w, x, y, z) format.
Adapted from ceres C++ library: ceres-solver/include/ceres/rotation.h
Args:
angle_axis (torch.Tensor): tensor with angle axis.
+ order (QuaternionCoeffOrder): quaternion coefficient order. Default: 'xyzw'.
+ Note: 'xyzw' will be deprecated in favor of 'wxyz'.
Return:
torch.Tensor: tensor with quaternion.
@@ -648,16 +759,23 @@ def angle_axis_to_quaternion(angle_axis: torch.Tensor) -> torch.Tensor:
Example:
>>> angle_axis = torch.rand(2, 3) # Nx3
- >>> quaternion = angle_axis_to_quaternion(angle_axis) # Nx4
+ >>> quaternion = angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.WXYZ) # Nx4
"""
if not torch.is_tensor(angle_axis):
- raise TypeError("Input type is not a torch.Tensor. Got {}".format(
- type(angle_axis)))
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(angle_axis)}")
if not angle_axis.shape[-1] == 3:
- raise ValueError(
- "Input must be a tensor of shape Nx3 or 3. Got {}".format(
- angle_axis.shape))
+ raise ValueError(f"Input must be a tensor of shape Nx3 or 3. Got {angle_axis.shape}")
+
+ if not torch.jit.is_scripting():
+ if order.name not in QuaternionCoeffOrder.__members__.keys():
+ raise ValueError(f"order must be one of {QuaternionCoeffOrder.__members__.keys()}")
+
+ if order == QuaternionCoeffOrder.XYZW:
+ warnings.warn("`XYZW` quaternion coefficient order is deprecated and"
+ " will be removed after > 0.6. "
+ "Please use `QuaternionCoeffOrder.WXYZ` instead.")
+
# unpack input and compute conversion
a0: torch.Tensor = angle_axis[..., 0:1]
a1: torch.Tensor = angle_axis[..., 1:2]
@@ -675,11 +793,19 @@ def angle_axis_to_quaternion(angle_axis: torch.Tensor) -> torch.Tensor:
k: torch.Tensor = torch.where(mask, k_pos, k_neg)
w: torch.Tensor = torch.where(mask, torch.cos(half_theta), ones)
- quaternion: torch.Tensor = torch.zeros_like(angle_axis)
- quaternion[..., 0:1] += a0 * k
- quaternion[..., 1:2] += a1 * k
- quaternion[..., 2:3] += a2 * k
- return torch.cat([w, quaternion], dim=-1)
+ quaternion: torch.Tensor = torch.zeros(size=(*angle_axis.shape[:-1], 4), dtype=angle_axis.dtype,
+ device=angle_axis.device)
+ if order == QuaternionCoeffOrder.XYZW:
+ quaternion[..., 0:1] = a0 * k
+ quaternion[..., 1:2] = a1 * k
+ quaternion[..., 2:3] = a2 * k
+ quaternion[..., 3:4] = w
+ else:
+ quaternion[..., 1:2] = a0 * k
+ quaternion[..., 2:3] = a1 * k
+ quaternion[..., 3:4] = a2 * k
+ quaternion[..., 0:1] = w
+ return quaternion
# based on:
diff --git a/test/geometry/test_conversions.py b/test/geometry/test_conversions.py
index d8c18e044..f2b5c05fa 100644
--- a/test/geometry/test_conversions.py
+++ b/test/geometry/test_conversions.py
@@ -1,14 +1,32 @@
-from typing import Optional
+from functools import partial
-import pytest
import numpy as np
+import pytest
+import torch
+from torch.autograd import gradcheck
+from torch.testing import assert_allclose
import kornia
+from kornia.geometry.conversions import QuaternionCoeffOrder
from kornia.testing import tensor_to_gradcheck_var, create_eye_batch
-import torch
-from torch.autograd import gradcheck
-from torch.testing import assert_allclose
+
+def atol(device, dtype):
+ """Lower tolerance for cuda-float16 only"""
+ if 'cuda' in device.type and dtype == torch.float16:
+ return 1.e-3
+ else:
+ return 1.e-4
+
+
+def rtol(device, dtype):
+ """Lower tolerance for cuda-float16 only"""
+ if 'cuda' in device.type and dtype == torch.float16:
+ return 1.e-3
+ else:
+ return 1.e-4
# based on:
@@ -16,300 +34,1019 @@ from torch.testing import assert_allclose
class TestAngleAxisToQuaternion:
+ def test_smoke_xyzw(self, device, dtype):
+ angle_axis = torch.zeros(3, dtype=dtype, device=device)
+ with pytest.warns(UserWarning):
+ quaternion = kornia.angle_axis_to_quaternion(angle_axis,
+ order=QuaternionCoeffOrder.XYZW)
+ assert quaternion.shape == (4,)
+
def test_smoke(self, device, dtype):
- angle_axis = torch.zeros(3)
- quaternion = kornia.angle_axis_to_quaternion(angle_axis)
+ angle_axis = torch.zeros(3, dtype=dtype, device=device)
+ quaternion = kornia.angle_axis_to_quaternion(angle_axis,
+ order=QuaternionCoeffOrder.WXYZ)
assert quaternion.shape == (4,)
+ @pytest.mark.parametrize("batch_size", (1, 3, 8))
+ def test_smoke_batch_xyzw(self, batch_size, device, dtype):
+ angle_axis = torch.zeros(batch_size, 3, device=device, dtype=dtype)
+ with pytest.warns(UserWarning):
+ quaternion = kornia.angle_axis_to_quaternion(angle_axis,
+ order=QuaternionCoeffOrder.XYZW)
+ assert quaternion.shape == (batch_size, 4)
+
@pytest.mark.parametrize("batch_size", (1, 3, 8))
def test_smoke_batch(self, batch_size, device, dtype):
angle_axis = torch.zeros(batch_size, 3, device=device, dtype=dtype)
- quaternion = kornia.angle_axis_to_quaternion(angle_axis)
+ quaternion = kornia.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.WXYZ)
assert quaternion.shape == (batch_size, 4)
- def test_zero_angle(self, device, dtype):
- angle_axis = torch.tensor([0., 0., 0.], device=device, dtype=dtype)
- expected = torch.tensor([1., 0., 0., 0.], device=device, dtype=dtype)
- quaternion = kornia.angle_axis_to_quaternion(angle_axis)
- assert_allclose(quaternion, expected, atol=1e-4, rtol=1e-4)
-
- def test_small_angle(self, device, dtype):
- theta = 1e-2
- angle_axis = torch.tensor([theta, 0., 0.], device=device, dtype=dtype)
- expected = torch.tensor([np.cos(theta / 2), np.sin(theta / 2), 0., 0.], device=device, dtype=dtype)
- quaternion = kornia.angle_axis_to_quaternion(angle_axis)
- assert_allclose(quaternion, expected, atol=1e-4, rtol=1e-4)
-
- def test_x_rotation(self, device, dtype):
- half_sqrt2 = 0.5 * np.sqrt(2)
- angle_axis = torch.tensor([kornia.pi / 2, 0., 0.], device=device, dtype=dtype)
- expected = torch.tensor([half_sqrt2, half_sqrt2, 0., 0.], device=device, dtype=dtype)
- quaternion = kornia.angle_axis_to_quaternion(angle_axis)
- assert_allclose(quaternion, expected, atol=1e-4, rtol=1e-4)
+ def test_zero_angle_xyzw(self, device, dtype, atol, rtol):
+ angle_axis = torch.tensor((0., 0., 0.), device=device, dtype=dtype)
+ expected = torch.tensor((0., 0., 0., 1.), device=device, dtype=dtype)
+ with pytest.warns(UserWarning):
+ quaternion = kornia.angle_axis_to_quaternion(angle_axis,
+ order=QuaternionCoeffOrder.XYZW)
+ assert_allclose(quaternion, expected, atol=atol, rtol=rtol)
+
+ def test_zero_angle(self, device, dtype, atol, rtol):
+ angle_axis = torch.tensor((0., 0., 0.), device=device, dtype=dtype)
+ expected = torch.tensor((1., 0., 0., 0.), device=device, dtype=dtype)
+ quaternion = kornia.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.WXYZ)
+ assert_allclose(quaternion, expected, atol=atol, rtol=rtol)
+
+ def test_small_angle_x_xyzw(self, device, dtype, atol, rtol):
+ theta = 1.e-2
+ angle_axis = torch.tensor((theta, 0., 0.), device=device, dtype=dtype)
+ expected = torch.tensor((np.sin(theta / 2.), 0., 0., np.cos(theta / 2.)),
+ device=device, dtype=dtype)
+ with pytest.warns(UserWarning):
+ quaternion = kornia.angle_axis_to_quaternion(angle_axis,
+ order=QuaternionCoeffOrder.XYZW)
+ assert_allclose(quaternion, expected, atol=atol, rtol=rtol)
+
+ def test_small_angle_x(self, device, dtype, atol, rtol):
+ theta = 1.e-2
+ angle_axis = torch.tensor((theta, 0., 0.), device=device, dtype=dtype)
+ expected = torch.tensor((np.cos(theta / 2.), np.sin(theta / 2.), 0., 0.),
+ device=device, dtype=dtype)
+ quaternion = kornia.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.WXYZ)
+ assert_allclose(quaternion, expected, atol=atol, rtol=rtol)
+
+ def test_small_angle_y_xyzw(self, device, dtype, atol, rtol):
+ theta = 1.e-2
+ angle_axis = torch.tensor((0., theta, 0.), device=device, dtype=dtype)
+ expected = torch.tensor((0., np.sin(theta / 2.), 0., np.cos(theta / 2.)),
+ device=device, dtype=dtype)
+ with pytest.warns(UserWarning):
+ quaternion = kornia.angle_axis_to_quaternion(angle_axis,
+ order=QuaternionCoeffOrder.XYZW)
+ assert_allclose(quaternion, expected, atol=atol, rtol=rtol)
+
+ def test_small_angle_y(self, device, dtype, atol, rtol):
+ theta = 1.e-2
+ angle_axis = torch.tensor((0., theta, 0.), device=device, dtype=dtype)
+ expected = torch.tensor((np.cos(theta / 2.), 0., np.sin(theta / 2.), 0.,),
+ device=device, dtype=dtype)
+ quaternion = kornia.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.WXYZ)
+ assert_allclose(quaternion, expected, atol=atol, rtol=rtol)
+
+ def test_small_angle_z_xyzw(self, device, dtype, atol, rtol):
+ theta = 1.e-2
+ angle_axis = torch.tensor((0., 0., theta), device=device, dtype=dtype)
+ expected = torch.tensor((0., 0., np.sin(theta / 2.), np.cos(theta / 2.)),
+ device=device, dtype=dtype)
+ with pytest.warns(UserWarning):
+ quaternion = kornia.angle_axis_to_quaternion(angle_axis,
+ order=QuaternionCoeffOrder.XYZW)
+ assert_allclose(quaternion, expected, atol=atol, rtol=rtol)
+
+ def test_small_angle_z(self, device, dtype, atol, rtol):
+ theta = 1.e-2
+ angle_axis = torch.tensor((0., 0., theta), device=device, dtype=dtype)
+ expected = torch.tensor((np.cos(theta / 2.), 0., 0., np.sin(theta / 2.)),
+ device=device, dtype=dtype)
+ quaternion = kornia.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.WXYZ)
+ assert_allclose(quaternion, expected, atol=atol, rtol=rtol)
+
+ def test_x_rotation_xyzw(self, device, dtype, atol, rtol):
+ half_sqrt2 = 0.5 * np.sqrt(2.)
+ angle_axis = torch.tensor((kornia.pi / 2., 0., 0.), device=device, dtype=dtype)
+ expected = torch.tensor((half_sqrt2, 0., 0., half_sqrt2), device=device, dtype=dtype)
+ with pytest.warns(UserWarning):
+ quaternion = kornia.angle_axis_to_quaternion(angle_axis,
+ order=QuaternionCoeffOrder.XYZW)
+ assert_allclose(quaternion, expected, atol=atol, rtol=rtol)
+
+ def test_x_rotation(self, device, dtype, atol, rtol):
+ half_sqrt2 = 0.5 * np.sqrt(2.)
+ angle_axis = torch.tensor((kornia.pi / 2., 0., 0.), device=device, dtype=dtype)
+ expected = torch.tensor((half_sqrt2, half_sqrt2, 0., 0.), device=device, dtype=dtype)
+ quaternion = kornia.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.WXYZ)
+ assert_allclose(quaternion, expected, atol=atol, rtol=rtol)
+
+ def test_y_rotation_xyzw(self, device, dtype, atol, rtol):
+ half_sqrt2 = 0.5 * np.sqrt(2.)
+ angle_axis = torch.tensor((0., kornia.pi / 2., 0.), device=device, dtype=dtype)
+ expected = torch.tensor((0., half_sqrt2, 0., half_sqrt2), device=device, dtype=dtype)
+ with pytest.warns(UserWarning):
+ quaternion = kornia.angle_axis_to_quaternion(angle_axis,
+ order=QuaternionCoeffOrder.XYZW)
+ assert_allclose(quaternion, expected, atol=atol, rtol=rtol)
+
+ def test_y_rotation(self, device, dtype, atol, rtol):
+ half_sqrt2 = 0.5 * np.sqrt(2.)
+ angle_axis = torch.tensor((0., kornia.pi / 2., 0.), device=device, dtype=dtype)
+ expected = torch.tensor((half_sqrt2, 0., half_sqrt2, 0.), device=device, dtype=dtype)
+ quaternion = kornia.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.WXYZ)
+ assert_allclose(quaternion, expected, atol=atol, rtol=rtol)
+
+ def test_z_rotation_xyzw(self, device, dtype, atol, rtol):
+ half_sqrt2 = 0.5 * np.sqrt(2.)
+ angle_axis = torch.tensor((0., 0., kornia.pi / 2.), device=device, dtype=dtype)
+ expected = torch.tensor((0., 0., half_sqrt2, half_sqrt2), device=device, dtype=dtype)
+ with pytest.warns(UserWarning):
+ quaternion = kornia.angle_axis_to_quaternion(angle_axis,
+ order=QuaternionCoeffOrder.XYZW)
+ assert_allclose(quaternion, expected, atol=atol, rtol=rtol)
+
+ def test_z_rotation(self, device, dtype, atol, rtol):
+ half_sqrt2 = 0.5 * np.sqrt(2.)
+ angle_axis = torch.tensor((0., 0., kornia.pi / 2.), device=device, dtype=dtype)
+ expected = torch.tensor((half_sqrt2, 0., 0., half_sqrt2), device=device, dtype=dtype)
+ quaternion = kornia.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.WXYZ)
+ assert_allclose(quaternion, expected, atol=atol, rtol=rtol)
+
+ def test_gradcheck_xyzw(self, device, dtype):
+ eps = torch.finfo(dtype).eps
+ angle_axis = torch.tensor((0., 0., 0.), device=device, dtype=dtype) + eps
+ angle_axis = tensor_to_gradcheck_var(angle_axis)
+ # evaluate function gradient
+ with pytest.warns(UserWarning):
+ assert gradcheck(partial(kornia.angle_axis_to_quaternion,
+ order=QuaternionCoeffOrder.XYZW),
+ (angle_axis,),
+ raise_exception=True)
def test_gradcheck(self, device, dtype):
- eps = 1e-12
- angle_axis = torch.tensor([0., 0., 0.], device=device, dtype=dtype) + eps
+ eps = torch.finfo(dtype).eps
+ angle_axis = torch.tensor((0., 0., 0.), device=device, dtype=dtype) + eps
angle_axis = tensor_to_gradcheck_var(angle_axis)
# evaluate function gradient
- assert gradcheck(kornia.angle_axis_to_quaternion, (angle_axis,),
+ assert gradcheck(partial(kornia.angle_axis_to_quaternion, order=QuaternionCoeffOrder.WXYZ),
+ (angle_axis,),
raise_exception=True)
-class TestRotationMatrixToQuaternion:
+class TestQuaternionToAngleAxis:
+
+ def test_smoke_xyzw(self, device, dtype):
+ quaternion = torch.zeros(4, device=device, dtype=dtype)
+ with pytest.warns(UserWarning):
+ angle_axis = kornia.quaternion_to_angle_axis(quaternion,
+ order=QuaternionCoeffOrder.XYZW)
+ assert angle_axis.shape == (3,)
+
+ def test_smoke(self, device, dtype):
+ quaternion = torch.zeros(4, device=device, dtype=dtype)
+ angle_axis = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.WXYZ)
+ assert angle_axis.shape == (3,)
+
+ @pytest.mark.parametrize("batch_size", (1, 3, 8))
+ def test_smoke_batch_xyzw(self, batch_size, device, dtype):
+ quaternion = torch.zeros(batch_size, 4, device=device, dtype=dtype)
+ with pytest.warns(UserWarning):
+ angle_axis = kornia.quaternion_to_angle_axis(quaternion,
+ order=QuaternionCoeffOrder.XYZW)
+ assert angle_axis.shape == (batch_size, 3)
@pytest.mark.parametrize("batch_size", (1, 3, 8))
def test_smoke_batch(self, batch_size, device, dtype):
+ quaternion = torch.zeros(batch_size, 4, device=device, dtype=dtype)
+ angle_axis = kornia.quaternion_to_angle_axis(quaternion,
+ order=QuaternionCoeffOrder.WXYZ)
+ assert angle_axis.shape == (batch_size, 3)
+
+ def test_unit_quaternion_xyzw(self, device, dtype, atol, rtol):
+ quaternion = torch.tensor((0., 0., 0., 1.), device=device, dtype=dtype)
+ expected = torch.tensor((0., 0., 0.), device=device, dtype=dtype)
+ with pytest.warns(UserWarning):
+ angle_axis = kornia.quaternion_to_angle_axis(quaternion,
+ order=QuaternionCoeffOrder.XYZW)
+ assert_allclose(angle_axis, expected, atol=atol, rtol=rtol)
+
+ def test_unit_quaternion(self, device, dtype, atol, rtol):
+ quaternion = torch.tensor((1., 0., 0., 0.), device=device, dtype=dtype)
+ expected = torch.tensor((0., 0., 0.), device=device, dtype=dtype)
+ angle_axis = kornia.quaternion_to_angle_axis(quaternion,
+ order=QuaternionCoeffOrder.WXYZ)
+ assert_allclose(angle_axis, expected, atol=atol, rtol=rtol)
+
+ def test_x_rotation_xyzw(self, device, dtype, atol, rtol):
+ quaternion = torch.tensor((1., 0., 0., 0.), device=device, dtype=dtype)
+ expected = torch.tensor((kornia.pi, 0., 0.), device=device, dtype=dtype)
+ with pytest.warns(UserWarning):
+ angle_axis = kornia.quaternion_to_angle_axis(quaternion,
+ order=QuaternionCoeffOrder.XYZW)
+ assert_allclose(angle_axis, expected, atol=atol, rtol=rtol)
+
+ def test_x_rotation(self, device, dtype, atol, rtol):
+ quaternion = torch.tensor((0., 1., 0., 0.), device=device, dtype=dtype)
+ expected = torch.tensor((kornia.pi, 0., 0.), device=device, dtype=dtype)
+ angle_axis = kornia.quaternion_to_angle_axis(quaternion,
+ order=QuaternionCoeffOrder.WXYZ)
+ assert_allclose(angle_axis, expected, atol=atol, rtol=rtol)
+
+ def test_y_rotation_xyzw(self, device, dtype, atol, rtol):
+ quaternion = torch.tensor((0., 1., 0., 0.), device=device, dtype=dtype)
+ expected = torch.tensor((0., kornia.pi, 0.), device=device, dtype=dtype)
+ with pytest.warns(UserWarning):
+ angle_axis = kornia.quaternion_to_angle_axis(quaternion,
+ order=QuaternionCoeffOrder.XYZW)
+ assert_allclose(angle_axis, expected, atol=atol, rtol=rtol)
+
+ def test_y_rotation(self, device, dtype, atol, rtol):
+ quaternion = torch.tensor((0., 0., 1., 0.), device=device, dtype=dtype)
+ expected = torch.tensor((0., kornia.pi, 0.), device=device, dtype=dtype)
+ angle_axis = kornia.quaternion_to_angle_axis(quaternion,
+ order=QuaternionCoeffOrder.WXYZ)
+ assert_allclose(angle_axis, expected, atol=atol, rtol=rtol)
+
+ def test_z_rotation_xyzw(self, device, dtype, atol, rtol):
+ quaternion = torch.tensor((0., 0., 0.5, np.sqrt(3.) / 2.), device=device, dtype=dtype)
+ expected = torch.tensor((0., 0., kornia.pi / 3.), device=device, dtype=dtype)
+ with pytest.warns(UserWarning):
+ angle_axis = kornia.quaternion_to_angle_axis(quaternion,
+ order=QuaternionCoeffOrder.XYZW)
+ assert_allclose(angle_axis, expected, atol=atol, rtol=rtol)
+
+ def test_z_rotation(self, device, dtype, atol, rtol):
+ quaternion = torch.tensor((np.sqrt(3.) / 2., 0., 0., 0.5), device=device, dtype=dtype)
+ expected = torch.tensor((0., 0., kornia.pi / 3.), device=device, dtype=dtype)
+ angle_axis = kornia.quaternion_to_angle_axis(quaternion,
+ order=QuaternionCoeffOrder.WXYZ)
+ assert_allclose(angle_axis, expected, atol=atol, rtol=rtol)
+
+ def test_small_angle_x_xyzw(self, device, dtype, atol, rtol):
+ theta = 1.e-2
+ quaternion = torch.tensor((np.sin(theta / 2.), 0., 0., np.cos(theta / 2.)), device=device,
+ dtype=dtype)
+ expected = torch.tensor((theta, 0., 0.), device=device, dtype=dtype)
+ with pytest.warns(UserWarning):
+ angle_axis = kornia.quaternion_to_angle_axis(quaternion,
+ order=QuaternionCoeffOrder.XYZW)
+ assert_allclose(angle_axis, expected, atol=atol, rtol=rtol)
+
+ def test_small_angle_x(self, device, dtype, atol, rtol):
+ theta = 1.e-2
+ quaternion = torch.tensor((np.cos(theta / 2.), np.sin(theta / 2.), 0., 0.), device=device,
+ dtype=dtype)
+ expected = torch.tensor((theta, 0., 0.), device=device, dtype=dtype)
+ angle_axis = kornia.quaternion_to_angle_axis(quaternion,
+ order=QuaternionCoeffOrder.WXYZ)
+ assert_allclose(angle_axis, expected, atol=atol, rtol=rtol)
+
+ def test_small_angle_y_xyzw(self, device, dtype, atol, rtol):
+ theta = 1.e-2
+ quaternion = torch.tensor((0., np.sin(theta / 2), 0., np.cos(theta / 2)), device=device,
+ dtype=dtype)
+ expected = torch.tensor((0., theta, 0.), device=device, dtype=dtype)
+ with pytest.warns(UserWarning):
+ angle_axis = kornia.quaternion_to_angle_axis(quaternion,
+ order=QuaternionCoeffOrder.XYZW)
+ assert_allclose(angle_axis, expected, atol=atol, rtol=rtol)
+
+ def test_small_angle_y(self, device, dtype, atol, rtol):
+ theta = 1.e-2
+ quaternion = torch.tensor((np.cos(theta / 2), 0., np.sin(theta / 2), 0.), device=device,
+ dtype=dtype)
+ expected = torch.tensor((0., theta, 0.), device=device, dtype=dtype)
+ angle_axis = kornia.quaternion_to_angle_axis(quaternion,
+ order=QuaternionCoeffOrder.WXYZ)
+ assert_allclose(angle_axis, expected, atol=atol, rtol=rtol)
+
+ def test_small_angle_z_xyzw(self, device, dtype, atol, rtol):
+ theta = 1.e-2
+ quaternion = torch.tensor((0., 0., np.sin(theta / 2), np.cos(theta / 2)), device=device,
+ dtype=dtype)
+ expected = torch.tensor((0., 0., theta), device=device, dtype=dtype)
+ with pytest.warns(UserWarning):
+ angle_axis = kornia.quaternion_to_angle_axis(quaternion,
+ order=QuaternionCoeffOrder.XYZW)
+ assert_allclose(angle_axis, expected, atol=atol, rtol=rtol)
+
+ def test_small_angle_z(self, device, dtype, atol, rtol):
+ theta = 1.e-2
+ quaternion = torch.tensor((np.cos(theta / 2), 0., 0., np.sin(theta / 2)), device=device,
+ dtype=dtype)
+ expected = torch.tensor((0., 0., theta), device=device, dtype=dtype)
+ angle_axis = kornia.quaternion_to_angle_axis(quaternion,
+ order=QuaternionCoeffOrder.WXYZ)
+ assert_allclose(angle_axis, expected, atol=atol, rtol=rtol)
+
+ def test_gradcheck_xyzw(self, device, dtype):
+ eps = torch.finfo(dtype).eps
+ quaternion = torch.tensor((0., 0., 0., 1.), device=device, dtype=dtype) + eps
+ quaternion = tensor_to_gradcheck_var(quaternion)
+ # evaluate function gradient
+ with pytest.warns(UserWarning):
+ assert gradcheck(partial(kornia.quaternion_to_angle_axis,
+ order=QuaternionCoeffOrder.XYZW),
+ (quaternion,),
+ raise_exception=True)
+
+ def test_gradcheck(self, device, dtype):
+ eps = torch.finfo(dtype).eps
+ quaternion = torch.tensor((1., 0., 0., 0.), device=device, dtype=dtype) + eps
+ quaternion = tensor_to_gradcheck_var(quaternion)
+ # evaluate function gradient
+ assert gradcheck(partial(kornia.quaternion_to_angle_axis, order=QuaternionCoeffOrder.WXYZ),
+ (quaternion,),
+ raise_exception=True)
+
+
+class TestRotationMatrixToQuaternion:
+
+ @pytest.mark.parametrize("batch_size", (1, 3, 8))
+ def test_smoke_batch_xyzw(self, batch_size, device, dtype):
matrix = torch.zeros(batch_size, 3, 3, device=device, dtype=dtype)
- quaternion = kornia.rotation_matrix_to_quaternion(matrix)
+ with pytest.warns(UserWarning):
+ quaternion = kornia.rotation_matrix_to_quaternion(matrix,
+ order=QuaternionCoeffOrder.XYZW)
assert quaternion.shape == (batch_size, 4)
- def test_identity(self, device, dtype):
- matrix = torch.tensor([
- [1., 0., 0.],
- [0., 1., 0.],
- [0., 0., 1.],
- ], device=device, dtype=dtype)
- expected = torch.tensor(
- [0., 0., 0., 1.], device=device, dtype=dtype)
- quaternion = kornia.rotation_matrix_to_quaternion(matrix)
- assert_allclose(quaternion, expected, atol=1e-4, rtol=1e-4)
+ @pytest.mark.parametrize("batch_size", (1, 3, 8))
+ def test_smoke_batch(self, batch_size, device, dtype):
+ matrix = torch.zeros(batch_size, 3, 3, device=device, dtype=dtype)
+ quaternion = kornia.rotation_matrix_to_quaternion(matrix, order=QuaternionCoeffOrder.WXYZ)
+ assert quaternion.shape == (batch_size, 4)
- def test_rot_x_45(self, device, dtype):
- matrix = torch.tensor([
- [1., 0., 0.],
- [0., 0., -1.],
- [0., 1., 0.],
- ], device=device, dtype=dtype)
- pi_half2 = torch.cos(kornia.pi / 4).to(device=device, dtype=dtype)
- expected = torch.tensor(
- [pi_half2, 0., 0., pi_half2], device=device, dtype=dtype)
- quaternion = kornia.rotation_matrix_to_quaternion(matrix)
- assert_allclose(quaternion, expected, atol=1e-4, rtol=1e-4)
-
- def test_back_and_forth(self, device, dtype):
- matrix = torch.tensor([
- [1., 0., 0.],
- [0., 0., -1.],
- [0., 1., 0.],
- ], device=device, dtype=dtype)
- quaternion = kornia.rotation_matrix_to_quaternion(matrix)
- matrix_hat = kornia.quaternion_to_rotation_matrix(quaternion)
- assert_allclose(matrix, matrix_hat)
-
- def test_corner_case(self, device, dtype):
- matrix = torch.tensor([
- [-0.7799533010, -0.5432914495, 0.3106555045],
- [0.0492402576, -0.5481169224, -0.8349509239],
- [0.6238971353, -0.6359263659, 0.4542570710]
- ], device=device, dtype=dtype)
- quaternion_true = torch.tensor([0.280136495828629, -0.440902262926102,
- 0.834015488624573, 0.177614107728004], device=device, dtype=dtype)
- quaternion = kornia.rotation_matrix_to_quaternion(matrix)
+ def test_identity_xyzw(self, device, dtype, atol, rtol):
+ matrix = torch.tensor((
+ (1., 0., 0.),
+ (0., 1., 0.),
+ (0., 0., 1.),
+ ), device=device, dtype=dtype)
+ expected = torch.tensor((0., 0., 0., 1.), device=device, dtype=dtype)
+ with pytest.warns(UserWarning):
+ quaternion = kornia.rotation_matrix_to_quaternion(matrix,
+ order=QuaternionCoeffOrder.XYZW)
+ assert_allclose(quaternion, expected, atol=atol, rtol=rtol)
+
+ def test_identity(self, device, dtype, atol, rtol):
+ matrix = torch.tensor((
+ (1., 0., 0.),
+ (0., 1., 0.),
+ (0., 0., 1.),
+ ), device=device, dtype=dtype)
+ expected = torch.tensor((1., 0., 0., 0.), device=device, dtype=dtype)
+ quaternion = kornia.rotation_matrix_to_quaternion(matrix, order=QuaternionCoeffOrder.WXYZ)
+ assert_allclose(quaternion, expected, atol=atol, rtol=rtol)
+
+ def test_rot_x_45_xyzw(self, device, dtype, atol, rtol):
+ matrix = torch.tensor((
+ (1., 0., 0.),
+ (0., 0., -1.),
+ (0., 1., 0.),
+ ), device=device, dtype=dtype)
+ pi_half2 = torch.cos(kornia.pi / 4.).to(device=device, dtype=dtype)
+ expected = torch.tensor((pi_half2, 0., 0., pi_half2), device=device, dtype=dtype)
+ with pytest.warns(UserWarning):
+ quaternion = kornia.rotation_matrix_to_quaternion(matrix,
+ order=QuaternionCoeffOrder.XYZW)
+ assert_allclose(quaternion, expected, atol=atol, rtol=rtol)
+
+ def test_rot_x_45(self, device, dtype, atol, rtol):
+ matrix = torch.tensor((
+ (1., 0., 0.),
+ (0., 0., -1.),
+ (0., 1., 0.),
+ ), device=device, dtype=dtype)
+ pi_half2 = torch.cos(kornia.pi / 4.).to(device=device, dtype=dtype)
+ expected = torch.tensor((pi_half2, pi_half2, 0., 0.), device=device, dtype=dtype)
+ quaternion = kornia.rotation_matrix_to_quaternion(matrix, order=QuaternionCoeffOrder.WXYZ)
+ assert_allclose(quaternion, expected, atol=atol, rtol=rtol)
+
+ def test_back_and_forth_xyzw(self, device, dtype, atol, rtol):
+ eps = torch.finfo(dtype).eps
+ matrix = torch.tensor((
+ (1., 0., 0.),
+ (0., 0., -1.),
+ (0., 1., 0.),
+ ), device=device, dtype=dtype)
+ with pytest.warns(UserWarning):
+ quaternion = kornia.rotation_matrix_to_quaternion(matrix, eps=eps,
+ order=QuaternionCoeffOrder.XYZW)
+ matrix_hat = kornia.quaternion_to_rotation_matrix(quaternion,
+ order=QuaternionCoeffOrder.XYZW)
+ assert_allclose(matrix, matrix_hat, atol=atol, rtol=rtol)
+
+ def test_back_and_forth(self, device, dtype, atol, rtol):
+ eps = torch.finfo(dtype).eps
+ matrix = torch.tensor((
+ (1., 0., 0.),
+ (0., 0., -1.),
+ (0., 1., 0.),
+ ), device=device, dtype=dtype)
+ quaternion = kornia.rotation_matrix_to_quaternion(matrix, eps=eps,
+ order=QuaternionCoeffOrder.WXYZ)
+ matrix_hat = kornia.quaternion_to_rotation_matrix(quaternion,
+ order=QuaternionCoeffOrder.WXYZ)
+ assert_allclose(matrix, matrix_hat, atol=atol, rtol=rtol)
+
+ def test_corner_case_xyzw(self, device, dtype, atol, rtol):
+ eps = torch.finfo(dtype).eps
+ matrix = torch.tensor((
+ (-0.7799533010, -0.5432914495, 0.3106555045),
+ (0.0492402576, -0.5481169224, -0.8349509239),
+ (0.6238971353, -0.6359263659, 0.4542570710)
+ ), device=device, dtype=dtype)
+ quaternion_true = torch.tensor(
+ (0.280136495828629, -0.440902262926102, 0.834015488624573, 0.177614107728004),
+ device=device, dtype=dtype)
+ with pytest.warns(UserWarning):
+ quaternion = kornia.rotation_matrix_to_quaternion(matrix,
+ eps=eps,
+ order=QuaternionCoeffOrder.XYZW)
+ torch.set_printoptions(precision=10)
+ assert_allclose(quaternion_true, quaternion, atol=atol, rtol=rtol)
+
+ def test_corner_case(self, device, dtype, atol, rtol):
+ eps = torch.finfo(dtype).eps
+ matrix = torch.tensor((
+ (-0.7799533010, -0.5432914495, 0.3106555045),
+ (0.0492402576, -0.5481169224, -0.8349509239),
+ (0.6238971353, -0.6359263659, 0.4542570710)
+ ), device=device, dtype=dtype)
+ quaternion_true = torch.tensor(
+ (0.177614107728004, 0.280136495828629, -0.440902262926102, 0.834015488624573),
+ device=device, dtype=dtype)
+ quaternion = kornia.rotation_matrix_to_quaternion(matrix,
+ eps=eps, order=QuaternionCoeffOrder.WXYZ)
torch.set_printoptions(precision=10)
- assert_allclose(quaternion_true, quaternion)
+ assert_allclose(quaternion_true, quaternion, atol=atol, rtol=rtol)
+
+ def test_gradcheck_xyzw(self, device, dtype):
+ eps = torch.finfo(dtype).eps
+ matrix = torch.eye(3, device=device, dtype=dtype)
+ matrix = tensor_to_gradcheck_var(matrix)
+ # evaluate function gradient
+ with pytest.warns(UserWarning):
+ assert gradcheck(partial(kornia.rotation_matrix_to_quaternion,
+ eps=eps, order=QuaternionCoeffOrder.XYZW),
+ (matrix,),
+ raise_exception=True)
def test_gradcheck(self, device, dtype):
+ eps = torch.finfo(dtype).eps
matrix = torch.eye(3, device=device, dtype=dtype)
matrix = tensor_to_gradcheck_var(matrix)
# evaluate function gradient
- assert gradcheck(kornia.rotation_matrix_to_quaternion, (matrix,),
+ assert gradcheck(partial(kornia.rotation_matrix_to_quaternion,
+ eps=eps, order=QuaternionCoeffOrder.WXYZ),
+ (matrix,),
raise_exception=True)
+ @pytest.mark.skipif(torch.__version__.startswith('1.6'), reason='JIT Enum not handled.')
+ def test_jit_xyzw(self, device, dtype):
+ op = kornia.quaternion_log_to_exp
+ op_script = torch.jit.script(op)
+ quaternion = torch.tensor((0., 0., 1.), device=device, dtype=dtype)
+ with pytest.warns(UserWarning):
+ actual = op_script(quaternion)
+ with pytest.warns(UserWarning):
+ expected = op(quaternion)
+ assert_allclose(actual, expected)
+
+ @pytest.mark.skipif(torch.__version__.startswith('1.6'), reason='JIT Enum not handled.')
def test_jit(self, device, dtype):
+ eps = torch.finfo(dtype).eps
op = kornia.quaternion_log_to_exp
op_script = torch.jit.script(op)
- quaternion = torch.tensor([0., 0., 1.], device=device, dtype=dtype)
- actual = op_script(quaternion)
- expected = op(quaternion)
+ quaternion = torch.tensor((0., 0., 1.), device=device, dtype=dtype)
+ actual = op_script(quaternion, eps=eps, order=QuaternionCoeffOrder.WXYZ)
+ expected = op(quaternion, eps=eps, order=QuaternionCoeffOrder.WXYZ)
assert_allclose(actual, expected)
class TestQuaternionToRotationMatrix:
@pytest.mark.parametrize("batch_size", (1, 3, 8))
- def test_smoke_batch(self, batch_size, device, dtype):
+ def test_smoke_batch_xyzw(self, batch_size, device, dtype):
quaternion = torch.zeros(batch_size, 4, device=device, dtype=dtype)
- matrix = kornia.quaternion_to_rotation_matrix(quaternion)
+ with pytest.warns(UserWarning):
+ matrix = kornia.quaternion_to_rotation_matrix(quaternion,
+ order=QuaternionCoeffOrder.XYZW)
assert matrix.shape == (batch_size, 3, 3)
- def test_unit_quaternion(self, device, dtype):
- quaternion = torch.tensor([0., 0., 0., 1.], device=device, dtype=dtype)
- expected = torch.tensor([
- [1., 0., 0.],
- [0., 1., 0.],
- [0., 0., 1.],
- ], device=device, dtype=dtype)
- matrix = kornia.quaternion_to_rotation_matrix(quaternion)
- assert_allclose(matrix, expected, atol=1e-4, rtol=1e-4)
-
- def test_x_rotation(self, device, dtype):
- quaternion = torch.tensor([1., 0., 0., 0.], device=device, dtype=dtype)
- expected = torch.tensor([
- [1., 0., 0.],
- [0., -1., 0.],
- [0., 0., -1.],
- ], device=device, dtype=dtype)
- matrix = kornia.quaternion_to_rotation_matrix(quaternion)
- assert_allclose(matrix, expected, atol=1e-4, rtol=1e-4)
-
- def test_y_rotation(self, device, dtype):
- quaternion = torch.tensor([0., 1., 0., 0.], device=device, dtype=dtype)
- expected = torch.tensor([
- [-1., 0., 0.],
- [0., 1., 0.],
- [0., 0., -1.],
- ], device=device, dtype=dtype)
- matrix = kornia.quaternion_to_rotation_matrix(quaternion)
- assert_allclose(matrix, expected, atol=1e-4, rtol=1e-4)
+ @pytest.mark.parametrize("batch_size", (1, 3, 8))
+ def test_smoke_batch(self, batch_size, device, dtype):
+ quaternion = torch.zeros(batch_size, 4, device=device, dtype=dtype)
+ matrix = kornia.quaternion_to_rotation_matrix(quaternion, order=QuaternionCoeffOrder.WXYZ)
+ assert matrix.shape == (batch_size, 3, 3)
- def test_z_rotation(self, device, dtype):
- quaternion = torch.tensor([0., 0., 1., 0.], device=device, dtype=dtype)
- expected = torch.tensor([
- [-1., 0., 0.],
- [0., -1., 0.],
- [0., 0., 1.],
- ], device=device, dtype=dtype)
- matrix = kornia.quaternion_to_rotation_matrix(quaternion)
- assert_allclose(matrix, expected, atol=1e-4, rtol=1e-4)
+ def test_unit_quaternion_xyzw(self, device, dtype, atol, rtol):
+ quaternion = torch.tensor((0., 0., 0., 1.), device=device, dtype=dtype)
+ expected = torch.tensor((
+ (1., 0., 0.),
+ (0., 1., 0.),
+ (0., 0., 1.),
+ ), device=device, dtype=dtype)
+ with pytest.warns(UserWarning):
+ matrix = kornia.quaternion_to_rotation_matrix(quaternion,
+ order=QuaternionCoeffOrder.XYZW)
+ assert_allclose(matrix, expected, atol=atol, rtol=rtol)
+
+ def test_unit_quaternion(self, device, dtype, atol, rtol):
+ quaternion = torch.tensor((1., 0., 0., 0.), device=device, dtype=dtype)
+ expected = torch.tensor((
+ (1., 0., 0.),
+ (0., 1., 0.),
+ (0., 0., 1.),
+ ), device=device, dtype=dtype)
+ matrix = kornia.quaternion_to_rotation_matrix(quaternion, order=QuaternionCoeffOrder.WXYZ)
+ assert_allclose(matrix, expected, atol=atol, rtol=rtol)
+
+ def test_x_rotation_xyzw(self, device, dtype, atol, rtol):
+ quaternion = torch.tensor((1., 0., 0., 0.), device=device, dtype=dtype)
+ expected = torch.tensor((
+ (1., 0., 0.),
+ (0., -1., 0.),
+ (0., 0., -1.),
+ ), device=device, dtype=dtype)
+ with pytest.warns(UserWarning):
+ matrix = kornia.quaternion_to_rotation_matrix(quaternion,
+ order=QuaternionCoeffOrder.XYZW)
+ assert_allclose(matrix, expected, atol=atol, rtol=rtol)
+
+ def test_x_rotation(self, device, dtype, atol, rtol):
+ quaternion = torch.tensor((0., 1., 0., 0.), device=device, dtype=dtype)
+ expected = torch.tensor((
+ (1., 0., 0.),
+ (0., -1., 0.),
+ (0., 0., -1.),
+ ), device=device, dtype=dtype)
+ matrix = kornia.quaternion_to_rotation_matrix(quaternion, order=QuaternionCoeffOrder.WXYZ)
+ assert_allclose(matrix, expected, atol=atol, rtol=rtol)
+
+ def test_y_rotation_xyzw(self, device, dtype, atol, rtol):
+ quaternion = torch.tensor((0., 1., 0., 0.), device=device, dtype=dtype)
+ expected = torch.tensor((
+ (-1., 0., 0.),
+ (0., 1., 0.),
+ (0., 0., -1.),
+ ), device=device, dtype=dtype)
+
+ with pytest.warns(UserWarning):
+ matrix = kornia.quaternion_to_rotation_matrix(quaternion,
+ order=QuaternionCoeffOrder.XYZW)
+ assert_allclose(matrix, expected, atol=atol, rtol=rtol)
+
+ def test_y_rotation(self, device, dtype, atol, rtol):
+ quaternion = torch.tensor((0., 0., 1., 0.), device=device, dtype=dtype)
+ expected = torch.tensor((
+ (-1., 0., 0.),
+ (0., 1., 0.),
+ (0., 0., -1.),
+ ), device=device, dtype=dtype)
+ matrix = kornia.quaternion_to_rotation_matrix(quaternion, order=QuaternionCoeffOrder.WXYZ)
+ assert_allclose(matrix, expected, atol=atol, rtol=rtol)
+
+ def test_z_rotation_xyzw(self, device, dtype, atol, rtol):
+ quaternion = torch.tensor((0., 0., 1., 0.), device=device, dtype=dtype)
+ expected = torch.tensor((
+ (-1., 0., 0.),
+ (0., -1., 0.),
+ (0., 0., 1.),
+ ), device=device, dtype=dtype)
+ with pytest.warns(UserWarning):
+ matrix = kornia.quaternion_to_rotation_matrix(quaternion,
+ order=QuaternionCoeffOrder.XYZW)
+ assert_allclose(matrix, expected, atol=atol, rtol=rtol)
+
+ def test_z_rotation(self, device, dtype, atol, rtol):
+ quaternion = torch.tensor((0., 0., 0., 1.), device=device, dtype=dtype)
+ expected = torch.tensor((
+ (-1., 0., 0.),
+ (0., -1., 0.),
+ (0., 0., 1.),
+ ), device=device, dtype=dtype)
+ matrix = kornia.quaternion_to_rotation_matrix(quaternion, order=QuaternionCoeffOrder.WXYZ)
+ assert_allclose(matrix, expected, atol=atol, rtol=rtol)
+
+ def test_gradcheck_xyzw(self, device, dtype):
+ quaternion = torch.tensor((0., 0., 0., 1.), device=device, dtype=dtype)
+ quaternion = tensor_to_gradcheck_var(quaternion)
+ # evaluate function gradient
+ with pytest.warns(UserWarning):
+ assert gradcheck(partial(kornia.quaternion_to_rotation_matrix,
+ order=QuaternionCoeffOrder.XYZW),
+ (quaternion,),
+ raise_exception=True)
def test_gradcheck(self, device, dtype):
- quaternion = torch.tensor([0., 0., 0., 1.], device=device, dtype=dtype)
+ quaternion = torch.tensor((0., 0., 0., 1.), device=device, dtype=dtype)
quaternion = tensor_to_gradcheck_var(quaternion)
# evaluate function gradient
- assert gradcheck(kornia.quaternion_to_rotation_matrix, (quaternion,),
+ assert gradcheck(partial(kornia.quaternion_to_rotation_matrix,
+ order=QuaternionCoeffOrder.WXYZ),
+ (quaternion,),
raise_exception=True)
+ @pytest.mark.skipif(torch.__version__.startswith('1.6'), reason='JIT Enum not handled.')
+ def test_jit_xyzw(self, device, dtype):
+ op = kornia.geometry.conversions.quaternion_to_rotation_matrix
+ op_jit = torch.jit.script(op)
+ quaternion = torch.tensor((0., 0., 1., 0.), device=device, dtype=dtype)
+ with pytest.warns(UserWarning):
+ assert_allclose(op(quaternion), op_jit(quaternion))
+
+ @pytest.mark.skipif(torch.__version__.startswith('1.6'), reason='JIT Enum not handled.')
def test_jit(self, device, dtype):
op = kornia.geometry.conversions.quaternion_to_rotation_matrix
op_jit = torch.jit.script(op)
- quaternion = torch.tensor([0., 0., 1., 0.], device=device, dtype=dtype)
- assert_allclose(op(quaternion), op_jit(quaternion))
+ quaternion = torch.tensor((0., 0., 0., 1.), device=device, dtype=dtype)
+ assert_allclose(op(quaternion, order=QuaternionCoeffOrder.WXYZ),
+ op_jit(quaternion, order=QuaternionCoeffOrder.WXYZ))
class TestQuaternionLogToExp:
@pytest.mark.parametrize("batch_size", (1, 3, 8))
- def test_smoke_batch(self, batch_size, device, dtype):
+ def test_smoke_batch_xyzw(self, batch_size, device, dtype):
quaternion_log = torch.zeros(batch_size, 3, device=device, dtype=dtype)
- quaternion_exp = kornia.quaternion_log_to_exp(quaternion_log)
+ with pytest.warns(UserWarning):
+ quaternion_exp = kornia.quaternion_log_to_exp(quaternion_log,
+ order=QuaternionCoeffOrder.XYZW)
assert quaternion_exp.shape == (batch_size, 4)
- def test_unit_quaternion(self, device, dtype):
- quaternion_log = torch.tensor([0., 0., 0.], device=device, dtype=dtype)
- expected = torch.tensor([0., 0., 0., 1.], device=device, dtype=dtype)
- assert_allclose(kornia.quaternion_log_to_exp(quaternion_log), expected)
+ @pytest.mark.parametrize("batch_size", (1, 3, 8))
+ def test_smoke_batch(self, batch_size, device, dtype):
+ quaternion_log = torch.zeros(batch_size, 3, device=device, dtype=dtype)
+ quaternion_exp = kornia.quaternion_log_to_exp(quaternion_log,
+ order=QuaternionCoeffOrder.WXYZ)
+ assert quaternion_exp.shape == (batch_size, 4)
- def test_pi_quaternion(self, device, dtype):
+ def test_unit_quaternion_xyzw(self, device, dtype, atol, rtol):
+ eps = torch.finfo(dtype).eps
+ quaternion_log = torch.tensor((0., 0., 0.), device=device, dtype=dtype)
+ expected = torch.tensor((0., 0., 0., 1.), device=device, dtype=dtype)
+ with pytest.warns(UserWarning):
+ quaternion_exp = kornia.quaternion_log_to_exp(quaternion_log, eps=eps,
+ order=QuaternionCoeffOrder.XYZW)
+ assert_allclose(quaternion_exp, expected, atol=atol, rtol=rtol)
+
+ def test_unit_quaternion(self, device, dtype, atol, rtol):
+ eps = torch.finfo(dtype).eps
+ quaternion_log = torch.tensor((0., 0., 0.), device=device, dtype=dtype)
+ expected = torch.tensor((1., 0., 0., 0.), device=device, dtype=dtype)
+ quaternion_exp = kornia.quaternion_log_to_exp(quaternion_log, eps=eps,
+ order=QuaternionCoeffOrder.WXYZ)
+ assert_allclose(quaternion_exp, expected, atol=atol, rtol=rtol)
+
+ def test_pi_quaternion_x_xyzw(self, device, dtype, atol, rtol):
+ eps = torch.finfo(dtype).eps
+ one = torch.tensor(1., device=device, dtype=dtype)
+ quaternion_log = torch.tensor((1., 0., 0.), device=device, dtype=dtype)
+ expected = torch.tensor((torch.sin(one), 0., 0., torch.cos(one)), device=device,
+ dtype=dtype)
+ with pytest.warns(UserWarning):
+ quaternion_exp = kornia.quaternion_log_to_exp(quaternion_log, eps=eps,
+ order=QuaternionCoeffOrder.XYZW)
+ assert_allclose(quaternion_exp, expected, atol=atol, rtol=rtol)
+
+ def test_pi_quaternion_x(self, device, dtype, atol, rtol):
+ eps = torch.finfo(dtype).eps
one = torch.tensor(1., device=device, dtype=dtype)
- quaternion_log = torch.tensor([1., 0., 0.], device=device, dtype=dtype)
- expected = torch.tensor([torch.sin(one), 0., 0., torch.cos(one)], device=device, dtype=dtype)
- assert_allclose(kornia.quaternion_log_to_exp(quaternion_log), expected)
+ quaternion_log = torch.tensor((1., 0., 0.), device=device, dtype=dtype)
+ expected = torch.tensor((torch.cos(one), torch.sin(one), 0., 0.), device=device,
+ dtype=dtype)
+ quaternion_exp = kornia.quaternion_log_to_exp(quaternion_log, eps=eps,
+ order=QuaternionCoeffOrder.WXYZ)
+ assert_allclose(quaternion_exp, expected, atol=atol, rtol=rtol)
+
+ def test_pi_quaternion_y_xyzw(self, device, dtype, atol, rtol):
+ eps = torch.finfo(dtype).eps
+ one = torch.tensor(1., device=device, dtype=dtype)
+ quaternion_log = torch.tensor((0., 1., 0.), device=device, dtype=dtype)
+ expected = torch.tensor((0., torch.sin(one), 0., torch.cos(one)), device=device,
+ dtype=dtype)
+ with pytest.warns(UserWarning):
+ quaternion_exp = kornia.quaternion_log_to_exp(quaternion_log, eps=eps,
+ order=QuaternionCoeffOrder.XYZW)
+ assert_allclose(quaternion_exp, expected, atol=atol, rtol=rtol)
+
+ def test_pi_quaternion_y(self, device, dtype, atol, rtol):
+ eps = torch.finfo(dtype).eps
+ one = torch.tensor(1., device=device, dtype=dtype)
+ quaternion_log = torch.tensor((0., 1., 0.), device=device, dtype=dtype)
+ expected = torch.tensor((torch.cos(one), 0., torch.sin(one), 0.), device=device,
+ dtype=dtype)
+ quaternion_exp = kornia.quaternion_log_to_exp(quaternion_log, eps=eps,
+ order=QuaternionCoeffOrder.WXYZ)
+ assert_allclose(quaternion_exp, expected, atol=atol, rtol=rtol)
+
+ def test_pi_quaternion_z_xyzw(self, device, dtype, atol, rtol):
+ eps = torch.finfo(dtype).eps
+ one = torch.tensor(1., device=device, dtype=dtype)
+ quaternion_log = torch.tensor((0., 0., 1.), device=device, dtype=dtype)
+ expected = torch.tensor((0., 0., torch.sin(one), torch.cos(one)), device=device,
+ dtype=dtype)
- def test_back_and_forth(self, device, dtype):
- quaternion_log = torch.tensor([0., 0., 0.], device=device, dtype=dtype)
- quaternion_exp = kornia.quaternion_log_to_exp(quaternion_log)
- quaternion_log_hat = kornia.quaternion_exp_to_log(quaternion_exp)
- assert_allclose(quaternion_log, quaternion_log_hat)
+ with pytest.warns(UserWarning):
+ quaternion_exp = kornia.quaternion_log_to_exp(quaternion_log, eps=eps,
+ order=QuaternionCoeffOrder.XYZW)
+ assert_allclose(quaternion_exp, expected, atol=atol, rtol=rtol)
+
+ def test_pi_quaternion_z(self, device, dtype, atol, rtol):
+ eps = torch.finfo(dtype).eps
+ one = torch.tensor(1., device=device, dtype=dtype)
+ quaternion_log = torch.tensor((0., 0., 1.), device=device, dtype=dtype)
+ expected = torch.tensor((torch.cos(one), 0., 0., torch.sin(one)), device=device,
+ dtype=dtype)
+ quaternion_exp = kornia.quaternion_log_to_exp(quaternion_log, eps=eps,
+ order=QuaternionCoeffOrder.WXYZ)
+ assert_allclose(quaternion_exp, expected, atol=atol, rtol=rtol)
+
+ def test_back_and_forth_xyzw(self, device, dtype, atol, rtol):
+ eps = torch.finfo(dtype).eps
+ quaternion_log = torch.tensor((1., 0., 0.), device=device, dtype=dtype)
+
+ with pytest.warns(UserWarning):
+ quaternion_exp = kornia.quaternion_log_to_exp(quaternion_log, eps=eps,
+ order=QuaternionCoeffOrder.XYZW)
+ with pytest.warns(UserWarning):
+ quaternion_log_hat = kornia.quaternion_exp_to_log(quaternion_exp, eps=eps,
+ order=QuaternionCoeffOrder.XYZW)
+ assert_allclose(quaternion_log, quaternion_log_hat, atol=atol, rtol=rtol)
+
+ def test_back_and_forth(self, device, dtype, atol, rtol):
+ eps = torch.finfo(dtype).eps
+ quaternion_log = torch.tensor((1., 0., 0.), device=device, dtype=dtype)
+
+ quaternion_exp = kornia.quaternion_log_to_exp(quaternion_log, eps=eps,
+ order=QuaternionCoeffOrder.WXYZ)
+ quaternion_log_hat = kornia.quaternion_exp_to_log(quaternion_exp, eps=eps,
+ order=QuaternionCoeffOrder.WXYZ)
+ assert_allclose(quaternion_log, quaternion_log_hat, atol=atol, rtol=rtol)
+
+ def test_gradcheck_xyzw(self, device, dtype):
+ eps = torch.finfo(dtype).eps
+ quaternion = torch.tensor((0., 0., 1.), device=device, dtype=dtype)
+ quaternion = tensor_to_gradcheck_var(quaternion)
+ # evaluate function gradient
+ with pytest.warns(UserWarning):
+ assert gradcheck(partial(kornia.quaternion_log_to_exp, eps=eps,
+ order=QuaternionCoeffOrder.XYZW),
+ (quaternion,),
+ raise_exception=True)
def test_gradcheck(self, device, dtype):
- quaternion = torch.tensor([0., 0., 1.], device=device, dtype=dtype)
+ eps = torch.finfo(dtype).eps
+ quaternion = torch.tensor((0., 0., 1.), device=device, dtype=dtype)
quaternion = tensor_to_gradcheck_var(quaternion)
# evaluate function gradient
- assert gradcheck(kornia.quaternion_log_to_exp, (quaternion,),
+ assert gradcheck(partial(kornia.quaternion_log_to_exp, eps=eps,
+ order=QuaternionCoeffOrder.WXYZ),
+ (quaternion,),
raise_exception=True)
+ @pytest.mark.skipif(torch.__version__.startswith('1.6'), reason='JIT Enum not handled.')
+ def test_jit_xyzw(self, device, dtype):
+ op = kornia.geometry.conversions.quaternion_log_to_exp
+ op_jit = torch.jit.script(op)
+ quaternion = torch.tensor((0., 0., 1.), device=device, dtype=dtype)
+ with pytest.warns(UserWarning):
+ assert_allclose(op(quaternion, order=QuaternionCoeffOrder.XYZW),
+ op_jit(quaternion, order=QuaternionCoeffOrder.XYZW))
+
+ @pytest.mark.skipif(torch.__version__.startswith('1.6'), reason='JIT Enum not handled.')
def test_jit(self, device, dtype):
op = kornia.geometry.conversions.quaternion_log_to_exp
op_jit = torch.jit.script(op)
- quaternion = torch.tensor([0., 0., 1.], device=device, dtype=dtype)
- assert_allclose(op(quaternion), op_jit(quaternion))
+ quaternion = torch.tensor((0., 0., 1.), device=device, dtype=dtype)
+ assert_allclose(op(quaternion, order=QuaternionCoeffOrder.WXYZ),
+ op_jit(quaternion, order=QuaternionCoeffOrder.WXYZ))
class TestQuaternionExpToLog:
@pytest.mark.parametrize("batch_size", (1, 3, 8))
- def test_smoke_batch(self, batch_size, device, dtype):
+ def test_smoke_batch_xyzw(self, batch_size, device, dtype):
+ eps = torch.finfo(dtype).eps
quaternion_exp = torch.zeros(batch_size, 4, device=device, dtype=dtype)
- quaternion_log = kornia.quaternion_exp_to_log(quaternion_exp)
+ with pytest.warns(UserWarning):
+ quaternion_log = kornia.quaternion_exp_to_log(quaternion_exp, eps=eps,
+ order=QuaternionCoeffOrder.XYZW)
assert quaternion_log.shape == (batch_size, 3)
- def test_unit_quaternion(self, device, dtype):
- quaternion_exp = torch.tensor([0., 0., 0., 1.], device=device, dtype=dtype)
- expected = torch.tensor([0., 0., 0.], device=device, dtype=dtype)
- assert_allclose(kornia.quaternion_exp_to_log(quaternion_exp), expected, atol=1e-4, rtol=1e-4)
-
- def test_pi_quaternion(self, device, dtype):
- quaternion_exp = torch.tensor([1., 0., 0., 0.], device=device, dtype=dtype)
- expected = torch.tensor([kornia.pi / 2, 0., 0.], device=device, dtype=dtype)
- assert_allclose(kornia.quaternion_exp_to_log(quaternion_exp), expected, atol=1e-4, rtol=1e-4)
+ @pytest.mark.parametrize("batch_size", (1, 3, 8))
+ def test_smoke_batch(self, batch_size, device, dtype):
+ eps = torch.finfo(dtype).eps
+ quaternion_exp = torch.zeros(batch_size, 4, device=device, dtype=dtype)
+ quaternion_log = kornia.quaternion_exp_to_log(quaternion_exp, eps=eps,
+ order=QuaternionCoeffOrder.WXYZ)
+ assert quaternion_log.shape == (batch_size, 3)
- def test_back_and_forth(self, device, dtype):
- quaternion_exp = torch.tensor([1., 0., 0., 0.], device=device, dtype=dtype)
- quaternion_log = kornia.quaternion_exp_to_log(quaternion_exp)
- quaternion_exp_hat = kornia.quaternion_log_to_exp(quaternion_log)
- assert_allclose(quaternion_exp, quaternion_exp_hat, atol=1e-4, rtol=1e-4)
+ def test_unit_quaternion_xyzw(self, device, dtype, atol, rtol):
+ eps = torch.finfo(dtype).eps
+ quaternion_exp = torch.tensor((0., 0., 0., 1.), device=device, dtype=dtype)
+ expected = torch.tensor((0., 0., 0.), device=device, dtype=dtype)
+ with pytest.warns(UserWarning):
+ quaternion_log = kornia.quaternion_exp_to_log(quaternion_exp, eps=eps,
+ order=QuaternionCoeffOrder.XYZW)
+ assert_allclose(quaternion_log, expected, atol=atol, rtol=rtol)
+
+ def test_unit_quaternion(self, device, dtype, atol, rtol):
+ eps = torch.finfo(dtype).eps
+ quaternion_exp = torch.tensor((1., 0., 0., 0.), device=device, dtype=dtype)
+ expected = torch.tensor((0., 0., 0.), device=device, dtype=dtype)
+ quaternion_log = kornia.quaternion_exp_to_log(quaternion_exp, eps=eps,
+ order=QuaternionCoeffOrder.WXYZ)
+ assert_allclose(quaternion_log, expected, atol=atol, rtol=rtol)
+
+ def test_pi_quaternion_x_xyzw(self, device, dtype, atol, rtol):
+ eps = torch.finfo(dtype).eps
+ quaternion_exp = torch.tensor((1., 0., 0., 0.), device=device, dtype=dtype)
+ expected = torch.tensor((kornia.pi / 2., 0., 0.), device=device, dtype=dtype)
+ with pytest.warns(UserWarning):
+ quaternion_log = kornia.quaternion_exp_to_log(quaternion_exp, eps=eps,
+ order=QuaternionCoeffOrder.XYZW)
+ assert_allclose(quaternion_log, expected, atol=atol, rtol=rtol)
+
+ def test_pi_quaternion_x(self, device, dtype, atol, rtol):
+ eps = torch.finfo(dtype).eps
+ quaternion_exp = torch.tensor((0., 1., 0., 0.), device=device, dtype=dtype)
+ expected = torch.tensor((kornia.pi / 2., 0., 0.), device=device, dtype=dtype)
+ quaternion_log = kornia.quaternion_exp_to_log(quaternion_exp, eps=eps,
+ order=QuaternionCoeffOrder.WXYZ)
+ assert_allclose(quaternion_log, expected, atol=atol, rtol=rtol)
+
+ def test_pi_quaternion_y_xyzw(self, device, dtype, atol, rtol):
+ eps = torch.finfo(dtype).eps
+ quaternion_exp = torch.tensor((0., 1., 0., 0.), device=device, dtype=dtype)
+ expected = torch.tensor((0., kornia.pi / 2., 0.), device=device, dtype=dtype)
+ with pytest.warns(UserWarning):
+ quaternion_log = kornia.quaternion_exp_to_log(quaternion_exp, eps=eps,
+ order=QuaternionCoeffOrder.XYZW)
+ assert_allclose(quaternion_log, expected, atol=atol, rtol=rtol)
+
+ def test_pi_quaternion_y(self, device, dtype, atol, rtol):
+ eps = torch.finfo(dtype).eps
+ quaternion_exp = torch.tensor((0., 0., 1., 0.), device=device, dtype=dtype)
+ expected = torch.tensor((0., kornia.pi / 2., 0.), device=device, dtype=dtype)
+ quaternion_log = kornia.quaternion_exp_to_log(quaternion_exp, eps=eps,
+ order=QuaternionCoeffOrder.WXYZ)
+ assert_allclose(quaternion_log, expected, atol=atol, rtol=rtol)
+
+ def test_pi_quaternion_z_xyzw(self, device, dtype, atol, rtol):
+ eps = torch.finfo(dtype).eps
+ quaternion_exp = torch.tensor((0., 0., 1., 0.), device=device, dtype=dtype)
+ expected = torch.tensor((0., 0., kornia.pi / 2.), device=device, dtype=dtype)
+ with pytest.warns(UserWarning):
+ quaternion_log = kornia.quaternion_exp_to_log(quaternion_exp, eps=eps,
+ order=QuaternionCoeffOrder.XYZW)
+ assert_allclose(quaternion_log, expected, atol=atol, rtol=rtol)
+
+ def test_pi_quaternion_z(self, device, dtype, atol, rtol):
+ eps = torch.finfo(dtype).eps
+ quaternion_exp = torch.tensor((0., 0., 0., 1.), device=device, dtype=dtype)
+ expected = torch.tensor((0., 0., kornia.pi / 2.), device=device, dtype=dtype)
+ quaternion_log = kornia.quaternion_exp_to_log(quaternion_exp, eps=eps,
+ order=QuaternionCoeffOrder.WXYZ)
+ assert_allclose(quaternion_log, expected, atol=atol, rtol=rtol)
+
+ def test_back_and_forth_xyzw(self, device, dtype, atol, rtol):
+ eps = torch.finfo(dtype).eps
+ quaternion_exp = torch.tensor((1., 0., 0., 0.), device=device, dtype=dtype)
+
+ with pytest.warns(UserWarning):
+ quaternion_log = kornia.quaternion_exp_to_log(quaternion_exp, eps=eps,
+ order=QuaternionCoeffOrder.XYZW)
+ with pytest.warns(UserWarning):
+ quaternion_exp_hat = kornia.quaternion_log_to_exp(quaternion_log, eps=eps,
+ order=QuaternionCoeffOrder.XYZW)
+ assert_allclose(quaternion_exp, quaternion_exp_hat, atol=atol, rtol=rtol)
+
+ def test_back_and_forth(self, device, dtype, atol, rtol):
+ eps = torch.finfo(dtype).eps
+ quaternion_exp = torch.tensor((0., 1., 0., 0.), device=device, dtype=dtype)
+ quaternion_log = kornia.quaternion_exp_to_log(quaternion_exp, eps=eps,
+ order=QuaternionCoeffOrder.WXYZ)
+ quaternion_exp_hat = kornia.quaternion_log_to_exp(quaternion_log, eps=eps,
+ order=QuaternionCoeffOrder.WXYZ)
+ assert_allclose(quaternion_exp, quaternion_exp_hat, atol=atol, rtol=rtol)
+
+ def test_gradcheck_xyzw(self, device, dtype):
+ eps = torch.finfo(dtype).eps
+ quaternion = torch.tensor((1., 0., 0., 0.), device=device, dtype=dtype)
+ quaternion = tensor_to_gradcheck_var(quaternion)
+ # evaluate function gradient
+ with pytest.warns(UserWarning):
+ assert gradcheck(partial(kornia.quaternion_exp_to_log, eps=eps,
+ order=QuaternionCoeffOrder.XYZW),
+ (quaternion,),
+ raise_exception=True)
def test_gradcheck(self, device, dtype):
- quaternion = torch.tensor([1., 0., 0., 0.], device=device, dtype=dtype)
+ eps = torch.finfo(dtype).eps
+ quaternion = torch.tensor((0., 1., 0., 0.), device=device, dtype=dtype)
quaternion = tensor_to_gradcheck_var(quaternion)
# evaluate function gradient
- assert gradcheck(kornia.quaternion_exp_to_log, (quaternion,),
+ assert gradcheck(partial(kornia.quaternion_exp_to_log, eps=eps,
+ order=QuaternionCoeffOrder.WXYZ),
+ (quaternion,),
raise_exception=True)
- def test_jit(self, device, dtype):
+ @pytest.mark.skipif(torch.__version__.startswith('1.6'), reason='JIT Enum not handled.')
+ def test_jit_xyzw(self, device, dtype, atol, rtol):
op = kornia.geometry.conversions.quaternion_exp_to_log
op_jit = torch.jit.script(op)
- quaternion = torch.tensor([0., 0., 1., 0.], device=device, dtype=dtype)
- assert_allclose(op(quaternion), op_jit(quaternion))
+ quaternion = torch.tensor((0., 0., 1., 0.), device=device, dtype=dtype)
+ with pytest.warns(UserWarning):
+ assert_allclose(op(quaternion), op_jit(quaternion), atol=atol, rtol=rtol)
+ @pytest.mark.skipif(torch.__version__.startswith('1.6'), reason='JIT Enum not handled.')
+ def test_jit(self, device, dtype, atol, rtol):
+ op = kornia.quaternion_exp_to_log
+ op_script = torch.jit.script(op)
-class TestQuaternionToAngleAxis:
+ quaternion = torch.tensor((0., 0., 0., 1.), device=device, dtype=dtype)
+ actual = op_script(quaternion, eps=torch.finfo(dtype).eps, order=QuaternionCoeffOrder.WXYZ)
+ expected = op(quaternion, eps=torch.finfo(dtype).eps, order=QuaternionCoeffOrder.WXYZ)
+ assert_allclose(actual, expected, atol=atol, rtol=rtol)
- def test_smoke(self, device, dtype):
- quaternion = torch.zeros(4, device=device, dtype=dtype)
- angle_axis = kornia.quaternion_to_angle_axis(quaternion)
- assert angle_axis.shape == (3,)
- @pytest.mark.parametrize("batch_size", (1, 3, 8))
- def test_smoke_batch(self, batch_size, device, dtype):
- quaternion = torch.zeros(batch_size, 4, device=device, dtype=dtype)
- angle_axis = kornia.quaternion_to_angle_axis(quaternion)
- assert angle_axis.shape == (batch_size, 3)
+class TestAngleAxisToRotationMatrix:
+
+ @pytest.mark.parametrize("batch_size", (1, 2, 5))
+ def test_rand_angle_axis_gradcheck(self, batch_size, device, dtype, atol, rtol):
+ # generate input data
+ angle_axis = torch.rand(batch_size, 3, device=device, dtype=dtype)
+ eye_batch = create_eye_batch(batch_size, 3, device=device, dtype=dtype)
- def test_unit_quaternion(self, device, dtype):
- quaternion = torch.tensor([1., 0., 0., 0.], device=device, dtype=dtype)
- expected = torch.tensor([0., 0., 0.], device=device, dtype=dtype)
- angle_axis = kornia.quaternion_to_angle_axis(quaternion)
- assert_allclose(angle_axis, expected, atol=1e-4, rtol=1e-4)
-
- def test_y_rotation(self, device, dtype):
- quaternion = torch.tensor([0., 0., 1., 0.], device=device, dtype=dtype)
- expected = torch.tensor([0., kornia.pi, 0.], device=device, dtype=dtype)
- angle_axis = kornia.quaternion_to_angle_axis(quaternion)
- assert_allclose(angle_axis, expected, atol=1e-4, rtol=1e-4)
-
- def test_z_rotation(self, device, dtype):
- quaternion = torch.tensor([np.sqrt(3) / 2, 0., 0., 0.5], device=device, dtype=dtype)
- expected = torch.tensor([0., 0., kornia.pi / 3], device=device, dtype=dtype)
- angle_axis = kornia.quaternion_to_angle_axis(quaternion)
- assert_allclose(angle_axis, expected, atol=1e-4, rtol=1e-4)
-
- def test_small_angle(self, device, dtype):
- theta = 1e-2
- quaternion = torch.tensor([np.cos(theta / 2), np.sin(theta / 2), 0., 0.], device=device, dtype=dtype)
- expected = torch.tensor([theta, 0., 0.], device=device, dtype=dtype)
- angle_axis = kornia.quaternion_to_angle_axis(quaternion)
- assert_allclose(angle_axis, expected, atol=1e-4, rtol=1e-4)
+ # apply transform
+ rotation_matrix = kornia.angle_axis_to_rotation_matrix(angle_axis)
+
+ rotation_matrix_eye = torch.matmul(rotation_matrix, rotation_matrix.transpose(-2, -1))
+ assert_allclose(rotation_matrix_eye, eye_batch, atol=atol, rtol=rtol)
- def test_gradcheck(self, device, dtype):
- eps = 1e-12
- quaternion = torch.tensor([1., 0., 0., 0.], device=device, dtype=dtype) + eps
- quaternion = tensor_to_gradcheck_var(quaternion)
# evaluate function gradient
- assert gradcheck(kornia.quaternion_to_angle_axis, (quaternion,),
+ angle_axis = tensor_to_gradcheck_var(angle_axis) # to var
+ assert gradcheck(kornia.angle_axis_to_rotation_matrix, (angle_axis,),
raise_exception=True)
+ def test_angle_axis_to_rotation_matrix(self, device, dtype, atol, rtol):
+ rmat_1 = torch.tensor(((-0.30382753, -0.95095137, -0.05814062),
+ (-0.71581715, 0.26812278, -0.64476041),
+ (0.62872461, -0.15427791, -0.76217038)), device=device, dtype=dtype)
+ rvec_1 = torch.tensor((1.50485376, -2.10737739, 0.7214174), device=device, dtype=dtype)
+
+ rmat_2 = torch.tensor(((0.6027768, -0.79275544, -0.09054801),
+ (-0.67915707, -0.56931658, 0.46327563),
+ (-0.41881476, -0.21775548, -0.88157628)), device=device, dtype=dtype)
+ rvec_2 = torch.tensor((-2.44916812, 1.18053411, 0.4085298), device=device, dtype=dtype)
+ rmat = torch.stack((rmat_2, rmat_1), dim=0)
+ rvec = torch.stack((rvec_2, rvec_1), dim=0)
+
+ assert_allclose(kornia.angle_axis_to_rotation_matrix(rvec), rmat, atol=atol, rtol=rtol)
+
+
+class TestRotationMatrixToAngleAxis:
+
+ @pytest.mark.parametrize("batch_size", (1, 2, 5))
+ def test_rand_quaternion_gradcheck(self, batch_size, device, dtype, atol, rtol):
+ # generate input data
+ quaternion = torch.rand(batch_size, 4, device=device, dtype=dtype)
+ quaternion = kornia.normalize_quaternion(quaternion)
+ rotation_matrix = kornia.quaternion_to_rotation_matrix(quaternion=quaternion,
+ order=QuaternionCoeffOrder.WXYZ)
+
+ eye_batch = create_eye_batch(batch_size, 3, device=device, dtype=dtype)
+ rotation_matrix_eye = torch.matmul(rotation_matrix, rotation_matrix.transpose(-2, -1))
+ # This didn't pass with atol=0.001, rtol=0.001 for float16 Cuda 11.2 GeForce 1080 Ti
+ assert_allclose(rotation_matrix_eye, eye_batch, atol=atol * 10., rtol=rtol * 10.)
+
+ # evaluate function gradient
+ rotation_matrix = tensor_to_gradcheck_var(rotation_matrix) # to var
+ assert gradcheck(kornia.rotation_matrix_to_angle_axis,
+ (rotation_matrix,), raise_exception=True)
+
+ def test_rotation_matrix_to_angle_axis(self, device, dtype, atol, rtol):
+ rmat_1 = torch.tensor(((-0.30382753, -0.95095137, -0.05814062),
+ (-0.71581715, 0.26812278, -0.64476041),
+ (0.62872461, -0.15427791, -0.76217038)), device=device, dtype=dtype)
+ rvec_1 = torch.tensor((1.50485376, -2.10737739, 0.7214174), device=device, dtype=dtype)
+
+ rmat_2 = torch.tensor(((0.6027768, -0.79275544, -0.09054801),
+ (-0.67915707, -0.56931658, 0.46327563),
+ (-0.41881476, -0.21775548, -0.88157628)), device=device, dtype=dtype)
+ rvec_2 = torch.tensor((-2.44916812, 1.18053411, 0.4085298), device=device, dtype=dtype)
+ rmat = torch.stack((rmat_2, rmat_1), dim=0)
+ rvec = torch.stack((rvec_2, rvec_1), dim=0)
+
+ assert_allclose(kornia.rotation_matrix_to_angle_axis(rmat), rvec, atol=atol, rtol=rtol)
+
def test_pi():
assert_allclose(kornia.pi, 3.141592)
@@ -335,7 +1072,7 @@ def test_rad2deg(batch_shape, device, dtype):
@pytest.mark.parametrize("batch_shape", [
(2, 3), (1, 2, 3), (2, 3, 3), (5, 5, 3), ])
-def test_deg2rad(batch_shape, device, dtype):
+def test_deg2rad(batch_shape, device, dtype, atol, rtol):
# generate input data
x_deg = 180. * torch.rand(batch_shape, device=device, dtype=dtype)
@@ -343,8 +1080,9 @@ def test_deg2rad(batch_shape, device, dtype):
x_rad = kornia.deg2rad(x_deg)
x_rad_to_deg = kornia.rad2deg(x_rad)
- assert_allclose(x_deg, x_rad_to_deg, atol=1e-4, rtol=1e-4)
+ assert_allclose(x_deg, x_rad_to_deg, atol=atol, rtol=rtol)
+ eps = torch.finfo(dtype).eps
assert gradcheck(kornia.deg2rad, (tensor_to_gradcheck_var(x_deg),),
raise_exception=True)
@@ -372,7 +1110,7 @@ class TestPolCartConversions:
assert_allclose(phi, phi_pol2cart)
assert gradcheck(kornia.pol2cart, (tensor_to_gradcheck_var(rho),
- tensor_to_gradcheck_var(phi), ), raise_exception=True)
+ tensor_to_gradcheck_var(phi),), raise_exception=True)
@pytest.mark.parametrize("batch_shape", [
(2, 3), (1, 2, 3), (2, 3, 3), (5, 5, 3), ])
@@ -391,7 +1129,7 @@ class TestPolCartConversions:
assert_allclose(y, y_cart2pol)
assert gradcheck(kornia.cart2pol, (tensor_to_gradcheck_var(x),
- tensor_to_gradcheck_var(y), ), raise_exception=True)
+ tensor_to_gradcheck_var(y),), raise_exception=True)
class TestConvertPointsToHomogeneous:
@@ -572,55 +1310,9 @@ class TestConvertPointsFromHomogeneous:
assert_allclose(op(points_h), op_jit(points_h))
[email protected]("batch_size", [1, 2, 5])
-def test_angle_axis_to_rotation_matrix(batch_size, device, dtype):
- # generate input data
- angle_axis = torch.rand(batch_size, 3, device=device, dtype=dtype)
- eye_batch = create_eye_batch(batch_size, 3, device=device, dtype=dtype)
-
- # apply transform
- rotation_matrix = kornia.angle_axis_to_rotation_matrix(angle_axis)
-
- rotation_matrix_eye = torch.matmul(
- rotation_matrix, rotation_matrix.transpose(1, 2))
- assert_allclose(rotation_matrix_eye, eye_batch, atol=1e-4, rtol=1e-4)
-
- # evaluate function gradient
- angle_axis = tensor_to_gradcheck_var(angle_axis) # to var
- assert gradcheck(kornia.angle_axis_to_rotation_matrix, (angle_axis,),
- raise_exception=True)
-
-
-'''@pytest.mark.parametrize("batch_size", [1, 2, 5])
-def test_rotation_matrix_to_angle_axis_gradcheck(batch_size, device_type):
- # generate input data
- rmat = torch.rand(batch_size, 3, 3).to(torch.device(device_type))
-
- # evaluate function gradient
- rmat = tensor_to_gradcheck_var(rmat) # to var
- assert gradcheck(kornia.rotation_matrix_to_angle_axis,
- (rmat,), raise_exception=True)'''
-
-
-'''def test_rotation_matrix_to_angle_axis(device_type):
- device = torch.device(device_type)
- rmat_1 = torch.tensor([[-0.30382753, -0.95095137, -0.05814062],
- [-0.71581715, 0.26812278, -0.64476041],
- [0.62872461, -0.15427791, -0.76217038]])
- rvec_1 = torch.tensor([1.50485376, -2.10737739, 0.7214174])
-
- rmat_2 = torch.tensor([[0.6027768, -0.79275544, -0.09054801],
- [-0.67915707, -0.56931658, 0.46327563],
- [-0.41881476, -0.21775548, -0.88157628]])
- rvec_2 = torch.tensor([-2.44916812, 1.18053411, 0.4085298])
- rmat = torch.stack([rmat_2, rmat_1], dim=0, device=device, dtype=dtype)
- rvec = torch.stack([rvec_2, rvec_1], dim=0, device=device, dtype=dtype)
-
- assert_allclose(kornia.rotation_matrix_to_angle_axis(rmat), rvec)'''
-
-
class TestNormalizePixelCoordinates:
- def test_tensor_bhw2(self, device, dtype):
+ def test_tensor_bhw2(self, device, dtype, atol, rtol):
+ eps = torch.finfo(dtype).eps
height, width = 3, 4
grid = kornia.utils.create_meshgrid(
height, width, normalized_coordinates=False, device=device).to(dtype=dtype)
@@ -629,11 +1321,12 @@ class TestNormalizePixelCoordinates:
height, width, normalized_coordinates=True, device=device).to(dtype=dtype)
grid_norm = kornia.normalize_pixel_coordinates(
- grid, height, width)
+ grid, height, width, eps=eps)
- assert_allclose(grid_norm, expected, atol=1e-4, rtol=1e-4)
+ assert_allclose(grid_norm, expected, atol=atol, rtol=rtol)
- def test_list(self, device, dtype):
+ def test_list(self, device, dtype, atol, rtol):
+ eps = torch.finfo(dtype).eps
height, width = 3, 4
grid = kornia.utils.create_meshgrid(
height, width, normalized_coordinates=False, device=device).to(dtype=dtype)
@@ -644,9 +1337,9 @@ class TestNormalizePixelCoordinates:
expected = expected.contiguous().view(-1, 2)
grid_norm = kornia.normalize_pixel_coordinates(
- grid, height, width)
+ grid, height, width, eps=eps)
- assert_allclose(grid_norm, expected, atol=1e-4, rtol=1e-4)
+ assert_allclose(grid_norm, expected, atol=atol, rtol=rtol)
def test_jit(self, device, dtype):
op = kornia.geometry.conversions.normalize_pixel_coordinates
diff --git a/test/geometry/transform/test_imgwarp.py b/test/geometry/transform/test_imgwarp.py
index 05f1a37af..f2d2a5c23 100644
--- a/test/geometry/transform/test_imgwarp.py
+++ b/test/geometry/transform/test_imgwarp.py
@@ -166,7 +166,7 @@ class TestWarpAffine:
# invert the transform
aff_ba = kornia.convert_affinematrix_to_homography(aff_ab).inverse()[..., :2, :]
img_b_hat = kornia.warp_affine(img_a, aff_ba, (h, w))
- assert_allclose(img_b_hat, img_b)
+ assert_allclose(img_b_hat, img_b, atol=1e-3, rtol=1e-3)
def test_jit(self, device, dtype):
aff_ab = torch.eye(2, 3, device=device, dtype=dtype)[None]
diff --git a/test/integration/test_conversions.py b/test/integration/test_conversions.py
new file mode 100644
index 000000000..efab59604
--- /dev/null
+++ b/test/integration/test_conversions.py
@@ -0,0 +1,548 @@
+import numpy as np
+import pytest
+import torch
+from torch.testing import assert_allclose
+
+import kornia
+from kornia.geometry.conversions import QuaternionCoeffOrder
+
+
+def atol(device, dtype):
+ """Lower tolerance for cuda-float16 only"""
+ if 'cuda' in device.type and dtype == torch.float16:
+ return 1.e-3
+ else:
+ return 1.e-4
+
+
+def rtol(device, dtype):
+ """Lower tolerance for cuda-float16 only"""
+ if 'cuda' in device.type and dtype == torch.float16:
+ return 1.e-3
+ else:
+ return 1.e-4
+
+
+class TestAngleAxisToQuaternionToAngleAxis:
+ def test_zero_angle(self, device, dtype, atol, rtol):
+ angle_axis = torch.tensor((0., 0., 0.), device=device, dtype=dtype)
+ quaternion = kornia.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.WXYZ)
+ angle_axis_hat = kornia.quaternion_to_angle_axis(quaternion,
+ order=QuaternionCoeffOrder.WXYZ)
+ assert_allclose(angle_axis_hat, angle_axis, atol=atol, rtol=rtol)
+
+ @pytest.mark.parametrize("axis", (0, 1, 2))
+ def test_small_angle(self, axis, device, dtype, atol, rtol):
+ theta = 1.e-2
+ array = [0., 0., 0.]
+ array[axis] = theta
+ angle_axis = torch.tensor(array, device=device, dtype=dtype)
+ quaternion = kornia.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.WXYZ)
+ angle_axis_hat = kornia.quaternion_to_angle_axis(quaternion,
+ order=QuaternionCoeffOrder.WXYZ)
+ assert_allclose(angle_axis_hat, angle_axis, atol=atol, rtol=rtol)
+
+ @pytest.mark.parametrize("axis", (0, 1, 2))
+ def test_rotation(self, axis, device, dtype, atol, rtol):
+ # half_sqrt2 = 0.5 * np.sqrt(2)
+ array = [0., 0., 0.]
+ array[axis] = kornia.pi / 2.
+ angle_axis = torch.tensor(array, device=device, dtype=dtype)
+ quaternion = kornia.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.WXYZ)
+ angle_axis_hat = kornia.quaternion_to_angle_axis(quaternion,
+ order=QuaternionCoeffOrder.WXYZ)
+ assert_allclose(angle_axis_hat, angle_axis, atol=atol, rtol=rtol)
+
+
+class TestQuaternionToAngleAxisToQuaternion:
+ def test_unit_quaternion_xyzw(self, device, dtype, atol, rtol):
+ quaternion = torch.tensor((0., 0., 0., 1.), device=device, dtype=dtype)
+ with pytest.warns(UserWarning):
+ angle_axis = kornia.quaternion_to_angle_axis(quaternion,
+ order=QuaternionCoeffOrder.XYZW)
+ with pytest.warns(UserWarning):
+ quaternion_hat = kornia.angle_axis_to_quaternion(angle_axis,
+ order=QuaternionCoeffOrder.XYZW)
+ assert_allclose(quaternion_hat, quaternion, atol=atol, rtol=rtol)
+
+ def test_unit_quaternion(self, device, dtype, atol, rtol):
+ quaternion = torch.tensor((1., 0., 0., 0.), device=device, dtype=dtype)
+ angle_axis = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.WXYZ)
+ quaternion_hat = kornia.angle_axis_to_quaternion(angle_axis,
+ order=QuaternionCoeffOrder.WXYZ)
+ assert_allclose(quaternion_hat, quaternion, atol=atol, rtol=rtol)
+
+ @pytest.mark.parametrize("axis", (0, 1, 2))
+ def test_rotation_xyzw(self, axis, device, dtype, atol, rtol):
+ array = [0., 0., 0., 0.]
+ array[axis] = 1.
+ quaternion = torch.tensor(array, device=device, dtype=dtype)
+ with pytest.warns(UserWarning):
+ angle_axis = kornia.quaternion_to_angle_axis(quaternion,
+ order=QuaternionCoeffOrder.XYZW)
+ with pytest.warns(UserWarning):
+ quaternion_hat = kornia.angle_axis_to_quaternion(angle_axis,
+ order=QuaternionCoeffOrder.XYZW)
+ assert_allclose(quaternion_hat, quaternion, atol=atol, rtol=rtol)
+
+ @pytest.mark.parametrize("axis", (0, 1, 2))
+ def test_rotation(self, axis, device, dtype, atol, rtol):
+ array = [0., 0., 0., 0.]
+ array[1 + axis] = 1.
+ quaternion = torch.tensor(array, device=device, dtype=dtype)
+ angle_axis = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.WXYZ)
+ quaternion_hat = kornia.angle_axis_to_quaternion(angle_axis,
+ order=QuaternionCoeffOrder.WXYZ)
+ assert_allclose(quaternion_hat, quaternion, atol=atol, rtol=rtol)
+
+ # just to be sure, check that mixing orders fails
+ with pytest.warns(UserWarning):
+ quaternion_hat_wrong = kornia.angle_axis_to_quaternion(angle_axis,
+ order=QuaternionCoeffOrder.XYZW)
+ assert not torch.allclose(quaternion_hat_wrong, quaternion, atol=atol, rtol=rtol)
+
+ @pytest.mark.parametrize("axis", (0, 1, 2))
+ def test_small_angle_xyzw(self, axis, device, dtype, atol, rtol):
+ theta = 1.e-2
+ array = [0., 0., 0., np.cos(theta / 2)]
+ array[axis] = np.sin(theta / 2.)
+ quaternion = torch.tensor(array, device=device, dtype=dtype)
+ with pytest.warns(UserWarning):
+ angle_axis = kornia.quaternion_to_angle_axis(quaternion,
+ order=QuaternionCoeffOrder.XYZW)
+ with pytest.warns(UserWarning):
+ quaternion_hat = kornia.angle_axis_to_quaternion(angle_axis,
+ order=QuaternionCoeffOrder.XYZW)
+ assert_allclose(quaternion_hat, quaternion, atol=atol, rtol=rtol)
+
+ @pytest.mark.parametrize("axis", (0, 1, 2))
+ def test_small_angle(self, axis, device, dtype, atol, rtol):
+ theta = 1.e-2
+ array = [np.cos(theta / 2), 0., 0., 0.]
+ array[1 + axis] = np.sin(theta / 2.)
+ quaternion = torch.tensor(array, device=device, dtype=dtype)
+ angle_axis = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.WXYZ)
+ quaternion_hat = kornia.angle_axis_to_quaternion(angle_axis,
+ order=QuaternionCoeffOrder.WXYZ)
+ assert_allclose(quaternion_hat, quaternion, atol=atol, rtol=rtol)
+
+ # just to be sure, check that mixing orders fails
+ with pytest.warns(UserWarning):
+ quaternion_hat_wrong = kornia.angle_axis_to_quaternion(angle_axis,
+ order=QuaternionCoeffOrder.XYZW)
+ assert not torch.allclose(quaternion_hat_wrong, quaternion, atol=atol, rtol=rtol)
+
+
+class TestQuaternionToRotationMatrixToAngleAxis:
+ @pytest.mark.parametrize("axis", (0, 1, 2))
+ def test_triplet_qma_xyzw(self, axis, device, dtype, atol, rtol):
+ array = [[0., 0., 0., 0.]]
+ array[0][axis] = 1. # `0 + axis` should fail when WXYZ
+ quaternion = torch.tensor(array, device=device, dtype=dtype)
+ assert quaternion.shape[-1] == 4
+
+ with pytest.warns(UserWarning):
+ mm = kornia.quaternion_to_rotation_matrix(quaternion, order=QuaternionCoeffOrder.XYZW)
+ assert mm.shape[-1] == 3
+ assert mm.shape[-2] == 3
+
+ angle_axis = kornia.rotation_matrix_to_angle_axis(mm)
+ assert angle_axis.shape[-1] == 3
+ angle_axis_expected = [[0., 0., 0.]]
+ angle_axis_expected[0][axis] = kornia.pi
+ angle_axis_expected = torch.tensor(angle_axis_expected, device=device, dtype=dtype)
+ assert_allclose(angle_axis, angle_axis_expected, atol=atol, rtol=rtol)
+
+ with pytest.warns(UserWarning):
+ quaternion_hat = kornia.angle_axis_to_quaternion(angle_axis,
+ order=QuaternionCoeffOrder.XYZW)
+ assert_allclose(quaternion_hat, quaternion, atol=atol, rtol=rtol)
+
+ @pytest.mark.parametrize("axis", (0, 1, 2))
+ def test_triplet_qma(self, axis, device, dtype, atol, rtol):
+ array = [[0., 0., 0., 0.]]
+ array[0][1 + axis] = 1. # `1 + axis` this should fail when XYZW
+ quaternion = torch.tensor(array, device=device, dtype=dtype)
+ assert quaternion.shape[-1] == 4
+
+ mm = kornia.quaternion_to_rotation_matrix(quaternion, order=QuaternionCoeffOrder.WXYZ)
+ assert mm.shape[-1] == 3
+ assert mm.shape[-2] == 3
+
+ angle_axis = kornia.rotation_matrix_to_angle_axis(mm)
+ assert angle_axis.shape[-1] == 3
+ angle_axis_expected = [[0., 0., 0.]]
+ angle_axis_expected[0][axis] = kornia.pi
+ angle_axis_expected = torch.tensor(angle_axis_expected, device=device, dtype=dtype)
+ assert_allclose(angle_axis, angle_axis_expected, atol=atol, rtol=rtol)
+
+ quaternion_hat = kornia.angle_axis_to_quaternion(angle_axis,
+ order=QuaternionCoeffOrder.WXYZ)
+ assert_allclose(quaternion_hat, quaternion, atol=atol, rtol=rtol)
+
+ @pytest.mark.parametrize("axis", (0, 1, 2))
+ def test_triplet_qam_xyzw(self, axis, device, dtype, atol, rtol):
+ array = [[0., 0., 0., 0.]]
+ array[0][axis] = 1.
+ quaternion = torch.tensor(array, device=device, dtype=dtype)
+ assert quaternion.shape[-1] == 4
+
+ with pytest.warns(UserWarning):
+ angle_axis = kornia.quaternion_to_angle_axis(quaternion,
+ order=QuaternionCoeffOrder.XYZW)
+ assert angle_axis.shape[-1] == 3
+
+ rot_m = kornia.angle_axis_to_rotation_matrix(angle_axis)
+ assert rot_m.shape[-1] == 3
+ assert rot_m.shape[-2] == 3
+
+ with pytest.warns(UserWarning):
+ quaternion_hat = kornia.rotation_matrix_to_quaternion(rot_m,
+ order=QuaternionCoeffOrder.XYZW)
+ assert_allclose(quaternion_hat, quaternion, atol=atol, rtol=rtol)
+
+ @pytest.mark.parametrize("axis", (0, 1, 2))
+ def test_triplet_qam(self, axis, device, dtype, atol, rtol):
+ array = [[0., 0., 0., 0.]]
+ array[0][1 + axis] = 1.
+ quaternion = torch.tensor(array, device=device, dtype=dtype)
+ assert quaternion.shape[-1] == 4
+
+ angle_axis = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.WXYZ)
+ assert angle_axis.shape[-1] == 3
+
+ rot_m = kornia.angle_axis_to_rotation_matrix(angle_axis)
+ assert rot_m.shape[-1] == 3
+ assert rot_m.shape[-2] == 3
+
+ quaternion_hat = kornia.rotation_matrix_to_quaternion(rot_m,
+ order=QuaternionCoeffOrder.WXYZ)
+ assert_allclose(quaternion_hat, quaternion, atol=atol, rtol=rtol)
+
+ @pytest.mark.parametrize("axis", (0, 1, 2))
+ def test_triplet_amq_xyzw(self, axis, device, dtype, atol, rtol):
+ array = [[0., 0., 0.]]
+ array[0][axis] = kornia.pi / 2.
+ angle_axis = torch.tensor(array, device=device, dtype=dtype)
+ assert angle_axis.shape[-1] == 3
+
+ rot_m = kornia.angle_axis_to_rotation_matrix(angle_axis)
+ assert rot_m.shape[-1] == 3
+ assert rot_m.shape[-2] == 3
+
+ with pytest.warns(UserWarning):
+ quaternion = kornia.rotation_matrix_to_quaternion(rot_m,
+ order=QuaternionCoeffOrder.XYZW)
+ assert quaternion.shape[-1] == 4
+
+ with pytest.warns(UserWarning):
+ angle_axis_hat = kornia.quaternion_to_angle_axis(quaternion,
+ order=QuaternionCoeffOrder.XYZW)
+ assert_allclose(angle_axis_hat, angle_axis, atol=atol, rtol=rtol)
+
+ @pytest.mark.parametrize("axis", (0, 1, 2))
+ def test_triplet_amq(self, axis, device, dtype, atol, rtol):
+ array = [[0., 0., 0.]]
+ array[0][axis] = kornia.pi / 2.
+ angle_axis = torch.tensor(array, device=device, dtype=dtype)
+ assert angle_axis.shape[-1] == 3
+
+ rot_m = kornia.angle_axis_to_rotation_matrix(angle_axis)
+ assert rot_m.shape[-1] == 3
+ assert rot_m.shape[-2] == 3
+
+ quaternion = kornia.rotation_matrix_to_quaternion(rot_m,
+ order=QuaternionCoeffOrder.WXYZ)
+ assert quaternion.shape[-1] == 4
+
+ angle_axis_hat = kornia.quaternion_to_angle_axis(quaternion,
+ order=QuaternionCoeffOrder.WXYZ)
+ assert_allclose(angle_axis_hat, angle_axis, atol=atol, rtol=rtol)
+
+ @pytest.mark.parametrize("axis", (0, 1, 2))
+ def test_triplet_aqm_xyzw(self, axis, device, dtype, atol, rtol):
+ array = [[0., 0., 0.]]
+ array[0][axis] = kornia.pi / 2.
+ angle_axis = torch.tensor(array, device=device, dtype=dtype)
+ assert angle_axis.shape[-1] == 3
+
+ with pytest.warns(UserWarning):
+ quaternion = kornia.angle_axis_to_quaternion(angle_axis,
+ order=QuaternionCoeffOrder.XYZW)
+ assert quaternion.shape[-1] == 4
+
+ with pytest.warns(UserWarning):
+ rot_m = kornia.quaternion_to_rotation_matrix(quaternion,
+ order=QuaternionCoeffOrder.XYZW)
+ assert rot_m.shape[-1] == 3
+ assert rot_m.shape[-2] == 3
+
+ angle_axis_hat = kornia.rotation_matrix_to_angle_axis(rot_m)
+ assert_allclose(angle_axis_hat, angle_axis, atol=atol, rtol=rtol)
+
+ @pytest.mark.parametrize("axis", (0, 1, 2))
+ def test_triplet_aqm(self, axis, device, dtype, atol, rtol):
+ array = [[0., 0., 0.]]
+ array[0][axis] = kornia.pi / 2.
+ angle_axis = torch.tensor(array, device=device, dtype=dtype)
+ assert angle_axis.shape[-1] == 3
+
+ quaternion = kornia.angle_axis_to_quaternion(angle_axis,
+ order=QuaternionCoeffOrder.WXYZ)
+ assert quaternion.shape[-1] == 4
+
+ rot_m = kornia.quaternion_to_rotation_matrix(quaternion,
+ order=QuaternionCoeffOrder.WXYZ)
+ assert rot_m.shape[-1] == 3
+ assert rot_m.shape[-2] == 3
+
+ angle_axis_hat = kornia.rotation_matrix_to_angle_axis(rot_m)
+ assert_allclose(angle_axis_hat, angle_axis, atol=atol, rtol=rtol)
+
+
+class TestAngleOfRotations:
+ """
+ See: https://arxiv.org/pdf/1711.02508.pdf
+ """
+
+ @staticmethod
+ def matrix_angle_abs(mx: torch.Tensor):
+ """Unsigned rotation matrix angle"""
+ trace = torch.diagonal(mx[..., :3, :3], dim1=-1, dim2=-2).sum(-1, keepdim=True)
+ return torch.acos((trace - 1.) / 2.)
+
+ @staticmethod
+ def axis_and_angle_to_rotation_matrix(axis_name: str, angle: torch.Tensor, device, dtype):
+ """
+ See also: https://en.wikipedia.org/wiki/Rotation_matrix#Basic_rotations
+ """
+ axis_name = axis_name.lower()
+ assert axis_name in ('x', 'y', 'z')
+ sn = torch.sin(angle)
+ cs = torch.cos(angle)
+ ones = torch.ones_like(sn)
+ zeros = torch.zeros_like(sn)
+ if axis_name == 'x':
+ axis = torch.tensor((1., 0., 0.), device=device, dtype=dtype).repeat(angle.size())
+ rot_m = torch.stack((ones, zeros, zeros, zeros, cs, -sn, zeros, sn, cs), dim=2) \
+ .view(-1, 3, 3)
+ elif axis_name == 'y':
+ axis = torch.tensor((0., 1., 0.), device=device, dtype=dtype).repeat(angle.size())
+ rot_m = torch.stack((cs, zeros, sn, zeros, ones, zeros, -sn, zeros, cs), dim=2) \
+ .view(-1, 3, 3)
+ elif axis_name == 'z':
+ axis = torch.tensor((0., 0., 1.), device=device, dtype=dtype).repeat(angle.size())
+ rot_m = torch.stack((cs, -sn, zeros, sn, cs, zeros, zeros, zeros, ones), dim=2) \
+ .view(-1, 3, 3)
+ else:
+ raise NotImplementedError(f'Not prepared for axis with name {axis_name}')
+
+ return rot_m, axis
+
+ @pytest.mark.parametrize('axis_name', ('x', 'y', 'z'))
+ def test_axis_angle_to_rotation_matrix(self, axis_name, device, dtype, atol, rtol):
+ # Random angle in [-pi..pi]
+ angle = torch.tensor((np.random.random(size=(2, 1)) * 2. * np.pi - np.pi), device=device,
+ dtype=dtype)
+ rot_m, axis = TestAngleOfRotations.axis_and_angle_to_rotation_matrix(
+ axis_name=axis_name, angle=angle, device=device, dtype=dtype)
+ assert rot_m.dim() == 3
+ assert rot_m.shape[-1] == 3
+ assert rot_m.shape[-2] == 3
+ assert rot_m.shape[-3] == angle.numel()
+ assert axis.shape[-1] == 3
+ assert axis.shape[-2] == angle.numel()
+
+ # Make sure the returned axis matches the named one, and the appropriate column
+ if axis_name == 'x':
+ assert_allclose(axis, torch.tensor(((1., 0., 0.),) * angle.numel(), device=device,
+ dtype=dtype))
+ assert_allclose(axis, rot_m[..., :3, 0])
+ elif axis_name == 'y':
+ assert_allclose(axis, torch.tensor(((0., 1., 0.),) * angle.numel(), device=device,
+ dtype=dtype))
+ assert_allclose(axis, rot_m[..., :3, 1])
+ elif axis_name == 'z':
+ assert_allclose(axis, torch.tensor(((0., 0., 1.),) * angle.numel(), device=device,
+ dtype=dtype))
+ assert_allclose(axis, rot_m[..., :3, 2])
+ else:
+ raise NotImplementedError(f'Not prepared for axis_name {axis_name}')
+
+ # Make sure axes are perpendicular
+ zero = torch.zeros_like(angle).unsqueeze(-1)
+ assert_allclose(rot_m[..., :3, 1:2].permute((0, 2, 1)) @ rot_m[..., :3, 0:1], zero,
+ atol=atol, rtol=rtol)
+ assert_allclose(rot_m[..., :3, 2:3].permute((0, 2, 1)) @ rot_m[..., :3, 1:2], zero,
+ atol=atol, rtol=rtol)
+ assert_allclose(rot_m[..., :3, 2:3].permute((0, 2, 1)) @ rot_m[..., :3, 0:1], zero,
+ atol=atol, rtol=rtol)
+
+ # Make sure axes are unit norm
+ one = torch.ones_like(angle)
+ assert_allclose(rot_m[..., :3, 0].norm(p=2, dim=-1, keepdim=True), one,
+ atol=atol, rtol=rtol)
+ assert_allclose(rot_m[..., :3, 1].norm(p=2, dim=-1, keepdim=True), one,
+ atol=atol, rtol=rtol)
+ assert_allclose(rot_m[..., :3, 2].norm(p=2, dim=-1, keepdim=True), one,
+ atol=atol, rtol=rtol)
+
+ @pytest.mark.parametrize('axis_name', ('x', 'y', 'z'))
+ @pytest.mark.parametrize("angle_deg", (-179.9, -135., -90., -45., 0., 45, 90, 135, 179.9))
+ def test_matrix_angle(self, axis_name, angle_deg, device, dtype):
+ angle = (angle_deg * kornia.pi / 180.).to(dtype).to(device).view(1, 1)
+ rot_m, _ = TestAngleOfRotations.axis_and_angle_to_rotation_matrix(axis_name=axis_name,
+ angle=angle,
+ device=device,
+ dtype=dtype)
+ matrix_angle_abs = TestAngleOfRotations.matrix_angle_abs(rot_m)
+ assert_allclose(torch.abs(angle), matrix_angle_abs)
+
+ @pytest.mark.parametrize('axis_name', ('x', 'y', 'z'))
+ @pytest.mark.parametrize("angle_deg", (-179.9, -90., -45., 0., 45, 90, 179.9))
+ def test_quaternion_xyzw(self, axis_name, angle_deg, device, dtype, atol, rtol):
+ eps = torch.finfo(dtype).eps
+ angle = torch.tensor((angle_deg * kornia.pi / 180.,), device=device, dtype=dtype) \
+ .repeat(2, 1)
+ pi = torch.ones_like(angle) * kornia.pi
+ assert 2 <= len(angle.shape)
+ rot_m, axis = TestAngleOfRotations.axis_and_angle_to_rotation_matrix(axis_name=axis_name,
+ angle=angle,
+ device=device,
+ dtype=dtype)
+ with pytest.warns(UserWarning):
+ quaternion = kornia.rotation_matrix_to_quaternion(rot_m, eps=eps,
+ order=QuaternionCoeffOrder.XYZW)
+ # compute quaternion rotation angle
+ # See Section 2.4.4 Equation (105a) in https://arxiv.org/pdf/1711.02508.pdf
+ angle_hat = 2. * torch.atan2(quaternion[..., :3].norm(p=2, dim=-1, keepdim=True),
+ quaternion[..., 3:4])
+ # make sure it lands between [-pi..pi)
+ mask = pi < angle_hat
+ while torch.any(mask):
+ angle_hat = torch.where(mask, angle_hat - 2. * kornia.pi, angle_hat)
+ mask = pi < angle_hat
+ # invert angle, if quaternion axis points in the opposite direction of the original axis
+ dots = (quaternion[..., :3] * axis).sum(dim=-1, keepdim=True)
+ angle_hat = torch.where(dots < 0., angle_hat * -1., angle_hat)
+ # quaternion angle should match input angle
+ assert_allclose(angle_hat, angle, atol=atol, rtol=rtol)
+ # magnitude of angle should match matrix rotation angle
+ matrix_angle_abs = TestAngleOfRotations.matrix_angle_abs(rot_m)
+ assert_allclose(torch.abs(angle_hat), matrix_angle_abs, atol=atol, rtol=rtol)
+
+ @pytest.mark.parametrize('axis_name', ('x', 'y', 'z'))
+ @pytest.mark.parametrize("angle_deg", (-179.9, -90., -45., 0., 45, 90, 179.9))
+ def test_quaternion(self, axis_name, angle_deg, device, dtype, atol, rtol):
+ eps = torch.finfo(dtype).eps
+ angle = torch.tensor((angle_deg * kornia.pi / 180.,), device=device, dtype=dtype) \
+ .repeat(2, 1)
+ pi = torch.ones_like(angle) * kornia.pi
+ assert 2 <= len(angle.shape)
+ rot_m, axis = TestAngleOfRotations.axis_and_angle_to_rotation_matrix(axis_name=axis_name,
+ angle=angle,
+ device=device,
+ dtype=dtype)
+ quaternion = kornia.rotation_matrix_to_quaternion(rot_m, eps=eps,
+ order=QuaternionCoeffOrder.WXYZ)
+ # compute quaternion rotation angle
+ # See Section 2.4.4 Equation (105a) in https://arxiv.org/pdf/1711.02508.pdf
+ angle_hat = 2. * torch.atan2(quaternion[..., 1:4].norm(p=2, dim=-1, keepdim=True),
+ quaternion[..., 0:1])
+ # make sure it lands between [-pi..pi)
+ mask = pi < angle_hat
+ while torch.any(mask):
+ angle_hat = torch.where(mask, angle_hat - 2. * kornia.pi, angle_hat)
+ mask = pi < angle_hat
+ # invert angle, if quaternion axis points in the opposite direction of the original axis
+ dots = (quaternion[..., 1:4] * axis).sum(dim=-1, keepdim=True)
+ angle_hat = torch.where(dots < 0., angle_hat * -1., angle_hat)
+ # quaternion angle should match input angle
+ assert_allclose(angle_hat, angle, atol=atol, rtol=rtol)
+ # magnitude of angle should match matrix rotation angle
+ matrix_angle_abs = TestAngleOfRotations.matrix_angle_abs(rot_m)
+ assert_allclose(torch.abs(angle_hat), matrix_angle_abs, atol=atol, rtol=rtol)
+
+ @pytest.mark.parametrize('axis_name', ('x', 'y', 'z'))
+ @pytest.mark.parametrize("angle_deg", (-179.9, -90., -45., 0, 45, 90, 179.9))
+ def test_angle_axis(self, axis_name, angle_deg, device, dtype, atol, rtol):
+ angle = (angle_deg * kornia.pi / 180.).to(dtype).to(device).repeat(2, 1)
+ rot_m, axis = TestAngleOfRotations.axis_and_angle_to_rotation_matrix(axis_name=axis_name,
+ angle=angle,
+ device=device,
+ dtype=dtype)
+ angle_axis = kornia.rotation_matrix_to_angle_axis(rot_m)
+ # compute angle_axis rotation angle
+ angle_hat = angle_axis.norm(p=2, dim=-1, keepdim=True)
+ # invert angle, if angle_axis axis points in the opposite direction of the original axis
+ dots = (angle_axis * axis).sum(dim=-1, keepdim=True)
+ angle_hat = torch.where(dots < 0., angle_hat * -1., angle_hat)
+ # angle_axis angle should match input angle
+ assert_allclose(angle_hat, angle, atol=atol, rtol=rtol)
+ # magnitude of angle should match matrix rotation angle
+ matrix_angle_abs = TestAngleOfRotations.matrix_angle_abs(rot_m)
+ assert_allclose(torch.abs(angle_hat), matrix_angle_abs, atol=atol, rtol=rtol)
+
+ @pytest.mark.parametrize('axis_name', ('x', 'y', 'z'))
+ @pytest.mark.parametrize("angle_deg", (-179.9, -90., -45., 0, 45, 90, 179.9))
+ def test_log_quaternion_xyzw(self, axis_name, angle_deg, device, dtype, atol, rtol):
+ eps = torch.finfo(dtype).eps
+ angle = (angle_deg * kornia.pi / 180.).to(dtype).to(device).repeat(2, 1)
+ pi = torch.ones_like(angle) * kornia.pi
+ rot_m, axis = TestAngleOfRotations.axis_and_angle_to_rotation_matrix(axis_name=axis_name,
+ angle=angle,
+ device=device,
+ dtype=dtype)
+ with pytest.warns(UserWarning):
+ quaternion = kornia.rotation_matrix_to_quaternion(rot_m, eps=eps,
+ order=QuaternionCoeffOrder.XYZW)
+ with pytest.warns(UserWarning):
+ log_q = kornia.quaternion_exp_to_log(quaternion, eps=eps,
+ order=QuaternionCoeffOrder.XYZW)
+ # compute angle_axis rotation angle
+ angle_hat = 2. * log_q.norm(p=2, dim=-1, keepdim=True)
+ # make sure it lands between [-pi..pi)
+ mask = pi < angle_hat
+ while torch.any(mask):
+ angle_hat = torch.where(mask, angle_hat - 2. * kornia.pi, angle_hat)
+ mask = pi < angle_hat
+ # invert angle, if angle_axis axis points in the opposite direction of the original axis
+ dots = (log_q * axis).sum(dim=-1, keepdim=True)
+ angle_hat = torch.where(dots < 0., angle_hat * -1., angle_hat)
+ # angle_axis angle should match input angle
+ assert_allclose(angle_hat, angle, atol=atol, rtol=rtol)
+ # magnitude of angle should match matrix rotation angle
+ matrix_angle_abs = TestAngleOfRotations.matrix_angle_abs(rot_m)
+ assert_allclose(torch.abs(angle_hat), matrix_angle_abs, atol=atol, rtol=rtol)
+
+ @pytest.mark.parametrize('axis_name', ('x', 'y', 'z'))
+ @pytest.mark.parametrize("angle_deg", (-179.9, -90., -45., 0, 45, 90, 179.9))
+ def test_log_quaternion(self, axis_name, angle_deg, device, dtype, atol, rtol):
+ eps = torch.finfo(dtype).eps
+ angle = (angle_deg * kornia.pi / 180.).to(dtype).to(device).repeat(2, 1)
+ pi = torch.ones_like(angle) * kornia.pi
+ rot_m, axis = TestAngleOfRotations.axis_and_angle_to_rotation_matrix(axis_name=axis_name,
+ angle=angle,
+ device=device,
+ dtype=dtype)
+ quaternion = kornia.rotation_matrix_to_quaternion(rot_m, eps=eps,
+ order=QuaternionCoeffOrder.WXYZ)
+ log_q = kornia.quaternion_exp_to_log(quaternion, eps=eps,
+ order=QuaternionCoeffOrder.WXYZ)
+ # compute angle_axis rotation angle
+ angle_hat = 2. * log_q.norm(p=2, dim=-1, keepdim=True)
+ # make sure it lands between [-pi..pi)
+ mask = pi < angle_hat
+ while torch.any(mask):
+ angle_hat = torch.where(mask, angle_hat - 2. * kornia.pi, angle_hat)
+ mask = pi < angle_hat
+ # invert angle, if angle_axis axis points in the opposite direction of the original axis
+ dots = (log_q * axis).sum(dim=-1, keepdim=True)
+ angle_hat = torch.where(dots < 0., angle_hat * -1., angle_hat)
+ # angle_axis angle should match input angle
+ assert_allclose(angle_hat, angle, atol=atol, rtol=rtol)
+ # magnitude of angle should match matrix rotation angle
+ matrix_angle_abs = TestAngleOfRotations.matrix_angle_abs(rot_m)
+ assert_allclose(torch.abs(angle_hat), matrix_angle_abs, atol=atol, rtol=rtol)