RGB-D转换为点云图

目录

前言

一、图像数据的采集

二、相机的位姿估计

1.位姿估计的方法

2.RGB-D转点云拼接

总结


前言

       这两天要做一个RGB-D转点云并进行拼接的小实验,这里面包含了几个小步骤分别是图像数据的采集、位姿的估计、RGB-D转点云、点云的拼接。同样是在师兄的帮助下完成的,所以再感谢一下师兄。


一、图像数据的采集

       关于图像数据的采集,我使用的是Percipio 深度相机,该相机输出的图像有未去畸变的彩色图、去畸变的彩色图以及彩色到深度的转换图。

       第一次采集图像数据的时候,我使用的是例程中自动输出的深度图,但是在之后所拼接的点云会和实际的环境有着很大的差异,不可以使用。于是在师兄的帮助下,对代码进行了解读找到了正确的深度图并予以输出,可以从下文中看出得到的效果较之前要好很多,但还是有缺陷。

       由于实验室的灯光对数据的采集也有一定的影响,故我是在关闭灯光之后进行的数据的采集,其中深度图的效果要比开着灯光采集的效果好。

二、相机的位姿估计

1.位姿估计的方法

       相机的位姿估计的方法有很多种,包括PnP、EPnP等,这里就不做过多的解释了,我采用的是2dto2d的一种位姿估计的方式。以下是相关的代码,是在高博教授的《Slam十四讲》中摘取的。

       那么下面先介绍2D-2D:对极几何的原理

       从这两张图像中,我们可以得到若干对匹配好的特征点。现在我们利用一对已经匹配好的特征点以及该点二维图像上的点的对应关系,来求解出相机的运动也就是 R 和 t 。

       设两个相机的中心分别为O_{1}O_{2} 。现 I_{1} 中有特征点 p_{1} 对应着 I_{2} 中的 p_{2} 。其中 P 点为三维空间中的点,此时O_{1}O_{2}P 三点确定了一个平面,称为极平面。 e_{1}e_{2} 称为极点。O_{1}O_{2} 称为基线。l_{1}l_{2} 称为极线。空间点 P 的像素点可能会出现在射线 O_{1}P 上任意位置。如果P点的位置是未知的,那么 P 点在 I_{2} 当中可能出现的位置就会处在 l_{2} 上。而 p_{2} 的像素位置是可以预测的,我们通过特征点匹配,可以在 I_{2} 中找到同 I_{1}p_{1} 相匹配的像素点 p_{2}

       假设在第一帧图像的坐标系下 P 点的空间位置坐标为

P=\begin{bmatrix} X &Y &Z \end{bmatrix}^{T}

       则这两个像素点的位置分别为

s_{1}\cdot p_{1}=KP

s_{2}\cdot p_{2}=K(R\cdot P+t)

       有的时候,我们使用齐次坐标来表示像素点的位置。在使用齐次坐标的时候,一个向量将等于他自身乘上任意的非零常数。这通常用于表达一个投影关系。例如,s_{1}\cdot p_{1}p_{1}成投影关系,它们在齐次坐标的意义下是相等的。我们称这种相等关系为尺度意义下相等,记作:

s\cdot p\simeq p

       故上述两个投影关系可以写为

p_{1}\simeq KP

p_{2}\simeq K(R\cdot P+t)

       假设

x_{1}=K^{-1}\cdot p_{1}

x_{2}=K^{-1}\cdot p_{2}

       代入上式可得

x_{2}\simeq R\cdot x_{1}+t

       两侧同时左乘t^{\wedge }可得

t^{\wedge }x_{2}\simeq t^{\wedge }R\cdot x_{1}

       两侧同时左乘x_{2}^{T}可得

x_{2}^{T}t^{\wedge }R\cdot x_{1}=0

       将x_{1} x_{2},代入上式可得

p_{2}^{T}K^{-T}t^{\wedge }RK^{-1}p_{1}=0

       该式称为对极约束,其几何意义为 O_{1}O_{2}P三点共面。由于我们已知两像素点的位置坐标以及相机的内参矩阵,故可以求得相机的运动。以上就是该法的大概原理,对于R t的求解,我会在下一篇文章中加以阐述。

 

 

