Overview
This article discuss how to convert a quaternion to a set of Euler angles. This mathematics is not trivial that I can forget the rationale if I don’t record it.
Theory
Suppose we have a quaternion $\mathbf{q}$ having element $q_i$ representing a 3-dimensional orientation. The quaternion can be expressed in complex-like form:
Another form to express an orientation is to use Euler angles $(\phi, \theta, \psi)$. The Euler angles are often called pitch, yaw and roll in flight dynamics.
A quaternion and a set of Euler angles are equivalent. You can convert Euler angles to a quaternion by making quaternions for each axis angles and then obtaining product of these quaternions, but the other way around is not as obvious.
The problem is that there are multiple conventions for Euler angles’ definition, so we cannot easily copy and paste from some random source on the Internet. Instead, we need to intrinsically understand how to convert one another. But there’s one article whose purpose is close to ours:
http://graphics.wikia.com/wiki/Conversion_between_quaternions_and_Euler_angles
Unfortunately, the article’s definition for axes is different from ours.
In our case, Z-axis points backward, X-axis to the right and Y-axis upward. This convention is chosen because it forms Cartesian coordinates if we were to look from the vehicle’s view, and we (and OpenGL) prefer right hand system.
Thus, our definitions are:
- Roll - $\phi$: rotation about the Z-axis
- Pitch - $\theta$: rotation about the X-axis
- Yaw - $\psi$: rotation about the Y-axis
Rotation order is the same as the reference, i.e. in the order yaw, pitch, roll.
Rotation quaternions for each angle are defined as below:
Rotation matrices
Rotation matrix corresponding to the quaternion $\mathbf{q}$ is the same as the reference.
The rotation matrices for each of Euler angles $(\phi, \theta, \psi)$ are
Product of those 3 matrices yields
$\mathbf{q}$ and $\mathbf{R}\psi \mathbf{R}\theta \mathbf{R}_\phi$ must be equal, so we can compare the elements to obtain the relationships