1 #include <opencv2/xfeatures2d/nonfree.hpp> 2 #include <opencv2/features2d/features2d.hpp> 3 #include <opencv2/highgui/highgui.hpp> 4 #include <opencv2/calib3d/calib3d.hpp> 5 #include <iostream> 6 7 8 using namespace cv; 9 using namespace std; 10 11 int main(int argc, char** argv) 12 { 13 Mat img1 = imread(argv[1]); 14 Mat img2 = imread(argv[2]); 15 vector<KeyPoint> keypoints_1, keypoints_2; 16 Mat descriptor_1, descriptor_2; 17 Ptr<Feature2D> sift = xfeatures2d::SIFT::create(0, 3, 0.04, 10); 18 19 sift->detectAndCompute(img1, noArray(), keypoints_1, descriptor_1); 20 sift->detectAndCompute(img2, noArray(), keypoints_2, descriptor_2); 21 cout<< keypoints_1.size()<<" "<<keypoints_2.size()<<endl; 22 Mat outimg1; 23 drawKeypoints(img1, keypoints_1, outimg1, Scalar::all(-1), DrawMatchesFlags::DEFAULT); 24 imshow("KeyPoint", outimg1); 25 26 vector<DMatch> matches; 27 vector<vector<DMatch>> knn_matches; 28 29 BFMatcher matcher(NORM_L2); 30 matcher.knnMatch(descriptor_1, descriptor_2, knn_matches, 2); 31 32 for (size_t r = 0; r < knn_matches.size(); ++r) 33 { 34 if (knn_matches[r][0].distance > 0.8*knn_matches[r][1].distance ) continue; 35 matches.push_back(knn_matches[r][0]); 36 } 37 38 Mat img_match; 39 Mat img_goodmatch; 40 drawMatches (img1, keypoints_1, img2, keypoints_2, matches, img_goodmatch); 41 imshow("good match", img_goodmatch); 42 waitKey(0); 43 44 return 0; 45 46 }
输入两张图像
提取sift特征点
使用knnmatch进行最近邻匹配