ceres求解PnP--SLAM 十四讲第七章课后题

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_rotcere_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);
}

其他部分都一样,不再叙述。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 156,265评论 4 359
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,274评论 1 288
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 106,087评论 0 237
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,479评论 0 203
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 51,782评论 3 285
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,218评论 1 207
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,594评论 2 309
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,316评论 0 194
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 33,955评论 1 237
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,274评论 2 240
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,803评论 1 255
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,177评论 2 250
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,732评论 3 229
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 25,953评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,687评论 0 192
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,263评论 2 267
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,189评论 2 258

推荐阅读更多精彩内容