很好的学习ceres的习题,难度很低,容易入手.

ceres结构体构造:

struct ICPCeres
{/*** @brief Construct a new ICPCeres object* * @param uvw:当前帧3d点* @param xyz:上一帧3d点*/ICPCeres(cv::Point3f uvw, cv::Point3f xyz) : _uvw(uvw), _xyz(xyz) {}template <typename T>/*** @brief * * @param camera * @param residual * @return true * @return false */bool operator()(const T *const camera,T *residual) const{T p[3];T point[3];point[0] = T(_xyz.x);point[1] = T(_xyz.y);point[2] = T(_xyz.z);AngleAxisRotatePoint(camera, point, p);p[0] += camera[3];p[1] += camera[4];p[2] += camera[5];//计算误差 e=p-(Rp‘+t)residual[0] = T(_uvw.x) - p[0];residual[1] = T(_uvw.y) - p[1];residual[2] = T(_uvw.z) - p[2];return true;}const cv::Point3f _uvw;const cv::Point3f _xyz;
};

其中AngleAxisRotatePoint在rotation.h中,作用是投影两帧之前的点,得到两帧之间camera的Rotation和position

rotation.h

#ifndef ROTATION_H
#define ROTATION_H#include <algorithm>
#include <cmath>
#include <limits>//
// math functions needed for rotation conversion.// dot and cross productiontemplate <typename T>
inline T DotProduct(const T x[3], const T y[3])
{return (x[0] * y[0] + x[1] * y[1] + x[2] * y[2]);
}template <typename T>
inline void CrossProduct(const T x[3], const T y[3], T result[3])
{result[0] = x[1] * y[2] - x[2] * y[1];result[1] = x[2] * y[0] - x[0] * y[2];result[2] = x[0] * y[1] - x[1] * y[0];
}//// Converts from a angle anxis to quaternion :
template <typename T>
inline void AngleAxisToQuaternion(const T *angle_axis, T *quaternion)
{const T &a0 = angle_axis[0];const T &a1 = angle_axis[1];const T &a2 = angle_axis[2];const T theta_squared = a0 * a0 + a1 * a1 + a2 * a2;if (theta_squared > T(std::numeric_limits<double>::epsilon())){const T theta = sqrt(theta_squared);const T half_theta = theta * T(0.5);const T k = sin(half_theta) / theta;quaternion[0] = cos(half_theta);quaternion[1] = a0 * k;quaternion[2] = a1 * k;quaternion[3] = a2 * k;}else{ // in case if theta_squared is zeroconst T k(0.5);quaternion[0] = T(1.0);quaternion[1] = a0 * k;quaternion[2] = a1 * k;quaternion[3] = a2 * k;}
}template <typename T>
inline void QuaternionToAngleAxis(const T *quaternion, T *angle_axis)
{const T &q1 = quaternion[1];const T &q2 = quaternion[2];const T &q3 = quaternion[3];const T sin_squared_theta = q1 * q1 + q2 * q2 + q3 * q3;// For quaternions representing non-zero rotation, the conversion// is numercially stableif (sin_squared_theta > T(std::numeric_limits<double>::epsilon())){const T sin_theta = sqrt(sin_squared_theta);const T &cos_theta = quaternion[0];// If cos_theta is negative, theta is greater than pi/2, which// means that angle for the angle_axis vector which is 2 * theta// would be greater than pi...const T two_theta = T(2.0) * ((cos_theta < 0.0)? atan2(-sin_theta, -cos_theta): atan2(sin_theta, cos_theta));const T k = two_theta / sin_theta;angle_axis[0] = q1 * k;angle_axis[1] = q2 * k;angle_axis[2] = q3 * k;}else{// For zero rotation, sqrt() will produce NaN in derivative since// the argument is zero. By approximating with a Taylor series,// and truncating at one term, the value and first derivatives will be// computed correctly when Jets are used..const T k(2.0);angle_axis[0] = q1 * k;angle_axis[1] = q2 * k;angle_axis[2] = q3 * k;}
}template <typename T>
inline void AngleAxisRotatePoint(const T angle_axis[3], const T pt[3], T result[3])
{const T theta2 = DotProduct(angle_axis, angle_axis);if (theta2 > T(std::numeric_limits<double>::epsilon())){// Away from zero, use the rodriguez formula////   result = pt costheta +//            (w x pt) * sintheta +//            w (w . pt) (1 - costheta)//// We want to be careful to only evaluate the square root if the// norm of the angle_axis vector is greater than zero. Otherwise// we get a division by zero.//const T theta = sqrt(theta2);const T costheta = cos(theta);const T sintheta = sin(theta);const T theta_inverse = 1.0 / theta;const T w[3] = {angle_axis[0] * theta_inverse,angle_axis[1] * theta_inverse,angle_axis[2] * theta_inverse};// Explicitly inlined evaluation of the cross product for// performance reasons./*const T w_cross_pt[3] = { w[1] * pt[2] - w[2] * pt[1],w[2] * pt[0] - w[0] * pt[2],w[0] * pt[1] - w[1] * pt[0] };*/T w_cross_pt[3];CrossProduct(w, pt, w_cross_pt);const T tmp = DotProduct(w, pt) * (T(1.0) - costheta);//    (w[0] * pt[0] + w[1] * pt[1] + w[2] * pt[2]) * (T(1.0) - costheta);result[0] = pt[0] * costheta + w_cross_pt[0] * sintheta + w[0] * tmp;result[1] = pt[1] * costheta + w_cross_pt[1] * sintheta + w[1] * tmp;result[2] = pt[2] * costheta + w_cross_pt[2] * sintheta + w[2] * tmp;}else{// Near zero, the first order Taylor approximation of the rotation// matrix R corresponding to a vector w and angle w is////   R = I + hat(w) * sin(theta)//// But sintheta ~ theta and theta * w = angle_axis, which gives us////  R = I + hat(w)//// and actually performing multiplication with the point pt, gives us// R * pt = pt + w x pt.//// Switching to the Taylor expansion near zero provides meaningful// derivatives when evaluated using Jets.//// Explicitly inlined evaluation of the cross product for// performance reasons./*const T w_cross_pt[3] = { angle_axis[1] * pt[2] - angle_axis[2] * pt[1],angle_axis[2] * pt[0] - angle_axis[0] * pt[2],angle_axis[0] * pt[1] - angle_axis[1] * pt[0] };*/T w_cross_pt[3];CrossProduct(angle_axis, pt, w_cross_pt);result[0] = pt[0] + w_cross_pt[0];result[1] = pt[1] + w_cross_pt[1];result[2] = pt[2] + w_cross_pt[2];}
}#endif // rotation.h

整体代码如下

ceres_icp.cpp

#include <iostream>
#include <chrono>
#include <ceres/ceres.h>
#include <opencv2/features2d/features2d.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/calib3d/calib3d.hpp>
#include <opencv2/core/eigen.hpp>
#include <Eigen/Core>
#include <Eigen/Geometry>
#include <Eigen/SVD>
#include "rotation.h"struct ICPCeres
{/*** @brief Construct a new ICPCeres object* * @param uvw:当前帧3d点* @param xyz:上一帧3d点*/ICPCeres(cv::Point3f uvw, cv::Point3f xyz) : _uvw(uvw), _xyz(xyz) {}template <typename T>/*** @brief * * @param camera * @param residual * @return true * @return false */bool operator()(const T *const camera,T *residual) const{T p[3];T point[3];point[0] = T(_xyz.x);point[1] = T(_xyz.y);point[2] = T(_xyz.z);AngleAxisRotatePoint(camera, point, p);p[0] += camera[3];p[1] += camera[4];p[2] += camera[5];//计算误差 e=p-(Rp‘+t)residual[0] = T(_uvw.x) - p[0];residual[1] = T(_uvw.y) - p[1];residual[2] = T(_uvw.z) - p[2];return true;}const cv::Point3f _uvw;const cv::Point3f _xyz;
};void find_feature_matches(const cv::Mat &img_1, const cv::Mat &img_2,std::vector<cv::KeyPoint> &keypoints_1,std::vector<cv::KeyPoint> &keypoints_2,std::vector<cv::DMatch> &matches);// 像素坐标转相机归一化坐标
cv::Point2d pixel2cam(const cv::Point2d &p, const cv::Mat &K);void pose_estimation_3d3d(const std::vector<cv::Point3f> &pts1,const std::vector<cv::Point3d> &pts2,cv::Mat &R, cv::Mat &t);int main (int argc, char ** argv) {if (argc != 5){std::cout << "usage: pose_estimation_3d3d img1 img2 depth1 depth2 !" << std::endl;return -1;}double camera[6] = {0, 1, 2, 0, 0, 0}; //初始位姿估计(R,t), 6维cv::Mat img_1 = cv::imread(argv[1], CV_LOAD_IMAGE_COLOR);cv::Mat img_2 = cv::imread(argv[2], CV_LOAD_IMAGE_COLOR);cv::Mat depth1 = cv::imread(argv[3], CV_LOAD_IMAGE_UNCHANGED);cv::Mat depth2 = cv::imread(argv[4], CV_LOAD_IMAGE_UNCHANGED);std::vector<cv::KeyPoint> keypoints_1, keypoints_2;std::vector<cv::DMatch> matches;find_feature_matches(img_1, img_2, keypoints_1, keypoints_2, matches);std::cout << "Find number of matched point: " << matches.size() << std::endl;cv::Mat K = (cv::Mat_<double>(3, 3) << 520.9, 0, 325.1, 0, 521.0, 249.7, 0, 0, 1);std::vector<cv::Point3d> pts1, pts2;for (cv::DMatch m : matches) {ushort d1 = depth1.ptr<unsigned short>(int(keypoints_1[m.queryIdx].pt.y))[int(keypoints_1[m.queryIdx].pt.x)]; //提取特征点深度信息ushort d2 = depth2.ptr<unsigned short>(int(keypoints_2[m.trainIdx].pt.y))[int(keypoints_2[m.trainIdx].pt.x)];if (d1 == 0 || d2 == 0) { //深度无效点continue;}cv::Point2d p1 = pixel2cam(keypoints_1[m.queryIdx].pt, K);cv::Point2d p2 = pixel2cam(keypoints_2[m.trainIdx].pt, K);float dd1 = float(d1) / 5000.0; //相机的参数,(和奥比中光一样必须要除,有点坑)float dd2 = float(d2) / 5000.0;pts1.push_back(cv::Point3f(p1.x * dd1, p1.y * dd1, dd1));pts2.push_back(cv::Point3f(p2.x * dd2, p2.y * dd2, dd2));}std::cout << "3d-3d pairs: " << pts1.size() << std::endl;cv::Mat R, t;ceres::Problem problem;for (int i = 0; i < pts2.size();  ++i) {ceres::CostFunction *cost_function = new ceres::AutoDiffCostFunction<ICPCeres, 3, 6>//3为输出残差维数, x,y,z的差值. 6为输入维数R(3维)t(3维)
(new ICPCeres(pts2[i], pts1[i]));problem.AddResidualBlock(cost_function, nullptr, camera);}ceres::Solver::Options options;options.linear_solver_type = ceres::DENSE_QR;options.minimizer_progress_to_stdout = true;ceres::Solver::Summary summery;ceres::Solve(options, &problem, &summery);std::cout << summery.FullReport() << "\n";cv::Mat R_vec = (cv::Mat_<double>(3, 1) << camera[0], camera[1], camera[2]); // 数组转cv向量cv::Mat R_cvest;Rodrigues(R_vec, R_cvest); // 罗德里格斯公式,旋转向量转旋转矩阵std::cout << "R_cvest=" << R_cvest << std::endl;Eigen::Matrix<double, 3, 3> R_est;cv2eigen(R_cvest, R_est); // cv矩阵转eigen矩阵std::cout << "R_est=" << R_est << std::endl;Eigen::Vector3d t_est(camera[3], camera[4], camera[5]);std::cout << "t_est=" << t_est << std::endl;Eigen::Isometry3d T(R_est); // 构造变换矩阵与输出T.pretranslate(t_est);std::cout << T.matrix() << std::endl;return 0;
}/*** @brief 调用cv::ORB返回匹配的特征点* * @param[in] img_1 * @param[in] img_2 * @param[out] keypoints_1 * @param[out] keypoints_2 * @param[out] matches */
void find_feature_matches(const cv::Mat &img_1, const cv::Mat &img_2,std::vector<cv::KeyPoint> &keypoints_1,std::vector<cv::KeyPoint> &keypoints_2,std::vector<cv::DMatch> &matches)
{//-- 初始化cv::Mat descriptors_1, descriptors_2;// used in OpenCV3cv::Ptr<cv::FeatureDetector> detector = cv::ORB::create();cv::Ptr<cv::DescriptorExtractor> descriptor = cv::ORB::create();// use this if you are in OpenCV2// Ptr<FeatureDetector> detector = FeatureDetector::create ( "ORB" );// Ptr<DescriptorExtractor> descriptor = DescriptorExtractor::create ( "ORB" );cv::Ptr<cv::DescriptorMatcher> matcher = cv::DescriptorMatcher::create("BruteForce-Hamming");//-- 第一步:检测 Oriented FAST 角点位置detector->detect(img_1, keypoints_1);detector->detect(img_2, keypoints_2);//-- 第二步:根据角点位置计算 BRIEF 描述子descriptor->compute(img_1, keypoints_1, descriptors_1);descriptor->compute(img_2, keypoints_2, descriptors_2);//-- 第三步:对两幅图像中的BRIEF描述子进行匹配,使用 Hamming 距离std::vector<cv::DMatch> match;// BFMatcher matcher ( NORM_HAMMING );matcher->match(descriptors_1, descriptors_2, match);//-- 第四步:匹配点对筛选double min_dist = 10000, max_dist = 0;// 找出所有匹配之间的最小距离和最大距离, 即是最相似的和最不相似的两组点之间的距离for (int i = 0; i < descriptors_1.rows; i++){double dist = match[i].distance;if (dist < min_dist)min_dist = dist;if (dist > max_dist)max_dist = dist;}printf("-- Max dist : %f \n", max_dist);printf("-- Min dist : %f \n", min_dist);// 当描述子之间的距离大于两倍的最小距离时,即认为匹配有误.但有时候最小距离会非常小,设置一个经验值30作为下限.for (int i = 0; i < descriptors_1.rows; i++){if (match[i].distance <= std::max(2 * min_dist, 30.0)){matches.push_back(match[i]);}}
}cv::Point2d pixel2cam(const cv::Point2d &p, const cv::Mat &K)
{return cv::Point2d((p.x - K.at<double>(0, 2)) / K.at<double>(0, 0),(p.y - K.at<double>(1, 2)) / K.at<double>(1, 1));
}

CMakeLists.txt如下

cmake_minimum_required(VERSION 3.5)
project(ceres_icp)set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
set(CMAKE_CXX_FLAGS_DEBUG "$ENV{CXXFLAGS} -O0 -Wall -g -ggdb")
set(CMAKE_CXX_FLAGS_RELEASE "$ENV{CXXFLAGS} -O3 -Wall")
set(CMAKE_CXX_STANDARD 14)find_package(OpenCV 3 REQUIRED)
find_package(Ceres REQUIRED)include_directories(/usr/local/includeinclude
)link_directories(/usr/local/lib
)add_executable(ceres_icpsrc/ceres_icp.cpp
)target_link_libraries(ceres_icp${OpenCV_LIBRARIES}${CERES_LIBRARIES}
)

结果如下

-- Max dist : 95.000000
-- Min dist : 7.000000
Find number of matched point: 81
3d-3d pairs: 75
iter      cost      cost_change  |gradient|   |step|    tr_ratio  tr_radius  ls_iter  iter_time  total_time0  1.187529e+02    0.00e+00    1.49e+02   0.00e+00   0.00e+00  1.00e+04        0    3.80e-03    3.86e-031  3.468083e+01    8.41e+01    5.94e+01   1.29e+00   8.95e-01  1.98e+04        1    3.80e-03    7.68e-032  6.366072e+00    2.83e+01    3.48e+01   1.47e+00   1.06e+00  5.93e+04        1    3.82e-03    1.15e-023  2.387209e+00    3.98e+00    1.63e+01   7.92e-01   8.04e-01  7.66e+04        1    3.93e-03    1.55e-024  9.092359e-01    1.48e+00    3.68e-01   2.88e-01   1.00e+00  2.30e+05        1    3.83e-03    1.93e-025  9.076072e-01    1.63e-03    1.65e-02   1.80e-02   1.05e+00  6.89e+05        1    3.73e-03    2.31e-026  9.075968e-01    1.05e-05    2.11e-03   2.14e-03   1.13e+00  2.07e+06        1    3.95e-03    2.70e-02Solver Summary (v 2.0.0-eigen-(3.3.90)-lapack-suitesparse-(5.7.1)-cxsparse-(3.2.0)-eigensparse-no_openmp)Original                  Reduced
Parameter blocks                            1                        1
Parameters                                  6                        6
Residual blocks                            75                       75
Residuals                                 225                      225Minimizer                        TRUST_REGIONDense linear algebra library            EIGEN
Trust region strategy     LEVENBERG_MARQUARDTGiven                     Used
Linear solver                        DENSE_QR                 DENSE_QR
Threads                                     1                        1
Linear solver ordering              AUTOMATIC                        1Cost:
Initial                          1.187529e+02
Final                            9.075968e-01
Change                           1.178453e+02Minimizer iterations                        7
Successful steps                            7
Unsuccessful steps                          0Time (in seconds):
Preprocessor                         0.000067Residual only evaluation           0.000095 (7)Jacobian & residual evaluation     0.026609 (7)Linear solver                      0.000119 (7)
Minimizer                            0.027029Postprocessor                        0.000004
Total                                0.027100Termination:                      CONVERGENCE (Function tolerance reached. |cost_change|/cost: 1.878852e-07 <= 1.000000e-06)R_cvest=[0.9972083771125694, -0.0578448212458617, 0.0472168325022967;0.05830249021928781, 0.9982638507212928, -0.008372811793325411;-0.04665053323109484, 0.0111022969754419, 0.9988495716328478]
R_est=   0.997208  -0.0578448   0.04721680.0583025    0.998264 -0.00837281-0.0466505   0.0111023     0.99885
t_est=-0.139986
0.0568282
0.03693650.997208  -0.0578448   0.0472168   -0.1399860.0583025    0.998264 -0.00837281   0.0568282-0.0466505   0.0111023     0.99885   0.03693650           0           0           1

和用g2o结果差不多

欢迎交流

SLAM14讲第七讲习题10:Ceres实现ICP优化相关推荐

  1. 高博14讲--第七讲 视觉里程计-7.3 2D-2D:对极几何

    高博14讲--第七讲 视觉里程计-7.3 2D-2D:对极几何 基本问题 对极约束 对极约束推导过程 本质矩阵 八点法 八点法推导过程 本质矩阵$\ E$的SVD分解 单目SLAM的一些问题 尺度不确 ...

  2. 2022张宇考研基础30讲 第七讲 零点问题与微分不等式

    文章目录 第七讲 零点问题与微分不等式 零点问题 普通方法 罗尔定理 实系数奇次方程至少一个根 微分不等式 第七讲 零点问题与微分不等式 零点问题 普通方法 罗尔定理 导数方程降n阶,fx多n个根 实 ...

  3. 概率论与数理统计张宇9讲 第七讲 大数定律与中心极限定理

    目录 例题七 例7.3  设随机变量序列X1,X2,⋯,Xn,⋯X_1,X_2,\cdots,X_n,\cdotsX1​,X2​,⋯,Xn​,⋯相互独立,根据辛钦大数定律,当n→∞n\to\infty ...

  4. matlab第七讲,matlab第七讲教案

    matlab第七讲教案 西南科技大学本科生课程备课教案 计算机技术在安全工程中的应用--Matlab 入门及应用 授课教师:徐中慧 班 级: 专 业:安全技术及工程第七章 逻辑函数与控制结构 课型:新 ...

  5. python字典、列表、元祖使用场景_python学习第七讲,python中的数据类型,列表,元祖,字典,之元祖使用与介绍...

    python学习第七讲,python中的数据类型,列表,元祖,字典,之元祖使用与介绍 一丶元祖 1.元祖简介 元祖跟列表类似.只不过是有区别的. 如下: tuple(元祖英文) 跟列表类似, 元素不能 ...

  6. [概统]本科二年级 概率论与数理统计 第七讲 期望、方差与相关性

    [概统]本科二年级 概率论与数理统计 第七讲 期望.方差与相关性 期望及其性质 方差.协方差.相关性系数 两两独立.独立与相关性 虽然之前就分别介绍过离散型随机变量与连续型随机变量的期望与方差,这一讲 ...

  7. PE格式第七讲,重定位表

    PE格式第七讲,重定位表 作者:IBinary 出处:http://www.cnblogs.com/iBinary/ 版权所有,欢迎保留原文链接进行转载:) 一丶何为重定位(注意,不是重定位表格) 首 ...

  8. 秦小明 第七讲 资产定价模型,股票定价

    这套课程对于赚到钱的程序员如何让钱生钱,保持财富非常重要,也对于做互联网金融行业的程序员非常重要. 有兴趣听课程的可以联系我的公众号:湾区人工智能 回复:秦小明 秦小明 第一讲 宏观和微观经济 htt ...

  9. Js与Jq实战:第七讲:jQuery基础

    第七讲:jQuery基础 一.预习笔记 1.jQuery的简述 2.jQuery对象与JS对象 3.jQuery的基本选择器 4.jQuery层次选择器 5.jQuery基本过滤选择器 6.jQuer ...

最新文章

  1. QQ采用什么传输协议?
  2. 数学建模学习笔记——模糊综合评价模型(评价类,发放问卷一般不用)
  3. 论文阅读笔记三十三:Feature Pyramid Networks for Object Detection(FPN CVPR 2017)
  4. 博客园今天将排名计算错误了
  5. 3分钟练成SVN命令高手:SVN常用命令
  6. Python遍历列表里面序号和值的方法
  7. 洛谷 P2919 [USACO08NOV]守护农场Guarding the Farm
  8. “李宏毅老师对不起,我要去追这门美女老师的课了” ,台大陈蕴侬深度学习课程最新资料下载...
  9. c语言 k最近邻分类算法代码,实验二 K-近邻算法及应用
  10. C++ 多线程 atomic
  11. 做游戏,学编程(C语言) 12 炸弹人
  12. 关于数组指针的一道面试题
  13. Atitit 编程语言知识点tech tree v2 attilax大总结
  14. 51单片机开发第一步 keilC51 以及 proteus 的安装
  15. 云优CMS火车头数据采集教程-自动采集发布教程
  16. meshlab点云颜色偏暗
  17. Winform实现确认取消框
  18. Detect-and-Track: Efficient Pose Estimation in Videos(检测和追踪:视频中有效的姿态评估)论文解读
  19. C# 获取系统显示器分辨率大小(多屏显示器)
  20. 庐山石刻分布及实习感想

热门文章

  1. 组织或项目外部影响因素分析
  2. 【NLP】13 ERNIE应用在情绪分类NLP任务——ERNIE安装、中文BERT的使用
  3. FFmpeg[35] - ffmpeg 合并 m3u8 遇到报错:Invalid UE golomb code
  4. Vue之component 标签
  5. 可以恢复SD卡丢失的数据的工具推荐
  6. go语言html模板,go html模板的使用
  7. Python~Day5
  8. 简单易用的PDF转SVG程序
  9. Redmine 安装及运维
  10. 计算差分方程的收敛点_时间序列分析第一章 差分方程