其具体原理可参考:这篇博客
#include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/features2d/features2d.hpp> #include <iostream> using namespace cv; using namespace std; int main(int argc, char** argv) { Mat img_1 = imread("./1.jpg"); Mat img_2 = imread("./2.jpg"); // -- Step 1: Detect the keypoints using STAR Detector std::vector<KeyPoint> keypoints_1,keypoints_2; ORB orb; orb.detect(img_1, keypoints_1); orb.detect(img_2, keypoints_2); // -- Stpe 2: Calculate descriptors (feature vectors) Mat descriptors_1, descriptors_2; orb.compute(img_1, keypoints_1, descriptors_1); orb.compute(img_2, keypoints_2, descriptors_2); //-- Step 3: Matching descriptor vectors with a brute force matcher BFMatcher matcher(NORM_HAMMING); std::vector<DMatch> matches; matcher.match(descriptors_1, descriptors_2, matches); //4.对匹配结果进行筛选(依据DMatch结构体中的float类型变量distance进行筛选) float minDistance = 100; float maxDistance = 0; for (int i = 0; i < matches.size(); i++) { if (matches[i].distance < minDistance) minDistance = matches[i].distance; if (matches[i].distance > maxDistance) maxDistance = matches[i].distance; } cout << "minDistance: " << minDistance << endl; cout << "maxDistance: " << maxDistance << endl; vector<DMatch> goodMatches; for (int i = 0; i < matches.size(); i++) { if (matches[i].distance < 2 * minDistance) { goodMatches.push_back(matches[i]); } } // -- dwaw matches Mat img_mathes; drawMatches(img_1, keypoints_1, img_2, keypoints_2, goodMatches, img_mathes); // -- show imshow("Mathces", img_mathes); waitKey(0); return 0; }