#include <iostream>
#include <Eigen/Core>
#include <Eigen/Geometry>
#include <opencv2/core/core.hpp>
#include <opencv2/features2d/features2d.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/calib3d/calib3d.hpp>
#include<opencv2/core/eigen.hpp>
#include<fstream>

// #include "extra.h" // 如果使用的是OpenCV2,则使用该行代码 
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 );
//函数声明,该函数的作用是寻找特征点并进行匹配
//输入 img_1 img_2

void pose_estimation_2d2d (
    std::vector<KeyPoint> keypoints_1,
    std::vector<KeyPoint> keypoints_2,
    std::vector< DMatch > matches,
    Mat& R, Mat& t );
//函数声明,该函数的作用是估计相机的位姿变化
//输入 keypoints_1 keypoints_2 matches
//输出 相机的旋转矩阵 R  相机的平移矩阵 t

// 像素坐标转相机归一化坐标
Point2d pixel2cam ( const Point2d& p, const Mat& K );

int main ( int argc, char** argv )
{
    if ( argc != 3 )
    {
        cout<<"usage: pose_estimation_2d2d img1 img2"<<endl;
        return 1;
    }
    //-- 读取图像
    Mat img_1 = imread ( "/home/joey/joinpcl/color/1.png", CV_LOAD_IMAGE_COLOR );//读取图像时的路径一定要设置对,否则可能会出现核心已转储的错误,这里我使用的是绝对路径。可以在终端中输入 pwd 查看绝对路径
    Mat img_2 = imread ( "/home/joey/joinpcl/color/6.png", CV_LOAD_IMAGE_COLOR );
    ofstream ofs;//读取图像时的路径一定要设置对,否则可能会出现核心已转储的错误,这里我使用的是绝对路径。可以在终端中输入 pwd 查看绝对路径

    vector<KeyPoint> keypoints_1, keypoints_2; //定义两个KeyPoint数据类型的变量
    vector<DMatch> matches; //定义DMatch数据类型的变量
    find_feature_matches ( img_1, img_2, keypoints_1, keypoints_2, matches ); //调用OpenCV函数,输入是 img_1,img_2 输出是 keypoints_1,keypoints_2,matches
    cout<<"一共找到了"<<matches.size() <<"组匹配点"<<endl;

    //-- 估计两张图像间运动
    Mat R,t; //OpenCV中的矩阵类型,并不能和Eigen中的矩阵类型兼容
    Eigen::Matrix3d R_E; //Eigen类型的旋转矩阵 R_E 3*3 double类型
    Eigen::Vector3d t_E; //Eigen类型的平移矩阵 t_E 3*1 double类型
    pose_estimation_2d2d ( keypoints_1, keypoints_2, matches, R, t ); //输入keypoints_1 keypoints_2 matches 输出 R t
    cv2eigen(R,R_E); //做一个矩阵类型的转换从OpenCV中转换到Eigen中的矩阵类型
    Eigen::Quaterniond q = Eigen::Quaterniond(R_E); //将旋转矩阵转换为四元数,因为pose.txt中要求存入四元数
    cout<<"quaterniond = "<<q.coeffs()<<endl; //四元数的结果输出,顺序为 qx qy qz qw
    ofs.open("/home/joey/joinpcl/pose1.txt",ios::out); //以写入的方式来打开pose1.txt文件
    ofs<<t<<" "<<q.coeffs()<<endl; //将平移矩阵以及四元数都存入到pose1.txt中去


    //-- 验证E=t^R*scale
    Mat t_x = ( Mat_<double> ( 3,3 ) <<
                0,                      -t.at<double> ( 2,0 ),     t.at<double> ( 1,0 ),
                t.at<double> ( 2,0 ),      0,                      -t.at<double> ( 0,0 ),
                -t.at<double> ( 1,0 ),     t.at<double> ( 0,0 ),      0 );

    cout<<"t^R="<<endl<<t_x*R<<endl;

    //-- 验证对极约束
    //因为我不需要验证对极约束,所以就把它注释掉了
    /*Mat K = ( Mat_<double> ( 3,3 ) << 520.9, 0, 325.1, 0, 521.0, 249.7, 0, 0, 1 );
    for ( DMatch m: matches )
    {
        Point2d pt1 = pixel2cam ( keypoints_1[ m.queryIdx ].pt, K );
        Mat y1 = ( Mat_<double> ( 3,1 ) << pt1.x, pt1.y, 1 );
        Point2d pt2 = pixel2cam ( keypoints_2[ m.trainIdx ].pt, K );
        Mat y2 = ( Mat_<double> ( 3,1 ) << pt2.x, pt2.y, 1 );
        Mat d = y2.t() * t_x * R * y1;
        cout << "epipolar constraint = " << d << endl;
    }*/
    return 0;
}

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; //初始化两个描述子矩阵变量
    // 我用的是opencv3所以可以用这两行代码
    Ptr<FeatureDetector> detector = ORB::create();
    Ptr<DescriptorExtractor> descriptor = ORB::create();
    // 如果安装的是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 )
           );
}


void pose_estimation_2d2d ( std::vector<KeyPoint> keypoints_1,
                            std::vector<KeyPoint> keypoints_2,
                            std::vector< DMatch > matches,
                            Mat& R, Mat& t )
{
    // 相机内参,TUM Freiburg2
    //Mat K = ( Mat_<double> ( 3,3 ) << 520.9, 0, 325.1, 0, 521.0, 249.7, 0, 0, 1 );
    //相机内参,我使用的相机和这个不一样,所以是自己标定的内参
    Mat K = ( Mat_<double> ( 3,3 ) << 886.2391758072229, 0, 639.496654129007, 0, 884.5569261594919, 338.8017291870644, 0, 0, 1 );

    //-- 把匹配点转换为vector<Point2f>的形式
    vector<Point2f> points1;
    vector<Point2f> points2;

    for ( int i = 0; i < ( int ) matches.size(); i++ )
    {
        points1.push_back ( keypoints_1[matches[i].queryIdx].pt );
        points2.push_back ( keypoints_2[matches[i].trainIdx].pt );
    }

    //-- 计算基础矩阵
    Mat fundamental_matrix;
    fundamental_matrix = findFundamentalMat ( points1, points2, CV_FM_8POINT );
    cout<<"fundamental_matrix is "<<endl<< fundamental_matrix<<endl;

    //-- 计算本质矩阵
    Point2d principal_point ( 325.1, 249.7 );	//相机光心, TUM dataset标定值
    double focal_length = 521;			//相机焦距, TUM dataset标定值
    Mat essential_matrix;
    essential_matrix = findEssentialMat ( points1, points2, focal_length, principal_point );
    cout<<"essential_matrix is "<<endl<< essential_matrix<<endl;

    //-- 计算单应矩阵
    Mat homography_matrix;
    homography_matrix = findHomography ( points1, points2, RANSAC, 3 );
    cout<<"homography_matrix is "<<endl<<homography_matrix<<endl;

    //-- 从本质矩阵中恢复旋转和平移信息.
    recoverPose ( essential_matrix, points1, points2, R, t, focal_length, principal_point );
    cout<<"R is "<<endl<<R<<endl;
    cout<<"t is "<<endl<<t<<endl;
    
}

 

2.RGB-D转点云拼接

代码如下(示例):

若该段代码中深度图转世界坐标部分看不懂的话可以下方评论我会及时反馈的。

#include <iostream>
#include <fstream>
using namespace std;
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <Eigen/Geometry> 
#include <boost/format.hpp>
#include <pcl/point_types.h> 
#include <pcl/io/pcd_io.h> 
#include <pcl/visualization/pcl_visualizer.h>

