by jie 2018.8.10
尝试用ceres去求解BA。完成SLAM十四讲第七章课后题10。遇到不少问题,记录如下:
首先上代码:
#include <iostream>
#include <opencv2/core/core.hpp>
#include <ceres/ceres.h>
#include <chrono>
#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 "common/rotation.h"
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 );
// 像素坐标转相机归一化坐标
Point2d pixel2cam ( const Point2d& p, const Mat& K );
struct cost_function_define
{
cost_function_define(Point3f p1,Point2f p2):_p1(p1),_p2(p2){}
template<typename T>
bool operator()(const T* const cere_r,const T* const cere_t,T* residual)const
{
T p_1[3];
T p_2[3];
p_1[0]=T(_p1.x);
p_1[1]=T(_p1.y);
p_1[2]=T(_p1.z);
cout<<"point_3d: "<<p_1[0]<<" "<<p_1[1]<<" "<<p_1[2]<<endl;
AngleAxisRotatePoint(cere_r,p_1,p_2);
p_2[0]=p_2[0]+cere_t[0];
p_2[1]=p_2[1]+cere_t[1];
p_2[2]=p_2[2]+cere_t[2];
const T x=p_2[0]/p_2[2];
const T y=p_2[1]/p_2[2];
//三维点重投影计算的像素坐标
const T u=x*520.9+325.1;
const T v=y*521.0+249.7;
//观测的在图像坐标下的值
T u1=T(_p2.x);
T v1=T(_p2.y);
residual[0]=u-u1;
residual[1]=v-v1;
return true;
}
Point3f _p1;
Point2f _p2;
};
int main ( int argc, char** argv )
{
if ( argc != 5 )
{
cout<<"usage: pose_estimation_3d2d 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 );
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;
// 建立3D点
Mat d1 = imread ( argv[3], 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> pts_3d;
vector<Point2f> pts_2d;
for ( DMatch m:matches )
{
ushort d = d1.ptr<unsigned short> (int ( keypoints_1[m.queryIdx].pt.y )) [ int ( keypoints_1[m.queryIdx].pt.x ) ];
if ( d == 0 ) // bad depth
continue;
float dd = d/1000.0;
Point2d p1 = pixel2cam ( keypoints_1[m.queryIdx].pt, K );
pts_3d.push_back ( Point3f ( p1.x*dd, p1.y*dd, dd ) );
pts_2d.push_back ( keypoints_2[m.trainIdx].pt );
}
cout<<"3d-2d pairs: "<<pts_3d.size() <<endl;
Mat r, t;
solvePnP ( pts_3d, pts_2d, K, Mat(), r, t, false ); // 调用OpenCV 的 PnP 求解,可选择EPNP,DLS等方法
Mat R;
cv::Rodrigues ( r, R ); // r为旋转向量形式,用Rodrigues公式转换为矩阵
cout<<"----------------optional berore--------------------"<<endl;
cout<<"R="<<endl<<R<<endl;
cout<<"t="<<endl<<t<<endl;
cout<<"R_inv = "<<R.t() <<endl;
cout<<"t_inv = "<<-R.t() *t<<endl;
cout<<"calling bundle adjustment"<<endl;
//给rot,和tranf初值
double cere_rot[3],cere_tranf[3];
// cere_rot[0]=r.at<double>(0,0);
// cere_rot[1]=r.at<double>(1,0);
// cere_rot[2]=r.at<double>(2,0);
cere_rot[0]=0;
cere_rot[1]=1;
cere_rot[2]=2;
cere_tranf[0]=t.at<double>(0,0);
cere_tranf[1]=t.at<double>(1,0);
cere_tranf[2]=t.at<double>(2,0);
ceres::Problem problem;
for(int i=0;i<pts_3d.size();i++)
{
ceres::CostFunction* costfunction=new ceres::AutoDiffCostFunction<cost_function_define,2,3,3>(new cost_function_define(pts_3d[i],pts_2d[i]));
problem.AddResidualBlock(costfunction,NULL,cere_rot,cere_tranf);//注意,cere_rot不能为Mat类型
}
ceres::Solver::Options option;
option.linear_solver_type=ceres::DENSE_SCHUR;
//输出迭代信息到屏幕
option.minimizer_progress_to_stdout=true;
//显示优化信息
ceres::Solver::Summary summary;
//开始求解
ceres::Solve(option,&problem,&summary);
//显示优化信息
cout<<summary.BriefReport()<<endl;
cout<<"----------------optional after--------------------"<<endl;
Mat cam_3d = ( Mat_<double> ( 3,1 )<<cere_rot[0],cere_rot[1],cere_rot[2]);
Mat cam_9d;
cv::Rodrigues ( cam_3d, cam_9d ); // r为旋转向量形式,用Rodrigues公式转换为矩阵
cout<<"cam_9d:"<<endl<<cam_9d<<endl;
cout<<"cam_t:"<<cere_tranf[0]<<" "<<cere_tranf[1]<<" "<<cere_tranf[2]<<endl;
}
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 )
);
}
代码分析
首先前面代码是EPnP求解PnP。
ceres求解BA的话:
(1)构建cost fuction,即代价函数,也就是寻优的目标式。这个部分需要使用仿函数(functor)这一技巧来实现,做法是定义一个cost function的结构体,在结构体内重载()运算符。
struct cost_function_define
{
cost_function_define(Point3f p1,Point2f p2):_p1(p1),_p2(p2){}
template<typename T>
bool operator()(const T* const cere_r,const T* const cere_t,T* residual)const
{
T p_1[3];
T p_2[3];
p_1[0]=T(_p1.x);
p_1[1]=T(_p1.y);
p_1[2]=T(_p1.z);
cout<<"point_3d: "<<p_1[0]<<" "<<p_1[1]<<" "<<p_1[2]<<endl;
AngleAxisRotatePoint(cere_r,p_1,p_2);
p_2[0]=p_2[0]+cere_t[0];
p_2[1]=p_2[1]+cere_t[1];
p_2[2]=p_2[2]+cere_t[2];
const T x=p_2[0]/p_2[2];
const T y=p_2[1]/p_2[2];
//三维点重投影计算的像素坐标
const T u=x*520.9+325.1;
const T v=y*521.0+249.7;
//观测的在图像坐标下的值
T u1=T(_p2.x);
T v1=T(_p2.y);
residual[0]=u-u1;
residual[1]=v-v1;
return true;
}
Point3f _p1;
Point2f _p2;
};
这里目标函数是重投影误差,将第一帧观测到的3D点坐标先通过R,T变化到第二帧的坐标系下,然后用内参转到图像坐标系下,即重投影的坐标u,v。然后残差是第二帧观测到的该三维点的坐标u1,v1分别减去u,v。
注意:
-
这里的R不是旋转矩阵,也不是四元数表示的,而是用欧拉角表示的。
通过函数AngleAxisRotatePoint(cere_r,p_1,p_2)
可以对3D点进行旋转。相当于用旋转矩阵去左乘。 -
这里相机内参没有进行优化,而是直接写入,要一起优化可以稍加修改即可。这里优化的只有相机外参。
-
这里因为有模板,因此要将Point3f类型的_p1转为模板类型p_1,这样才可以在模板类型中的元素进行运算。否则会报错。
-
还有遇到了奇葩的问题,如果将观测变量
_p1
由类型Point3f
改为double*
,则优化结果完全错误。调试发现,传入的观测_p1
始终是第一次的值,后面没有再改变。猜测可能是数组必须按地址传递造成的。我将其类型改为自己写的struct类型则正确,初步验证了我的猜想,但是ceres内部怎么写的造成这样,还不太清楚。
(2)通过代价函数构建待求解的优化问题
ceres::Problem problem;
for(int i=0;i<pts_3d.size();i++)
{
ceres::CostFunction* costfunction=new ceres::AutoDiffCostFunction<cost_function_define,2,3,3>(new cost_function_define(pts_3d[i],pts_2d[i]));
problem.AddResidualBlock(costfunction,NULL,cere_rot,cere_tranf);//注意,cere_rot不能为Mat类型
}
-
这里可以看到,待优化的变量为
cere_rot
和cere_tranf
,都是3维的变量,残差是2维的,因此ceres::AutoDiffCostFunction<cost_function_define,2,3,3>
对应2,3,3. -
传入的观测是第一帧坐标系下的3D点坐标,和第二帧图像坐标系下的二维点。因为类型不统一,而又必须要用模板参数,因此这里统一类型,修改为
double*
。
(3)配置问题并求解
ceres::Solver::Options option;
option.linear_solver_type=ceres::DENSE_SCHUR;
//输出迭代信息到屏幕
option.minimizer_progress_to_stdout=true;
//显示优化信息
ceres::Solver::Summary summary;
//开始求解
ceres::Solve(option,&problem,&summary);
//显示优化信息
cout<<summary.BriefReport()<<endl;
- 注意
cere_rot
是旋转向量,因此可以Rodrigues公式转换为旋转矩阵
Mat cam_3d = ( Mat_<double> ( 3,1 )<<cere_rot[0],cere_rot[1],cere_rot[2]);
Mat cam_9d;
cv::Rodrigues ( cam_3d, cam_9d ); // r为旋转向量形式,用Rodrigues公式转换为矩阵
cout<<"----------optional after--------------"<<endl;
cout<<"cam_9d:"<<endl<<cam_9d<<endl;
输出结果和EPnP求解的基本一致。
Ceres Solver Report: Iterations: 15, Initial cost: 1.748561e+07, Final cost: 1.597795e+02, Termination: CONVERGENCE
----------------optional after--------------------
cam_9d:
[0.9979193163023975, -0.05138607093001037, 0.03894239161802245;
0.05033839242150249, 0.9983556583913398, 0.02742308528253861;
-0.04028752162859243, -0.02540572912495343, 0.9988650882519897]
cam_t:-0.627937 -0.0368194 0.304997
对代价函数进行封装后重写
上面的写法封装性不好,因此借鉴书上第10讲的写法重写。
(1)构建cost fuction
template<typename T>
inline bool CamProjectionWithDistortion(const T* cere_rot, const T* cere_tranf, const T* p_1, T* predictions){
// Rodrigues' formula
T p_2[3];
AngleAxisRotatePoint(cere_rot, p_1, p_2);
// camera[3,4,5] are the translation
p_2[0] = p_2[0]+cere_tranf[0];
p_2[1] = p_2[1]+ cere_tranf[1];
p_2[2] = p_2[2]+ cere_tranf[2];
T xp = p_2[0]/p_2[2];
T yp = p_2[1]/p_2[2];
T up=xp* 520.9+325.1;
T vp=yp*521.0 + 249.7;
predictions[0]=up;
predictions[1]=vp;
return true;
}
class SnavelyReprojectionError
{
public:
SnavelyReprojectionError(Point3f p1,Point2f p2):_p1(p1),_p2(p2){}
// SnavelyReprojectionError( double* p1, double* p2):_p1(p1),_p2(p2){}
template<typename T>
bool operator()(const T* const cere_rot,
const T* const cere_tranf,
T* residual)const{
T predictions[2];
//把double类型转为T类型
T p_1[3];
p_1[0]=T(_p1.x);
p_1[1]=T(_p1.y);
p_1[2]=T(_p1.z);
cout<<"point_3d: "<<p_1[0]<<" "<<p_1[1]<<" "<<p_1[2]<<endl;
CamProjectionWithDistortion(cere_rot, cere_tranf, p_1, predictions);
//观测的在图像坐标下的值
T u1=T(_p2.x);
T v1=T(_p2.y);
residual[0]=predictions[0]-u1;
residual[1]=predictions[1]-v1;
return true;
}
static ceres::CostFunction* Create( Point3f p1, Point2f p2){
return (new ceres::AutoDiffCostFunction<SnavelyReprojectionError,2,3,3>(
new SnavelyReprojectionError(p1,p2)));
}
private:
Point3f _p1;
Point2f _p2;
};
(2)构建问题求解
for (int i = 0; i < pts_3d.size(); i++)
{
ceres::CostFunction *cost_function;
cost_function = SnavelyReprojectionError::Create(pts_3d[i], pts_2d[i]);
problem.AddResidualBlock(cost_function, nullptr, cere_rot, cere_tranf);
}
其他部分都一样,不再叙述。
网友评论