When gimbal lock occurs, multiple combinations of Euler angles can produce the same rotation matrix. For example, in an 'sxyz' sequence where the $y$ angle is $-\pi/2$, you can achieve the same transformation by adding a value to the $x$ angle and subtracting it from the $z$ angle, or by combining them into a single $x$ rotation and setting $z$ to 0.
To avoid the mathematical ambiguity of gimbal lock, you can:
- Change the rotation order: Use a different sequence (e.g., 'sxzy' instead of 'sxyz') so the axes do not align in the same way.
- Recalculate angles: Use
mat2euler to find a new set of Euler angles that represent the same rotation matrix without the lock-induced ambiguity.
import numpy as np
from transforms3d.euler import euler2mat, mat2euler
# Example of gimbal lock scenario
x_angle = -0.2
y_angle = -np.pi / 2
z_angle = -0.2
# This matrix is subject to gimbal lock
R = euler2mat(x_angle, y_angle, z_angle, 'sxyz')
# You can achieve the same R by combining x and z:
R_dash = euler2mat(x_angle + z_angle, y_angle, 0, 'sxyz')
print(np.allclose(R, R_dash)) # Returns True
# To get a 'clean' representation, convert the matrix back to Euler angles
x_dash, y_dash, z_dash = mat2euler(R, 'sxyz')
print(np.array((x_dash, y_dash, z_dash)))