ICP(Iterative Closest Point)求解点云数据对的变换矩阵

误差模型

线性解SVD,非线性解BA

#include <iostream>

#include <opencv2/core/core.hpp>

#include <opencv2/features2d/features2d.hpp>

#include <opencv2/highgui/highgui.hpp>

#include <opencv2/calib3d/calib3d.hpp>

#include <Eigen/Core>

#include <Eigen/Geometry>

#include <Eigen/SVD>

#include <g2o/core/base_vertex.h>

#include <g2o/core/base_unary_edge.h>

#include <g2o/core/block_solver.h>

#include <g2o/core/optimization_algorithm_gauss_newton.h>

#include <g2o/solvers/eigen/linear_solver_eigen.h>

#include <g2o/types/sba/types_six_dof_expmap.h>

#include <chrono>

using namespace std;

using namespace cv;

void find_feature_matches ( const Mat& img_1, const Mat& img_2,

std::vector<KeyPoint>& keypoints_1,

std::vector<KeyPoint>& keypoints_2,

std::vector< DMatch >& matches )

{

//-- 初始化

Mat descriptors_1, descriptors_2;

// used in OpenCV3

Ptr<FeatureDetector> detector = ORB::create();

Ptr<DescriptorExtractor> descriptor = ORB::create();

// use this if you are in OpenCV2

// Ptr<FeatureDetector> detector = FeatureDetector::create ( "ORB" );

// Ptr<DescriptorExtractor> descriptor = DescriptorExtractor::create ( "ORB" );

Ptr<DescriptorMatcher> matcher  = 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 距离

vector<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 <= max ( 2*min_dist, 30.0 ) )

{

matches.push_back ( match[i] );

}

}

}

Point2d pixel2cam ( const Point2d& p, const Mat& K )

{

return 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 )

);

}

主函数

int main ( int argc, char** argv )

{

if ( argc != 5 )

{

cout<<"usage: pose_estimation_3d3d img1 img2 depth1 depth2"<<endl;

return 1;

}

   //-- 读取图像

Mat img_1 = imread ( argv[1], CV_LOAD_IMAGE_COLOR );

Mat img_2 = imread ( argv[2], CV_LOAD_IMAGE_COLOR );

   // 1. 找关键点和匹配关系

vector<KeyPoint> keypoints_1, keypoints_2;

vector<DMatch> matches;

find_feature_matches ( img_1, img_2, keypoints_1, keypoints_2, matches );

cout<<"一共找到了"<<matches.size() <<"组匹配点"<<endl;

   // 2. 建立两幅图的3D点

Mat depth1 = imread ( argv[3], CV_LOAD_IMAGE_UNCHANGED );       // 深度图为16位无符号数,单通道图像

Mat depth2 = imread ( argv[4], CV_LOAD_IMAGE_UNCHANGED );       // 深度图为16位无符号数,单通道图像

Mat K = ( Mat_<double> ( 3,3 ) << 520.9, 0, 325.1, 0, 521.0, 249.7, 0, 0, 1 );

vector<Point3f> pts1, pts2;

for ( 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 )   // bad depth

continue;

//poxel2cam()像素坐标P转到相机归一化坐标系x;   .pt转化为像素坐标

Point2d p1 = pixel2cam ( keypoints_1[m.queryIdx].pt, K );

Point2d p2 = pixel2cam ( keypoints_2[m.trainIdx].pt, K );

float dd1 = float ( d1 ) /5000.0;  //自定义的深度尺度,方便画图,无实际意义。

float dd2 = float ( d2 ) /5000.0;

 pts1.push_back ( Point3f ( p1.x*dd1, p1.y*dd1, dd1 ) );

        pts2.push_back ( Point3f ( p2.x*dd2, p2.y*dd2, dd2 ) );

}

cout<<"3d-3d pairs: "<<pts1.size() <<endl;

Mat R, t;

// 3. 位姿估计使用SVD

pose_estimation_3d3d ( pts1, pts2, R, t );

cout<<"ICP via SVD results: "<<endl;

cout<<"R = "<<R<<endl;

cout<<"t = "<<t<<endl;

cout<<"R_inv = "<<R.t() <<endl;

cout<<"t_inv = "<<-R.t() *t<<endl;

cout<<"calling bundle adjustment"<<endl;

