#include <opencv2/opencv.hpp>
#include <opencv2/xfeatures2d.hpp>
#include <iostream>
using namespace cv;
using namespace std;
using namespace cv::xfeatures2d;
int main(int argc, char** argv)
{
//1、载入两张图片
Mat img1 = imread("1.jpg", IMREAD_GRAYSCALE);
Mat img2 = imread("2.jpg", IMREAD_GRAYSCALE);
if (!img1.data || !img2.data) {
return -1;
}
imshow("image1", img1);
imshow("image2", img2);
//2、使用SURF算子检测关键点,
// 计算描述符(也就是特征向量)
int minHessian = 800;
Ptr<SURF> detector = SURF::create(minHessian);
vector<KeyPoint> keypoints_1;
vector<KeyPoint> keypoints_2;
Mat descriptor_1, descriptor_2;
detector->detectAndCompute(img1, Mat(), keypoints_1, descriptor_1);
detector->detectAndCompute(img2, Mat(), keypoints_2, descriptor_2);
//3、使用BruteForce进行匹配,实例化一个匹配器
BFMatcher matcher(NORM_L2);
vector<DMatch> matches;
matcher.match(descriptor_1, descriptor_2, matches);
//4、绘制从两个图像中匹配出的关键点
Mat matchesImg;
drawMatches(img1, keypoints_1, img2, keypoints_2, matches, matchesImg);
imshow("Descriptor Demo", matchesImg);
waitKey(0);
return 0;
}
或者
#include <stdio.h>
#include <iostream>
#include "opencv2/core.hpp"
#include "opencv2/features2d.hpp"
#include "opencv2/xfeatures2d.hpp"
#include "opencv2/highgui.hpp"
using namespace cv;
using namespace cv::xfeatures2d;
void readme();
/* @function main */
int main(int argc, char** argv)
{
//if (argc != 3)
//{
// readme(); return -1;
//}
Mat img_1 = imread("1.jpg", IMREAD_GRAYSCALE);
Mat img_2 = imread("2.jpg", IMREAD_GRAYSCALE);
if (!img_1.data || !img_2.data)
{
std::cout << " --(!) Error reading images " << std::endl; return -1;
}
//-- Step 1: Detect the keypoints using SURF Detector
int minHessian = 400;
Ptr<SURF> detector = SURF::create(minHessian);
std::vector<KeyPoint> keypoints_1, keypoints_2;
detector->detect(img_1, keypoints_1);
detector->detect(img_2, keypoints_2);
//-- Draw keypoints
Mat img_keypoints_1; Mat img_keypoints_2;
drawKeypoints(img_1, keypoints_1, img_keypoints_1, Scalar::all(-1), DrawMatchesFlags::DEFAULT);
drawKeypoints(img_2, keypoints_2, img_keypoints_2, Scalar::all(-1), DrawMatchesFlags::DEFAULT);
//-- Show detected (drawn) keypoints
imshow("Keypoints_1", img_keypoints_1);
imshow("Keypoints_2", img_keypoints_2);
//计算特征向量
Ptr<SURF>extractor = SURF::create();
Mat descriptors1, descriptors2;
extractor->compute(img_1, keypoints_1, descriptors1);
extractor->compute(img_2, keypoints_2, descriptors2);
//使用BruteForce进行匹配
Ptr<DescriptorMatcher> matcher = DescriptorMatcher::create("BruteForce");
std::vector< DMatch > matches;
matcher->match(descriptors1, descriptors2, matches);
//绘制直线连接关键点
Mat imgMatches;
drawMatches(img_1, keypoints_1, img_2, keypoints_2, matches, imgMatches);
imshow("match", imgMatches);
waitKey(0);
return 0;
}
/* @function readme */
void readme()
{
std::cout << " Usage: ./SURF_detector <img1> <img2>" << std::endl;
}