OpenCV4入门教程113:FLANN+SURF关键点描述与匹配

索引地址:系列索引

使用surf提取关键点,使用flann进行匹配。

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
#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/xfeatures2d/nonfree.hpp>
#include <opencv2/features2d/features2d.hpp>
using namespace cv;
using namespace std;

int main( )
{
//【1】载入图像、显示并转化为灰度图
Mat trainImage = imread("1.jpg"), trainImage_gray;
imshow("src",trainImage);
cvtColor(trainImage, trainImage_gray, COLOR_BGR2GRAY);

//【2】检测Surf关键点、提取训练图像描述符
vector<KeyPoint> train_keyPoint;
Mat trainDescriptor;
Ptr<xfeatures2d::SURF> surf = xfeatures2d::SURF::create(80);
surf->detectAndCompute(trainImage_gray, Mat(),train_keyPoint,trainDescriptor);

//【3】创建基于FLANN的描述符匹配对象
FlannBasedMatcher matcher;
vector<Mat> train_desc_collection(1, trainDescriptor);
matcher.add(train_desc_collection);
matcher.train();

//【4】创建视频对象、定义帧率
VideoCapture cap("tifa.mp4");
unsigned int frameCount = 0;//帧数

//【5】不断循环,直到q键被按下
while(char(waitKey(1)) != 'q')
{
//<1>参数设置
int64 time0 = getTickCount();
Mat testImage, testImage_gray;
cap >> testImage;//采集视频到testImage中
if(testImage.empty())
continue;

//<2>转化图像到灰度
cvtColor(testImage, testImage_gray, COLOR_BGR2GRAY);

//<3>检测S关键点、提取测试图像描述符
vector<KeyPoint> test_keyPoint;
Mat testDescriptor;
surf->detectAndCompute(testImage_gray, Mat(),test_keyPoint,testDescriptor);

//<4>匹配训练和测试描述符
vector<vector<DMatch> > matches;
matcher.knnMatch(testDescriptor, matches, 2);

// <5>根据劳氏算法(Lowe's algorithm),得到优秀的匹配点
vector<DMatch> goodMatches;
for(unsigned int i = 0; i < matches.size(); i++)
{
if(matches[i][0].distance < 0.6 * matches[i][1].distance)
goodMatches.push_back(matches[i][0]);
}

//<6>绘制匹配点并显示窗口
Mat dstImage;
drawMatches(testImage, test_keyPoint, trainImage, train_keyPoint, goodMatches, dstImage);
imshow("matched", dstImage);

//<7>输出帧率信息
cout << "当前帧率为:" << getTickFrequency() / (getTickCount() - time0) << endl;
}

return 0;
}

效果

sufr flann


OpenCV4入门教程113:FLANN+SURF关键点描述与匹配
https://feater.top/opencv/opencv-flann-surf-key-feature-detect-and-match/
作者
JackeyLea
发布于
2020年11月10日
许可协议