// 4.位姿估计使用 BA非线性优化

  bundleAdjustment( pts1, pts2, R, t );

//5 验证 p1 = R*p2 + t

for ( int i=0; i<5; i++ )

{

cout<<"p1 = "<<pts1[i]<<endl;

cout<<"p2 = "<<pts2[i]<<endl;

cout<<"(R*p2+t) = "<<

R * (Mat_<double>(3,1)<<pts2[i].x, pts2[i].y, pts2[i].z) + t

<<endl;

cout<<endl;

}

}

/

SVD解决ICP问题

void pose_estimation_3d3d (

const vector<Point3f>& pts1,

const vector<Point3f>& pts2,

Mat& R, Mat& t

)

{

//1. 去质心坐标q1 q2

Point3f p1, p2;     // center of mass(Point3f三维坐标点)

int N = pts1.size();

for ( int i=0; i<N; i++ )

{

p1 += pts1[i];

p2 += pts2[i];

}

p1 = Point3f( Vec3f(p1) /  N);   //Vec3f指的是图像3通道

p2 = Point3f( Vec3f(p2) / N);

 // vector<Point3f>向量,向量的每个分量都是3D点

vector<Point3f>     q1 ( N ), q2 ( N ); // remove the center去质心后的点

for ( int i=0; i<N; i++ )

{

q1[i] = pts1[i] - p1;

q2[i] = pts2[i] - p2;

}

    // 2 计算W=sum(q1*q2^T)

Eigen::Matrix3d W = Eigen::Matrix3d::Zero();

for ( int i=0; i<N; i++ )

{

W += Eigen::Vector3d ( q1[i].x, q1[i].y, q1[i].z ) * Eigen::Vector3d ( q2[i].x, q2[i].y, q2[i].z ).transpose();

}

cout<<"W="<<W<<endl;

  // 3 SVD on W

Eigen::JacobiSVD<Eigen::Matrix3d> svd ( W, Eigen::ComputeFullU|Eigen::ComputeFullV );

Eigen::Matrix3d U = svd.matrixU();

Eigen::Matrix3d V = svd.matrixV();

if (U.determinant() * V.determinant() < 0)

{

for (int x = 0; x < 3; ++x)

{

U(x, 2) *= -1;

}

}

cout<<"U="<<U<<endl;

cout<<"V="<<V<<endl;

// 4. R=U*V^T

  Eigen::Matrix3d R_ = U* ( V.transpose() );

Eigen::Vector3d t_ = Eigen::Vector3d ( p1.x, p1.y, p1.z ) - R_ * Eigen::Vector3d ( p2.x, p2.y, p2.z );

 // convert to cv::Mat

R = ( Mat_<double> ( 3,3 ) <<

R_ ( 0,0 ), R_ ( 0,1 ), R_ ( 0,2 ),

R_ ( 1,0 ), R_ ( 1,1 ), R_ ( 1,2 ),

R_ ( 2,0 ), R_ ( 2,1 ), R_ ( 2,2 )

);

t = ( Mat_<double> ( 3,1 ) << t_ ( 0,0 ), t_ ( 1,0 ), t_ ( 2,0 ) );

}

///

BA解决ICP问题

