Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient quaternions to Euler transformation

I'm using the following Python function to convert quaternions to Euler angles:

import math

def quaternion_to_euler_angle(w, x, y, z):
    ysqr = y * y

    t0 = +2.0 * (w * x + y * z)
    t1 = +1.0 - 2.0 * (x * x + ysqr)
    X = math.degrees(math.atan2(t0, t1))

    t2 = +2.0 * (w * y - z * x)
    t2 = +1.0 if t2 > +1.0 else t2
    t2 = -1.0 if t2 < -1.0 else t2
    Y = math.degrees(math.asin(t2))

    t3 = +2.0 * (w * z + x * y)
    t4 = +1.0 - 2.0 * (ysqr + z * z)
    Z = math.degrees(math.atan2(t3, t4))

    return X, Y, Z

I would like to transform a Pandas DataFrame, which has columns "w", "quat_x", "quat_y" and "quat_z", to Eueler angles. Currently, I'm iterating over each row of the DataFrame using a for loop and call the quaternion_to_euler_angle() function on each row. This is very slow because I have more than 400'000 rows.

Is there a more efficient way to do it? For example, I could pass the DataFrame (or inidividual Series) to quaternion_to_euler_angle() but then the problem is to change quaternion_to_euler_angle() so that it can handle DataFrames instead of integers.

like image 772
machinery Avatar asked Jun 09 '26 08:06

machinery


1 Answers

A more compact way is to use Rotation from scipy.spatial.transform:

import pandas as pd
from scipy.spatial.transform import Rotation

rot = Rotation.from_quat(quat_df)
rot_euler = rot.as_euler('xyz', degrees=True)
euler_df = pd.DataFrame(data=rot_euler, columns=['x', 'y', 'z'])
like image 134
SaTa Avatar answered Jun 10 '26 23:06

SaTa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!