Then (suppose the coordinates before rotation: ( x0, y0, z0 ) , the coordinates after rotation: ( x3, y3, z3 )):
- # Quaternion converted to Euler angles
- def quat2eular (w, x, y, z):
- # Cartesian coordinate system
- roll = math.atan2(2 * (w * x + y * z), 1 - 2 * (x * x + y * y))
- pitch = math.asin(2 * (w * y - x * z))
- yaw = math.atan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z))
- # Direct3D, the X axis of the Cartesian coordinates becomes the Z axis , the Y axis becomes the X axis , and the Z axis becomes the Y axis
- # roll = math.atan2(2 * (w * z + x * y), 1 - 2 * (z * z + x * x))
- # pitch = math.asin(2 * (w * x - y * z))
- # yaw = math.atan2(2 * (w * y + z * x), 1 - 2 * (x * x + y * y))
- # Converted into an angle
- return math.degrees(yaw), math.degrees(pitch), math.degrees(roll)
- # Euler angles is converted to quaternions , rotation sequence is ZYX ( yaw angle Yaw, pitch angle Pitch, roll angle of roll)
- def eular2quat(yaw, pitch, roll):
- #Note that this must be converted to radians first , because all the triangle calculations here use radians .
- yaw = math.radians(yaw)
- pitch = math.radians(pitch)
- roll = math.radians(roll)
- en , sy = math.cos (yaw * 0.5 ), math.sin (yaw * 0.5 )
- cp, sp = math.cos(pitch * 0.5), math.sin(pitch * 0.5)
- cr, sr = math.cos(roll * 0.5), math.sin(roll * 0.5)
- # Cartesian coordinate system
- w = c * ep * cs + r * sp * sy
- x = r * ep * cy - er * sp * sy
- y = cr * sp * cy + sr * cp * sy
- z = c * ep * sy - r * sp * cs
- # Direct3D, the X axis of the Cartesian coordinates becomes the Z axis , the Y axis becomes the X axis , and the Z axis becomes the Y axis
- # W 'cp = CR + SR * Cy * sp * sy
- # X = c * sp * cs + SR 'cp * sy
- # y = cr * cp * sy - sr * sp * cy
- # Z = r * CP * cy - er sp * sy
- return w, x, y, z
- if __name__ == "__main__":
- y, p, r = (10, 20, 30)
- q0, q1, q2, q3 = eular2quat(y, p, r)
- print(q0, q1, q2, q3)
- y, p, r = quat2eular(q0, q1, q2, q3)
- q0, q1, q2, q3 = eular2quat(y, p, r)
- print(q0, q1, q2, q3)
- print(quat2eular(q0, q1, q2, q3))