Convert between a quaternion and its Euler angles (and vice versa)

The quaternion values (w,x,y,z) can be computed from the ZYX Euler angles \left(\phi,\theta,\psi\right):

w = \cos\left(\frac{\phi}{2}\right) \cos\left(\frac{\theta}{2}\right) \cos\left(\frac{\psi}{2}\right) + \sin\left(\frac{\phi}{2}\right) \sin\left(\frac{\theta}{2}\right) \sin\left(\frac{\psi}{2}\right)\\
x = \sin\left(\frac{\phi}{2}\right) \cos\left(\frac{\theta}{2}\right) \cos\left(\frac{\psi}{2}\right) - \cos\left(\frac{\phi}{2}\right) \sin\left(\frac{\theta}{2}\right) \sin\left(\frac{\psi}{2}\right)\\
y = \cos\left(\frac{\phi}{2}\right) \sin\left(\frac{\theta}{2}\right) \cos\left(\frac{\psi}{2}\right) + \sin\left(\frac{\phi}{2}\right) \cos\left(\frac{\theta}{2}\right) \sin\left(\frac{\psi}{2}\right)\\
z = \cos\left(\frac{\phi}{2}\right) \cos\left(\frac{\theta}{2}\right) \sin\left(\frac{\psi}{2}\right) - \sin\left(\frac{\phi}{2}\right) \sin\left(\frac{\theta}{2}\right) \cos\left(\frac{\psi}{2}\right)

or inversely the ZYX Euler angles (in radians) \left(\phi,\theta,\psi\right) can be derived from the quaternion values (w,x,y,z):

\phi &= \text{atan2}\left(wx+yz,~\frac{1}{2}-\left(x^2+y^2\right)\right) \quad \text{ rotation around the x-axis, between } -\pi \text{ and } \pi\\
\theta &= \text{asin} \left( \text{max} \left( \text{min} \left( 2\left(wy-xz\right), 1 \right), -1 \right) \right) \quad \text{ rotation around the y-axis, between } -\frac{\pi}{2} \text{ and } \frac{\pi}{2}\\
\psi &= \text{atan2}\left(wz+xy,~\frac{1}{2}-\left(y^2+z^2\right)\right) \quad \text{ rotation around the z-axis, between } -\pi \text{ and } \pi

There are several online tools to perform these conversion, see for example here.