7.2 实践:特征提取和匹配

一、需要使用库opencv

二、代码解读

1.关于Mat 的说明参见:http://www.opencv.org.cn/opencvdoc/2.3.2/html/doc/tutorials/core/mat%20-%20the%20basic%20image%20container/mat%20-%20the%20basic%20image%20container.html
mat 包含两部分:信息头和矩阵指针
2.opencv相关函数:
引用:https://blog.csdn.net/eternity1118_/article/details/51333364
3.代码及注释


feature_extraction.cpp:

#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;//keypoint是opencv里的数据类型
    Mat descriptors_1, descriptors_2;//描述子
    Ptr detector = ORB::create();//opencv检测器orb
    Ptr descriptor = ORB::create();//描述orb
    // 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 );

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

    Mat outimg1;
    drawKeypoints( img_1, keypoints_1, outimg1, Scalar::all(-1), DrawMatchesFlags::DEFAULT );//把图一的keypoint画出来
   imshow("ORB特征点",outimg1);

    //-- 第三步:对两幅图像中的BRIEF描述子进行匹配,使用 Hamming 距离
    vector matches;
    //BFMatcher matcher ( NORM_HAMMING );
    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;
    }

    // 仅供娱乐的写法
    min_dist = min_element( matches.begin(), matches.end(), [](const DMatch& m1, const DMatch& m2) {return m1.distancedistance;
    max_dist = max_element( matches.begin(), matches.end(), [](const DMatch& m1, const DMatch& m2) {return m1.distancedistance;

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

程序运行可获得三个图像窗口:


特征匹配

你可能感兴趣的:(7.2 实践:特征提取和匹配)