代碼如下:
//旋轉矩陣轉歐拉角
static Eigen::Vector3d R2ypr(const Eigen::Matrix3d &R)
{
Eigen::Vector3d n = R.col(0);
Eigen::Vector3d o = R.col(1);
Eigen::Vector3d a = R.col(2);
Eigen::Vector3d ypr(3);
double y = atan2(n(1), n(0));
double p = atan2(-n(2), n(0) * cos(y) + n(1) * sin(y));
double r = atan2(a(0) * sin(y) - a(1) * cos(y), -o(0) * sin(y) + o(1) * cos(y));
ypr(0) = y;
ypr(1) = p;
ypr(2) = r;
return ypr / M_PI * 180.0;
}
//歐拉角轉旋轉矩陣
template <typename Derived>
static Eigen::Matrix<typename Derived::Scalar, 3, 3> ypr2R(const Eigen::MatrixBase<Derived> &ypr)
{
typedef typename Derived::Scalar Scalar_t;
Scalar_t y = ypr(0) / 180.0 * M_PI;//yaw
Scalar_t p = ypr(1) / 180.0 * M_PI;//pitch
Scalar_t r = ypr(2) / 180.0 * M_PI;//roll
//繞z軸的旋轉矩陣
Eigen::Matrix<Scalar_t, 3, 3> Rz;
Rz << cos(y), -sin(y), 0,
sin(y), cos(y), 0,
0, 0, 1;
//繞y軸的旋轉矩陣
Eigen::Matrix<Scalar_t, 3, 3> Ry;
Ry << cos(p), 0., sin(p),
0., 1., 0.,
-sin(p), 0., cos(p);
//繞x軸的旋轉矩陣
Eigen::Matrix<Scalar_t, 3, 3> Rx;
Rx << 1., 0., 0.,
0., cos(r), -sin(r),
0., sin(r), cos(r);
return Rz * Ry * Rx;//合併
}