OpenCV4入门109:基于描述子匹配的已知对象定位

图像特征点检测、描述子生成以后,就可以通过OpenCV提供的描述子匹配算法,得到描述子直接的距离,距离越小的说明是匹配越好的,最终绘制位置即可。

测试代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
#include <vector>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;

int main(){
Mat box = imread("./data/box.png");
Mat box_in_scene = imread("./data/box_in_scene.png");
imshow("box",box);
imshow("box_in_scene",box_in_scene);

vector<KeyPoint> keypoints1,keypoints2;
Mat descriptors1,descriptors2;
//创建ORB特征检测器
Ptr<Feature2D> orb = ORB::create();
orb->detectAndCompute(box,Mat(),keypoints1,descriptors1,false);
orb->detectAndCompute(box_in_scene,Mat(),keypoints2,descriptors2,false);

//暴力匹配
BFMatcher matcher(NORM_HAMMING,true);
vector<DMatch> matches;
matcher.match(descriptors1,descriptors2,matches);

int maxdist = 0;
vector<DMatch> goodMtachs;

//发现匹配
// for(auto m:matches){
// maxdist = max(maxdist,m.distance);
// }
// for(auto m:matches){
// if(m.distance < 0.4 * maxdist){
// goodMtachs.push_back(m);
// }
// }

Mat result ;
drawMatches(box,keypoints1,box_in_scene,keypoints2,matches,result);
imshow("result", result);

waitKey(0);
return 0;
}

测试效果:

match