OpenCV4入门教程110:FLANN特征点匹配

索引地址:系列索引

FLANN库全称是Fast Library for Approximate Nearest Neighbors(快速最近邻逼进搜索库),是一个在高维空间快速搜索近邻的库,它是目前最完整的(近似)最近邻开源库。不但实现了一系列查找算法,还包含了一种自动选取最快算法的机制。

主要优势:实现了包含kd-tree等在内的搜索算法集合,并且可以根据数据集本身特点,自动选取最适合的算法来完成k近邻搜索任务(更加确切的说是高维特征向量的匹配任务),提供了c++、c、python、matlab的接口。

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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include "opencv2/core/core.hpp"
#include "opencv2/xfeatures2d.hpp"
#include "opencv2/features2d/features2d.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <iostream>
using namespace cv;
using namespace std;

int main(int argc, char **argv) {
//【1】载入源图片
Mat img_1 = imread("box.png", 1);
Mat img_2 = imread("box_in_scene.png", 1);
if (!img_1.data || !img_2.data) {
printf("读取图片image0错误~! \n");
return false;
}

//【2】利用SURF检测器检测的关键点
int minHessian = 300;
Ptr<xfeatures2d::SURF> detector= xfeatures2d::SURF::create(minHessian);
std::vector<KeyPoint> keypoints_1, keypoints_2;
detector->detect(img_1, keypoints_1);
detector->detect(img_2, keypoints_2);

//【3】计算描述符(特征向量)
Ptr<xfeatures2d::SURF> extractor=xfeatures2d::SURF::create();
Mat descriptors_1, descriptors_2;
extractor->compute(img_1, keypoints_1, descriptors_1);
extractor->compute(img_2, keypoints_2, descriptors_2);

//【4】采用FLANN算法匹配描述符向量
FlannBasedMatcher matcher;
std::vector<DMatch> matches;
matcher.match(descriptors_1, descriptors_2, matches);
double max_dist = 0;
double min_dist = 100;

//【5】快速计算关键点之间的最大和最小距离
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);

//【6】存下符合条件的匹配结果(即其距离小于2* min_dist的),使用radiusMatch同样可行
std::vector<DMatch> good_matches;
for (int i = 0; i < descriptors_1.rows; i++) {
if (matches[ i ].distance < 2 * min_dist) {
good_matches.push_back(matches[ i ]);
}
}

//【7】绘制出符合条件的匹配点
Mat img_matches;
drawMatches(img_1, keypoints_1, img_2, keypoints_2, good_matches, img_matches, Scalar::all(-1),
Scalar::all(-1), vector<char>(), DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS);

//【8】输出相关匹配点信息
for (int i = 0; i < good_matches.size(); i++) {
printf(">符合条件的匹配点 [%d] 特征点1: %d -- 特征点2: %d \n", i,
good_matches[ i ].queryIdx, good_matches[ i ].trainIdx);
}

//【9】显示效果图
imshow("result", img_matches);

//按任意键退出程序
waitKey(0);
return 0;
}

输出为

1
2
3
4
5
6
7
8
> 最大距离(Max dist) : 0.723325 
> 最小距离(Min dist) : 0.055338
>符合条件的匹配点 [0] 特征点1: 38 -- 特征点2: 116
>符合条件的匹配点 [1] 特征点1: 47 -- 特征点2: 77
>符合条件的匹配点 [2] 特征点1: 49 -- 特征点2: 77
>符合条件的匹配点 [3] 特征点1: 70 -- 特征点2: 310
>符合条件的匹配点 [4] 特征点1: 104 -- 特征点2: 356
>符合条件的匹配点 [5] 特征点1: 111 -- 特征点2: 335

效果为

flann


OpenCV4入门教程110:FLANN特征点匹配
https://feater.top/opencv/opencv-flann-feature-match/
作者
JackeyLea
发布于
2020年11月10日
许可协议