在采用surf+knnmatch进行特征匹配的时候,参考了如下这篇博客的代码,
https://www.cnblogs.com/skyfsm/p/7401523.html
#include "highgui/highgui.hpp"
#include "opencv2/nonfree/nonfree.hpp"
#include "opencv2/legacy/legacy.hpp"
#include <iostream>
using namespace cv;
using namespace std;
int main()
{
Mat image01 = imread("g2.jpg", 1);
Mat image02 = imread("g4.jpg", 1);
imshow("p2", image01);
imshow("p1", image02);
//灰度图转换
Mat image1, image2;
cvtColor(image01, image1, CV_RGB2GRAY);
cvtColor(image02, image2, CV_RGB2GRAY);
//提取特征点
SurfFeatureDetector surfDetector(2000); // 海塞矩阵阈值,在这里调整精度,值越大点越少,越精准
vector<KeyPoint> keyPoint1, keyPoint2;
surfDetector.detect(image1, keyPoint1);
surfDetector.detect(image2, keyPoint2);
//特征点描述,为下边的特征点匹配做准备
SurfDescriptorExtractor SurfDescriptor;
Mat imageDesc1, imageDesc2;
SurfDescriptor.compute(image1, keyPoint1, imageDesc1);
SurfDescriptor.compute(image2, keyPoint2, imageDesc2);
FlannBasedMatcher matcher;
vector<vector<DMatch> > matchePoints;
vector<DMatch> GoodMatchePoints;
vector<Mat> train_desc(1, imageDesc1);
matcher.add(train_desc);
matcher.train();
matcher.knnMatch(imageDesc2, matchePoints, 2);
cout << "total match points: " << matchePoints.size() << endl;
// Lowe's algorithm,获取优秀匹配点
for (int i = 0; i < matchePoints.size(); i++)
{
if (matchePoints[i][0].distance < 0.6 * matchePoints[i][1].distance)
{
GoodMatchePoints.push_back(matchePoints[i][0]);
}
}
Mat first_match;
drawMatches(image02, keyPoint2, image01, keyPoint1, GoodMatchePoints, first_match);
imshow("first_match ", first_match);
waitKey();
return 0;
}
这个代码在主函数里运行着,是正常的,可以检测出特征点。于是我就尝试着把函数封装成类或者子函数。
#include "stdafx.h"
#include "highgui/highgui.hpp"
#include "opencv2/nonfree/nonfree.hpp"
#include "opencv2/legacy/legacy.hpp"
#include <opencv2/opencv.hpp>
#include <iostream>
#include <vector>
using namespace cv;
using namespace std;
Mat image01;
Mat image02;
Mat showImg1, showImg2;
Point p;
Rect select;
bool select_flag1 = false;
bool select_flag2 = false;
bool end_flag1;
bool end_flag2;
Mat ROI1, ROI2;
Point p1A, p2A, p1B, p2B;
vector<Point2f> KeyPoints;
vector<KeyPoint> keyPoint1, keyPoint2;
vector<vector<DMatch> > matchePoints;
vector<DMatch> GoodMatchePoints;
void on_mouse(int EVENT, int x, int y, int flags, void* userdata);
void A_on_Mouse(int event, int x, int y, int flags, void*param);
void B_on_Mouse(int event, int x, int y, int flags, void*param);
bool getfeaturepoints(Mat &ROI1, Mat &ROI2, Point p1A, Point p1B, vector<Point2f> &KeyPoints);
int main()
{
image01 = imread("1.jpg", 1); //右图
image02 = imread("2.jpg", 1);