ROS 中使用 C/C++ 实现四元数(xyzw)和欧拉角(roll, pitch, yaw)的转换

Quaternion - 四元数,Euler angles - 欧拉角,Roll - 侧倾/翻滚,Pitch - 俯仰,Yaw - 横摆/偏航

基础知识

四元数

围绕一个固定点,任何三维旋转以及三维旋转的叠加都等价于:围绕穿过该固定点的某一轴线 e \mathbf{e} e,转过一个角度 θ \theta θ,如下图所示。

在这里插入图片描述

四元数就是针对绕轴旋转的一种空间旋转表达方式,所谓四元即四个变量:xyzw,其中包含一个向量和一个标量,即 w + x i + y j + z k w+x\mathbf{i} + y\mathbf{j} + z\mathbf{k} w+xi+yj+zk,在已知轴线 e x i + e y j + e z k e_{x} \mathbf{i}+e_{y} \mathbf{j}+e_{z} \mathbf{k} exi+eyj+ezk 和转过的角度 θ \theta θ 时,可以计算对应的四元数 q \mathbf{q} q

q = cos ⁡ θ 2 + ( e x i + e y j + e z k ) sin ⁡ θ 2 = cos ⁡ θ 2 + e sin ⁡ θ 2 \mathbf{q} = \cos \frac{\theta}{2}+\left(e_{x} \mathbf{i}+e_{y} \mathbf{j}+e_{z} \mathbf{k}\right) \sin \frac{\theta}{2}=\cos \frac{\theta}{2}+\mathbf{e} \sin \frac{\theta}{2} q=cos2θ+(exi+eyj+ezk)sin2θ=cos2θ+esin2θ

四元数的特点:

  • 多个四元数表示的绕轴旋转可以通过相乘叠加,易于计算
  • 相比欧拉角的绕 XYZ 轴旋转而言,四元数较难理解

欧拉角

包括侧倾角(Roll),俯仰角(Pitch)和横摆角(Yaw),如下图所示。

在这里插入图片描述

C/C++ 转换

四元数转欧拉角

// 引入 tf2::Matrix3x3 和 tf2::Quaternion
#include <tf2/LinearMath/Matrix3x3.h>

// 首先赋值待转换的四元数
tf2::Quaternion myQuaternion(0, 0, 0, 1);
//使用 Matrix3x3 工具,其构造函数可以直接输入四元数
tf2::Matrix3x3 myMat(myQuaternion);

// 定义待赋值的 RPY 变量,使用 getRPY 对其赋值
double roll, pitch, yaw;
myMat.getRPY(&roll, &pitch, &yaw);

欧拉角转四元数

// 引入 tf2::Quaternion
#include <tf2/LinearMath/Quaternion.h>
// 引入 M_PI
#define _USE_MATH_DEFINES
#include <math.h>

tf2::Quaternion myQuaternion;
// setRPY 的输入为弧度值的 RPY
// 例如下面表示绕 Z 轴旋转 90 度
myQuaternion.setRPY(0, 0,  M_PI / 2.0);

// 使用 .get?() 访问对应的四元数
ROS_INFO_STREAM("x: " << myQuaternion.getX() << " y: " << myQuaternion.getY() << 
                " z: " << myQuaternion.getZ() << " w: " << myQuaternion.getW());
  • 30
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值