自定义边EdgeProjectXYZRGBDPoseOnly类(3D-3D的边 ,g2o中无3d-3d的边。

class EdgeProjectXYZRGBDPoseOnly : public g2o::BaseUnaryEdge<3, Eigen::Vector3d, g2o::VertexSE3Expmap>

{

public:

EIGEN_MAKE_ALIGNED_OPERATOR_NEW;

EdgeProjectXYZRGBDPoseOnly( const Eigen::Vector3d& point ) : _point(point) {}

    virtual void computeError()

{

const g2o::VertexSE3Expmap* pose = static_cast<const g2o::VertexSE3Expmap*> ( _vertices[0] );

  // measurement is p, point is p'

_error = _measurement - pose->estimate().map( _point );

/**********************************************************************************************************/

注解:

Vector3D map(const Vector3D & xyz) const

{

return _r*xyz + _t;

}

}

传入一个3D点,返回r*p+t,很明显就是求变换后点的坐标。

在g2o中,用SE3Quat类型表示变换T,此类型中有个成员函数就是map(),作用为对一个3D点进行坐标变换,

/**********************************************************************************************************/

virtual void linearizeOplus()    //雅克比矩阵

{

g2o::VertexSE3Expmap* pose = static_cast<g2o::VertexSE3Expmap *>(_vertices[0]);

g2o::SE3Quat T(pose->estimate());

Eigen::Vector3d xyz_trans = T.map(_point);

double x = xyz_trans[0];

double y = xyz_trans[1];

double z = xyz_trans[2];

_jacobianOplusXi(0,0) = 0;

_jacobianOplusXi(0,1) = -z;

_jacobianOplusXi(0,2) = y;

_jacobianOplusXi(0,3) = -1;

_jacobianOplusXi(0,4) = 0;

_jacobianOplusXi(0,5) = 0;

_jacobianOplusXi(1,0) = z;

_jacobianOplusXi(1,1) = 0;

_jacobianOplusXi(1,2) = -x;

_jacobianOplusXi(1,3) = 0;

_jacobianOplusXi(1,4) = -1;

_jacobianOplusXi(1,5) = 0;

_jacobianOplusXi(2,0) = -y;

_jacobianOplusXi(2,1) = x;

_jacobianOplusXi(2,2) = 0;

_jacobianOplusXi(2,3) = 0;

_jacobianOplusXi(2,4) = 0;

_jacobianOplusXi(2,5) = -1;

}

bool read ( istream& in ) {}

bool write ( ostream& out ) const {}

protected:

Eigen::Vector3d _point;

};

//BA求解ICP

void bundleAdjustment (

const vector< Point3f >& pts1,

const vector< Point3f >& pts2,

Mat& R, Mat& t )

{

 // 初始化g2o

typedef g2o::BlockSolver< g2o::BlockSolverTraits<6,3> > Block;  // pose维度为 6, landmark 维度为 3

Block::LinearSolverType* linearSolver = new g2o::LinearSolverEigen<Block::PoseMatrixType>(); // 线性方程求解器

Block* solver_ptr = new Block( linearSolver );      // 矩阵块求解器

g2o::OptimizationAlgorithmGaussNewton* solver = new g2o::OptimizationAlgorithmGaussNewton( solver_ptr );

g2o::SparseOptimizer optimizer;

optimizer.setAlgorithm( solver );

    // vertex

g2o::VertexSE3Expmap* pose = new g2o::VertexSE3Expmap(); // camera pose

pose->setId(0);

pose->setEstimate( g2o::SE3Quat(

Eigen::Matrix3d::Identity(),

Eigen::Vector3d( 0,0,0 )

) );

optimizer.addVertex( pose );

    // edges

int index = 1;

vector<EdgeProjectXYZRGBDPoseOnly*> edges;

for ( size_t i=0; i<pts1.size(); i++ )

{

EdgeProjectXYZRGBDPoseOnly* edge = new EdgeProjectXYZRGBDPoseOnly(

Eigen::Vector3d(pts2[i].x, pts2[i].y, pts2[i].z) );

edge->setId( index );

edge->setVertex( 0, dynamic_cast<g2o::VertexSE3Expmap*> (pose) );

edge->setMeasurement( Eigen::Vector3d(

pts1[i].x, pts1[i].y, pts1[i].z) );

edge->setInformation( Eigen::Matrix3d::Identity()*1e4 );

optimizer.addEdge(edge);

index++;

edges.push_back(edge);

}

//执行优化

optimizer.setVerbose( true );

optimizer.initializeOptimization();

optimizer.optimize(10);

cout<<endl<<"after optimization:"<<endl;

cout<<"T="<<endl<<Eigen::Isometry3d( pose->estimate() ).matrix()<<endl;

}

结果

[ INFO:0] Initialize OpenCL runtime...
-- Max dist : 95.000000 
-- Min dist : 7.000000 
一共找到了81组匹配点
3d-3d pairs: 75
W=  11.8688 -0.717698   1.89486
 -1.88065   3.83391  -5.78219
  3.25846  -5.82734   9.65267
U=  0.592295  -0.805658 -0.0101195
 -0.418171  -0.318113   0.850845
  0.688709   0.499719   0.525319
V=   0.64736  -0.761401 -0.0345329
 -0.388765  -0.368829   0.844291
  0.655581   0.533135   0.534772
ICP via SVD results: 
R = [0.9972065647956201, 0.05834273442898391, -0.04663895869192625;
 -0.05787745545449197, 0.998260122172866, 0.01126626067193237;
 0.04721511705620757, -0.008535444848613793, 0.9988482762174666]
t = [0.1379879629890433;
 -0.06551699470729988;
 -0.02981649388290575]
R_inv = [0.9972065647956201, -0.05787745545449197, 0.04721511705620757;
 0.05834273442898391, 0.998260122172866, -0.008535444848613793;
 -0.04663895869192625, 0.01126626067193237, 0.9988482762174666]
t_inv = [-0.1399866702492459;
 0.05709791102272541;
 0.03695589996443214]
calling bundle adjustment
iteration= 0  chi2= 18157.747747  time= 5.0389e-05  cumTime= 5.0389e-05  edges= 75  schur= 0
iteration= 1  chi2= 18151.933202  time= 1.3988e-05  cumTime= 6.4377e-05  edges= 75  schur= 0
iteration= 2  chi2= 18151.932131  time= 1.3026e-05  cumTime= 7.7403e-05  edges= 75  schur= 0
iteration= 3  chi2= 18151.932130  time= 1.2161e-05  cumTime= 8.95641e-05  edges= 75  schur= 0
iteration= 4  chi2= 18151.932130  time= 1.1238e-05  cumTime= 0.000100802  edges= 75  schur= 0
iteration= 5  chi2= 18151.932130  time= 1.3357e-05  cumTime= 0.000114159  edges= 75  schur= 0
iteration= 6  chi2= 18151.932130  time= 1.1731e-05  cumTime= 0.00012589  edges= 75  schur= 0
iteration= 7  chi2= 18151.932130  time= 1.1751e-05  cumTime= 0.000137641  edges= 75  schur= 0
iteration= 8  chi2= 18151.932130  time= 1.2621e-05  cumTime= 0.000150262  edges= 75  schur= 0
iteration= 9  chi2= 18151.932130  time= 1.1748e-05  cumTime= 0.00016201  edges= 75  schur= 0
optimization costs time: 0.000471091 seconds.

after optimization:
T=
   0.997207   0.0583427   -0.046639    0.137988
 -0.0578775     0.99826   0.0112663   -0.065517
  0.0472151 -0.00853546    0.998848  -0.0298169
          0           0           0           1
p1 = [-0.0374123, -0.830816, 2.7448]
p2 = [-0.0111479, -0.746763, 2.7652]
(R*p2+t) = [-0.04566300488482969;
 -0.7791822151698653;
 2.738046267661636]

p1 = [-0.243698, -0.117719, 1.5848]
p2 = [-0.299118, -0.0975683, 1.6558]
(R*p2+t) = [-0.243212054430598;
 -0.1269486029625337;
 1.610786345002579]

p1 = [-0.627753, 0.160186, 1.3396]
p2 = [-0.709645, 0.159033, 1.4212]
(R*p2+t) = [-0.6266796777024644;
 0.1503229238263245;
 1.354883323538178]

p1 = [-0.323443, 0.104873, 1.4266]
p2 = [-0.399079, 0.12047, 1.4838]
(R*p2+t) = [-0.3221508525590339;
 0.09455772952719482;
 1.432403794814274]

p1 = [-0.627221, 0.101454, 1.3116]
p2 = [-0.709709, 0.100216, 1.3998]
(R*p2+t) = [-0.6291763602679332;
 0.09137127679150184;
 1.334006907588644]

六、3D-3D ICP问题线性SVD解法与非线性BA解法相关推荐

  1. ICP 问题之 SVD

    欢迎访问我的博客首页. ICP 问题之 SVD 1. SVD 求 ICP 1.1 构造最小二乘问题 1.2 求解最小二乘问题 1.3 求位姿 2. 例子 2.1 代码实现 2.2 实例分析 2.3 使 ...

  2. 按头安利 好看又实用的中望3D 3d模型素材看这里

    中望3D 3d模型类资源应该算是素材类网站中必不可少的资源类型了吧~今天给大家推荐超好用,免费质量高的素材噢,让你坐拥海量资源同时又不撞款! 接下来就给大家介绍一下我珍藏已久的网站:爱给网,我的工作灵 ...

  3. 用c语言求解n阶线性,用C语言求解N阶线性矩阵方程Ax=b的简单解法.docx

    您所在位置:网站首页 > 海量文档 &nbsp>&nbsp高等教育&nbsp>&nbsp专业基础教材 用C语言求解N阶线性矩阵方程Ax=b的简单解法. ...

  4. 决策树算法模型的归类与整理(ID3&C4.5&CART&线性二分类&非线性二分类)

    决策树算法模型的归类与整理(ID3&C4.5&CART&线性二分类&非线性二分类) 一. 总结摘要 决策树模型在监督学习中非常常见,可用于分类(二分类.多分类)和回归. ...

  5. python堆栈汉诺塔非递归_汉诺塔问题的递归解法和非递归解法(python语言实现)...

    汉诺塔问题的非递归解法(python语言类解法) #!/usr/bin/env python #coding:utf-8 import sys import time reload(sys) sys. ...

  6. 紧凑存储的杜利特尔分解法Doolittle(LU分解法)_解线性方程组的直接解法

    紧凑存储的杜利特尔分解法Doolittle(LU分解法)_解线性方程组的直接解法 标签:计算方法实验 /* 紧凑存储的杜利特尔分解法Doolittle:如果初始矩阵不要求保留的话,可以紧凑存储.因为每 ...

  7. Android OpenGLES2.0(十六)——3D模型贴图及光照处理(obj+mtl)

    转自:http://blog.csdn.net/junzia/article/details/58272305 在Android OpenGLES2.0(十四)--Obj格式3D模型加载中实现了Obj ...

  8. 第六章 3D地形搭建(上)

    Unity 提供了多种工具来创建环境特征,例如地形和植被.要在场景中添加地形 (Terrain) 游戏对象,请从菜单中选择 GameObject > 3D Object > Terrain ...

  9. 【TRIO-Basic从入门到精通教程六】3D仿真、同步控制的使用1

    很多朋友都对可视化控制好奇,问我如何使用TRIO 3D示波器.今天刚好有时间和大家一起讨论,由于笔者的实力有效,不能做到面面俱到,请勿怪罪! 这节课用大家感兴趣的SCARA机器人仿真做演示.废话少说, ...

最新文章

  1. wsl ubuntu拒绝访问_一起聊聊WSL的那些事儿(下)
  2. 线程池什么时候调用shutdown方法_ThreadPoolExecutor.shutdown()?
  3. Spring Caching集成Ehcache
  4. 【…感激2008,部署我的2009…】
  5. 程序员正在抛弃 Facebook
  6. python解释器调用_Python3.x那些事儿:[2]如何调用解释器-百度经验
  7. opera5.6安装完成
  8. 对涉密计算机检查内容,保密工作检查内容主要有哪些
  9. 国内搜索引擎技术现状 zZ
  10. NLP - ngram - N元语言模型 python 实现
  11. 数据库数据模型理解 概念数据模型 逻辑数据模型 物理数据模型区别和联系
  12. Sorry, you have been blocked !vultr 又被 openai 屏蔽了,只能换个 vps 了
  13. java 金融面试题目_面试题 - java金融 - 博客园
  14. android 修改aar包资源文件的最简单方法
  15. 被ddos攻击,附加IP有作用吗
  16. 智能云解析DNS健康监测是如何实现的?-中科三方
  17. pycharm的主菜单消失如何解决(“File-Edit-Navigate-View”等菜单丢失)
  18. 什么是西安80坐标系
  19. 什么是HEVC/H265?解密4K 8K视频核心编码HEVC(4K时代不能不懂的知识)
  20. 把MM照片变手绘卡通效果

热门文章

  1. 为Sublime Text 3的C++编译器(g++)添加C++11标准的方法
  2. pycharm+anaconda编译器运行程序时一直显示“ImportError: DLL load failed: 找不到指定的模块”的解决办法
  3. rz/sz命令参数解释
  4. source:读取文件 “/etc/profile” 时发生错误解决办法
  5. Spark Streaming和Flume集成指南V1.4.1
  6. Python练习:合格率的计算
  7. 串口上升时间标准_国家电网公司时钟同步标准.pdf
  8. 5 重启应用_iphone8黑屏怎么办 iphone8黑屏重启方法【详细介绍】
  9. unity贪吃蛇c 语言代码,unity实现简单贪吃蛇游戏
  10. html5复习分类,HTML5考试复习资料.doc