Last active
May 29, 2021 10:50
-
-
Save ugo-nama-kun/ee773f7ddf7fa443ddbf651f9d70dcbb to your computer and use it in GitHub Desktop.
Quarternion to Euler & Euler to Quarternion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Reference: https://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles | |
# Quaternion to Euler | |
def qtoeuler(q): | |
""" quaternion to Euler angle | |
:param q: quaternion | |
:return: | |
""" | |
# roll (x-axis rotation) | |
sinr_cosp = 2 * (q[0] * q[1] + q[2] * q[3]) | |
cosr_cosp = 1 - 2 * (q[1] * q[1] + q[2] * q[2]) | |
roll = np.arctan2(sinr_cosp, cosr_cosp) | |
# pitch (y-axis rotation) | |
sinp = 2 * (q[0] * q[2] - q[3] * q[1]) | |
if np.abs(sinp) >= 1: | |
pitch = np.sign(sinp) * np.pi / 2 # use 90 degrees if out of range | |
else: | |
pitch = np.arcsin(sinp) | |
# yaw (z-axis rotation) | |
siny_cosp = 2 * (q[0] * q[3] + q[1] * q[2]) | |
cosy_cosp = 1 - 2 * (q[2] * q[2] + q[3] * q[3]) | |
yaw = np.arctan2(siny_cosp, cosy_cosp) | |
return np.array([pitch, roll, yaw]) | |
# Euler to Quaternion | |
def eulertoq(euler): | |
pitch, roll, yaw = euler | |
cy = np.cos(yaw * 0.5) | |
sy = np.sin(yaw * 0.5) | |
cp = np.cos(pitch * 0.5) | |
sp = np.sin(pitch * 0.5) | |
cr = np.cos(roll * 0.5) | |
sr = np.sin(roll * 0.5) | |
return np.array([ | |
cr * cp * cy + sr * sp * sy, | |
sr * cp * cy - cr * sp * sy, | |
cr * sp * cy + sr * cp * sy, | |
cr * cp * sy - sr * sp * cy, | |
]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment