ORB_slam 利用opencv提取特征点与匹配

 

步骤:

1、imread()读取图片;

2、特征点检测器:检测每个图片的 Oriented FAST 角点 detector->detect();

3、根据各图片角点位置计算 BRIEF 描述子descriptor->compute ( img_1, keypoints_1, descriptors_1 );

4、计算两幅图像的 Hamming 距离matcher->match ( descriptors_1, descriptors_2, matches );;

5、找出所有匹配之间的最小距离和最大距离,选出优化的匹配点;

6、drawMatches()绘制匹配结果。

#include 
#include 
#include 
#include 

using namespace std;
using namespace cv;

int main ( int argc, char** argv )
{
    if ( argc != 3 )
    {
        cout<<"usage: feature_extraction img1 img2"< keypoints_1, keypoints_2;
    Mat descriptors_1, descriptors_2;

//Ptr智能指针,只需要new定义申请,无需释放;
//FeatureDetector和DescriptorExtractor是一个纯虚类,这里用ORB特征点,也可以用SIFT,SURF等特征点
    Ptr detector = ORB::create(); 
    Ptr descriptor = ORB::create();

//opencv3中已经去除了SITF 和 SURF的算法
    // Ptr detector = FeatureDetector::create(detector_name);
    // Ptr descriptor = DescriptorExtractor::create(descriptor_name);
    Ptr matcher  = DescriptorMatcher::create ( "BruteForce-Hamming" );

    //-- 第一步:检测 Oriented FAST 角点位置
    detector->detect ( img_1,keypoints_1 );
    detector->detect ( img_2,keypoints_2 );

    Mat outimg1;
    drawKeypoints( img_1, keypoints_1, outimg1, Scalar::all(-1), DrawMatchesFlags::DEFAULT );
    imshow("ORB特征点",outimg1);


    //-- 第二步:根据角点位置计算 BRIEF 描述子
    descriptor->compute ( img_1, keypoints_1, descriptors_1 );
    descriptor->compute ( img_2, keypoints_2, descriptors_2 );

    //-- 第三步:对两幅图像中的BRIEF描述子进行匹配,使用 Hamming 距离
    vector matches;
    matcher->match ( descriptors_1, descriptors_2, matches );

    //-- 第四步:匹配点对筛选
    double min_dist=10000, max_dist=0;

    //找出所有匹配之间的最小距离和最大距离, 即是最相似的和最不相似的两组点之间的距离
    for ( int i = 0; i < descriptors_1.rows; i++ )
    {
        double dist = matches[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作为下限.
    std::vector< DMatch > good_matches;
    for ( int i = 0; i < descriptors_1.rows; i++ )
    {
        if ( matches[i].distance <= max ( 2*min_dist, 30.0 ) )
        {
            good_matches.push_back ( matches[i] );
        }
    }

    //-- 第五步:绘制匹配结果
    Mat img_match;
    Mat img_goodmatch;
    drawMatches ( img_1, keypoints_1, img_2, keypoints_2, matches, img_match );
    drawMatches ( img_1, keypoints_1, img_2, keypoints_2, good_matches, img_goodmatch );
    imshow ( "所有匹配点对", img_match );
    imshow ( "优化后匹配点对", img_goodmatch );
    waitKey(0);

    return 0;
}

借鉴高博《视觉十四讲》的代码分析。

你可能感兴趣的:(SLAM)