SIFT算法要比SURF算法慢一点
#include<opencv2/core/core.hpp>
#include<opencv2/features2d/features2d.hpp>
#include<opencv2/highgui/highgui.hpp>
#include<opencv2/nonfree/features2d.hpp>
#include<opencv2/legacy/legacy.hpp>
#include<iostream>
using namespace std;
using namespace cv;
int main()
{
Mat trainImage = imread("1.jpg", 1);
Mat captureImage = imread("2.jpg", 1);
Mat trainImage_gray, captureImage_gray;
if (!trainImage.data || !captureImage.data)
{
cout << "读取图片错误,请确定图片是否存在" << endl;
return false;
}
imshow("原始图1", trainImage);
imshow("原始图2", captureImage);
//灰度化
cvtColor(trainImage,trainImage_gray,CV_BGR2GRAY);
cvtColor(captureImage, captureImage_gray, CV_BGR2GRAY);
//检测SIFT关键点、提取训练对象描述符
vector<KeyPoint> train_KP, test_KP;
SiftFeatureDetector feaDetector;
feaDetector.detect(trainImage_gray,train_KP);//检测关键点
feaDetector.detect(captureImage_gray, test_KP);
SiftDescriptorExtractor feaExtractor;
Mat trainDescription, testDescription;
feaExtractor.compute(trainImage_gray,train_KP,trainDescription);//描述子
feaExtractor.compute(captureImage_gray, test_KP, testDescription);
//进行基于描述符的暴力匹配
BFMatcher matcher;
vector<Mat> train_desc_collection(1, trainDescription);
matcher.add(train_desc_collection);
matcher.train();
//匹配训练和测试描述符
vector<vector<DMatch>> matches;
matcher.knnMatch(testDescription,matches,2);
//根据劳氏算法,得到优秀的匹配点
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]);
}
Mat dst;
drawMatches(captureImage,test_KP,trainImage,train_KP,goodMatches,dst);
imshow("匹配窗口",dst);
waitKey(0);
return 0;
}
效果图: