Jump to content

Connect Leeroopedia MCP: Equip your AI agents to search best practices, build plans, verify code, diagnose failures, and look up hyperparameter defaults.

Implementation:Kornia Kornia Quaternion

From Leeroopedia


Knowledge Sources
Domains Vision, Geometry
Last Updated 2026-02-09 15:00 GMT

Overview

Provides a full-featured Quaternion class (as an nn.Module) for representing and manipulating 3D rotations, including arithmetic, conversion to/from rotation matrices, Euler angles, and axis-angle, plus SLERP interpolation and weighted averaging.

Description

The quaternion.py module in the Kornia geometry library defines the Quaternion class, an nn.Module subclass that stores quaternion data in (w, x, y, z) format as a tensor of shape (B, 4). It supports full quaternion algebra (addition, subtraction, multiplication, division, negation, exponentiation), conversion to and from rotation matrices, Euler angles (roll/pitch/yaw in XYZ convention), and axis-angle representations. Additional capabilities include normalization, conjugation, inversion, norm computation, spherical linear interpolation (SLERP), and identity/random quaternion generation. The module also provides an average_quaternions function for computing the (weighted) average of multiple quaternions using eigendecomposition. The class is inspired by Eigen, Sophus, and PyQuaternion libraries.

Usage

Import the Quaternion class when you need a differentiable, object-oriented quaternion representation for 3D rotation manipulation, pose estimation, SLAM, robotics, or animation interpolation in PyTorch.

Code Reference

Source Location

Signature

class Quaternion(nn.Module):
    def __init__(self, data: Union[torch.Tensor, nn.Parameter]) -> None
    def __neg__(self) -> "Quaternion"
    def __add__(self, right: Union["Quaternion", torch.Tensor, float]) -> "Quaternion"
    def __sub__(self, right: Union["Quaternion", torch.Tensor, float]) -> "Quaternion"
    def __mul__(self, right: Union["Quaternion", torch.Tensor, float]) -> "Quaternion"
    def __truediv__(self, right: Union[torch.Tensor, "Quaternion", float]) -> "Quaternion"
    def __pow__(self, t: float) -> "Quaternion"

    @property
    def data(self) -> torch.Tensor  # shape (B, 4)
    @property
    def real(self) -> torch.Tensor  # shape (B,)
    @property
    def vec(self) -> torch.Tensor   # shape (B, 3)
    @property
    def w(self) -> torch.Tensor
    @property
    def x(self) -> torch.Tensor
    @property
    def y(self) -> torch.Tensor
    @property
    def z(self) -> torch.Tensor
    @property
    def polar_angle(self) -> torch.Tensor

    def matrix(self) -> torch.Tensor  # (B, 3, 3)
    @classmethod
    def from_matrix(cls, matrix: torch.Tensor) -> "Quaternion"
    @classmethod
    def from_euler(cls, roll, pitch, yaw) -> "Quaternion"
    def to_euler(self) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]
    @classmethod
    def from_axis_angle(cls, axis_angle: torch.Tensor) -> "Quaternion"
    def to_axis_angle(self) -> torch.Tensor
    @classmethod
    def identity(cls, batch_size=None, device=None, dtype=None) -> "Quaternion"
    @classmethod
    def from_coeffs(cls, w, x, y, z) -> "Quaternion"
    @classmethod
    def random(cls, batch_size=None, device=None, dtype=None) -> "Quaternion"

    def slerp(self, q1: "Quaternion", t: float) -> "Quaternion"
    def norm(self, keepdim: bool = False) -> torch.Tensor
    def normalize(self) -> "Quaternion"
    def conj(self) -> "Quaternion"
    def inv(self) -> "Quaternion"
    def squared_norm(self) -> torch.Tensor

def average_quaternions(Q: "Quaternion", w: Optional[torch.Tensor] = None) -> "Quaternion"

Import

from kornia.geometry.quaternion import Quaternion, average_quaternions

I/O Contract

Inputs (Quaternion.__init__)

Name Type Required Description
data torch.Tensor or nn.Parameter Yes Quaternion data of shape (B, 4) in (w, x, y, z) format

Outputs (Quaternion.matrix)

Name Type Description
rotation_matrix torch.Tensor Rotation matrix of shape (B, 3, 3)

Inputs (average_quaternions)

Name Type Required Description
Q Quaternion Yes Quaternion object with data of shape (M, 4)
w torch.Tensor No Weights of shape (M,). Uniform if None

Outputs (average_quaternions)

Name Type Description
q_avg Quaternion Averaged quaternion with data of shape (1, 4)

Usage Examples

import torch
from kornia.geometry.quaternion import Quaternion, average_quaternions

# Create identity quaternion
q_id = Quaternion.identity(batch_size=4)
# q_id.data shape: (4, 4) = [[1,0,0,0], ...]

# Create from rotation matrix
R = torch.eye(3).unsqueeze(0)  # (1, 3, 3)
q = Quaternion.from_matrix(R)

# Convert back to rotation matrix
R_back = q.matrix()  # (1, 3, 3)

# Create from Euler angles
q_euler = Quaternion.from_euler(
    roll=torch.tensor(0.0),
    pitch=torch.tensor(1.0),
    yaw=torch.tensor(0.0),
)

# Quaternion multiplication (composition)
q1 = Quaternion.identity()
q2 = Quaternion(torch.tensor([0.7071, 0.7071, 0., 0.]))
q3 = q1 * q2

# SLERP interpolation
q_interp = q1.slerp(q2, t=0.5)

# Random quaternion
q_rand = Quaternion.random(batch_size=8)

# Average quaternions
Q = Quaternion(torch.randn(10, 4))
q_avg = average_quaternions(Q)

Related Pages

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment