python中将四元数转换为旋转矩阵

在制作bundlefusion时,想测试TUM数据集,并且将groundtruth写入到数据集中,TUM中给定的groundtruth中的旋转是使用四元数表示的,而bundlefusion中需要SE3的形式,所以我需要首先将四元数转换为旋转矩阵,然后再将其与平移向量合并在一起,因为我之前关于生成bundlefusion数据集写了一些python脚本,所以这次仍然想在原来的脚本上完成这项任务,所以我就在网上搜索,实现方法,最终我成功解决这个问题的方法如下:

最近买了个,所以我可以潇洒的在google中搜索 quaternion to rotation matrix python, 然后 就找到了这个

https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.transform.Rotation.html

我安装了conda,所以首先我使用下面这条指令安装scipy

conda install scipy

安装之后,我在pycharm上编辑代码,运行一下,提示说找不到scipy这个模块,我很纳闷,这是咋回事,我命名安装了呀,

我下意识的感觉到了什么, 我的pycharm链接到的是本地的python3.7,而我是在conda的base的环境下安装的scipy,所以我在python 的setting中更改了,连接的python版本

from scipy.spatial.transform import Rotation as R

 就是这个地方,改了之后,pycharm就可以识别scipy了.

python中将四元数转换为旋转矩阵_第1张图片

下面是我的测试代码,里面还包括了,numpy中的矩阵的合并,设置数据类型等知识点,这些知识正好是今天早晨看morvan python学到的.

https://morvanzhou.github.io/tutorials/data-manipulation/np-pd/2-6-np-concat/ 

 

from scipy.spatial.transform import Rotation as R
import numpy as np
print('test')
# use [:, np.newaxis] to transform from row vector to col vector
position = np.array([0.6453529828252734, -0.26022684372145516, 1.179122068068349])[:, np.newaxis]
share_vector = np.array([0,0,0,1], dtype=float)[np.newaxis, :]
print('share_vector:\n', share_vector)
print('position:\n',position)
r = R.from_quat([-0.716556549511624,-0.6971278819736084, -0.010016582945017661,  0.02142651612120239])
r.as_matrix()
print('rotation:\n',r.as_matrix())
rotation_matrix = r.as_matrix()
print(rotation_matrix)

#combine three matrix or vector together
m34 = np.concatenate((rotation_matrix, position), axis = 1)
print(m34)
m44 = np.concatenate((m34, share_vector), axis=0)
# m44 = np.hstack((m34, share_vector))

print(m44)

rot_vec = r.as_rotvec()
print('rot_vec:\n', rot_vec)
rot_euler = r.as_euler('zyx', degrees = False)
print('rot_euler:\n',rot_euler)

r = R.from_matrix(rotation_matrix)
print('as_quat():\n',r.as_quat())
print('as_rotvec():\n', r.as_rotvec())
print('as_euler():\n', r.as_euler('zyx', degrees=True))

 

你可能感兴趣的:(机器视觉,python)