int main( int argc, char** argv )
{
    vector<cv::Mat> colorImgs, depthImgs;    // 彩色图和深度图
    vector<Eigen::Isometry3d, Eigen::aligned_allocator<Eigen::Isometry3d>> poses;         // 相机位姿
    
    ifstream fin("/home/joey/joinpcl/pose.txt");
    if (!fin)
    {
        cerr<<"请在有pose.txt的目录下运行此程序"<<endl;
        return 1;
    }
    
    for ( int i=0; i<5; i++ )
    {
        boost::format fmt( "/home/joey/joinpcl/%s/%d.%s" ); //图像文件格式
        colorImgs.push_back( cv::imread( (fmt%"color"%(i+1)%"png").str() ));
        depthImgs.push_back( cv::imread( (fmt%"depth"%(i+1)%"pgm").str(), -1 )); // -1表示读取原始图像不对图像作出修改
        
        double data[7] = {0};
        for ( auto& d:data )
            fin>>d;
        Eigen::Quaterniond q( data[6], data[3], data[4], data[5] );
        Eigen::Isometry3d T(q);
        T.pretranslate( Eigen::Vector3d( data[0], data[1], data[2] ));
        poses.push_back( T );
    }
    
    // 计算点云并拼接
    // 相机内参 
    double cx = 639.5;
    double cy = 338.8;
    double fx = 886.2;
    double fy = 884.6;
    double depthScale = 1000.0;
    
    cout<<"正在将图像转换为点云..."<<endl;
    
    // 定义点云使用的格式:这里用的是XYZRGB
    typedef pcl::PointXYZRGB PointT; 
    typedef pcl::PointCloud<PointT> PointCloud;
    
    // 新建一个点云
    PointCloud::Ptr pointCloud( new PointCloud ); 
    for ( int i=0; i<5; i++ )
    {
        cout<<"转换图像中: "<<i+1<<endl; 
        cv::Mat color = colorImgs[i]; 
        cv::Mat depth = depthImgs[i];
        Eigen::Isometry3d T = poses[i];
        for ( int v=0; v<color.rows; v++ )
            for ( int u=0; u<color.cols; u++ )
            {
                unsigned int d = depth.ptr<unsigned short> ( v )[u]; // 深度值
                if ( d==0 ) continue; // 为0表示没有测量到
                Eigen::Vector3d point; 
                point[2] = double(d)/depthScale; 
                point[0] = (u-cx)*point[2]/fx;
                point[1] = (v-cy)*point[2]/fy; 
                Eigen::Vector3d pointWorld = T*point;
                
                PointT p ;
                p.x = pointWorld[0];
                p.y = pointWorld[1];
                p.z = pointWorld[2];
                p.b = color.data[ v*color.step+u*color.channels() ];
                p.g = color.data[ v*color.step+u*color.channels()+1 ];
                p.r = color.data[ v*color.step+u*color.channels()+2 ];
                pointCloud->points.push_back( p );
            }
    }
    
    pointCloud->is_dense = false;
    cout<<"点云共有"<<pointCloud->size()<<"个点."<<endl;
    pcl::io::savePCDFileBinary("map.pcd", *pointCloud );
    return 0;
}

 

cmake_minimum_required( VERSION 2.8 )
project( vo1 )

set( CMAKE_BUILD_TYPE "Release" )
set( CMAKE_CXX_FLAGS "-std=c++11 -O3" )

# 添加cmake模块以使用g2o
list( APPEND CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/cmake_modules )

find_package(OpenCV REQUIRED)
include_directories(${OpenCV_INCLUDE_DIRS})
include_directories("/usr/include/eigen3/")

find_package(PCL REQUIRED COMPONENT common io)
include_directories(${PCL_INCLUDE_DIRS})
add_definitions(${PCL_DEFINITIONS})

find_package( OpenCV 3.1 REQUIRED )
# find_package( OpenCV REQUIRED ) # use this if in OpenCV2 
find_package( G2O REQUIRED )
find_package( CSparse REQUIRED )

include_directories( 
    ${OpenCV_INCLUDE_DIRS} 
    ${G2O_INCLUDE_DIRS}
    ${CSPARSE_INCLUDE_DIR}
    "/usr/include/eigen3/"
)

add_executable( pose_estimation_2d2d pose_estimation_2d2d.cpp )
target_link_libraries( pose_estimation_2d2d ${OpenCV_LIBS} )

add_executable(joinMap joinMap.cpp)
target_link_libraries(joinMap ${OpenCV_LIBS} ${PCL_LIBRARIES})

该文章参考高翔博士的《视觉SLAM十四讲》。


总结

如果有什么错误的地方希望大家指出!如果大家有什么疑问也可以留言,互相讨论共同进步!

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值