python_四元数q转旋转矩阵R(已验证)

注意: 符号相反的四元数,代表同一个旋转 (q = -q )

四元数 -> 旋转矩阵

方法1

使用公式: https://doc.rc-visard.com/latest/de/pose_formats.html?highlight=format

 

方法2

 使用库scipy中的方法 Rm = R.from_quat(Rq)

from scipy.spatial.transform import Rotation as R

Rq=[-0.35, 1.23e-06, 4.18e-08, 0.39]
Rm = R.from_quat(Rq)
rotation_matrix = Rm.as_matrix()
print('rotation:\n',rotation_matrix)

#结果:
rotation:
 [[ 1.00000000e+00 -3.25420248e-06  3.38725419e-06]
 [-3.01673707e-06  1.07793154e-01  9.94173343e-01]
 [-3.60036417e-06 -9.94173343e-01  1.07793154e-01]]

备注: SLAM十四讲 第一版中公式(3.35)形式是对的,但R的下标和位置有误, 在第二版中未再提及该公式 

-----------------------

下面两个转换待验证

旋转矩阵-> 欧拉角

参考:https://www.learnopencv.com/rotation-matrix-to-euler-angles/

# Calculates Rotation Matrix given euler angles.
def eulerAnglesToRotationMatrix(theta) :
    
    R_x = np.array([[1,         0,                  0                   ],
                    [0,         math.cos(theta[0]), -math.sin(theta[0]) ],
                    [0,         math.sin(theta[0]), math.cos(theta[0])  ]
                    ])
                    
    R_y = np.array([[math.cos(theta[1]),    0,      math.sin(theta[1])  ],
                    [0,                     1,      0                   ],
                    [-math.sin(theta[1]),   0,      math.cos(theta[1])  ]
                    ])
                
    R_z = np.array([[math.cos(theta[2]),    -math.sin(theta[2]),    0],
                    [math.sin(theta[2]),    math.cos(theta[2]),     0],
                    [0,                     0,                      1]
                    ])               
                    
    R = np.dot(R_z, np.dot( R_y, R_x ))

    return R

欧拉角-> 旋转矩阵

# Checks if a matrix is a valid rotation matrix.
def isRotationMatrix(R) :
    Rt = np.transpose(R)
    shouldBeIdentity = np.dot(Rt, R)
    I = np.identity(3, dtype = R.dtype)
    n = np.linalg.norm(I - shouldBeIdentity)
    return n < 1e-6

# Calculates rotation matrix to euler angles
# The result is the same as MATLAB except the order
# of the euler angles ( x and z are swapped ).
def rotationMatrixToEulerAngles(R) :

    assert(isRotationMatrix(R)) 
    sy = math.sqrt(R[0,0] * R[0,0] +  R[1,0] * R[1,0]) 
    singular = sy < 1e-6

    if  not singular :
        x = math.atan2(R[2,1] , R[2,2])
        y = math.atan2(-R[2,0], sy)
        z = math.atan2(R[1,0], R[0,0])
    else :
        x = math.atan2(-R[1,2], R[1,1])
        y = math.atan2(-R[2,0], sy)
        z = 0

    return np.array([x, y, z])

 

评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

惊鸿一博

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值