1 #include "opencv2/calib3d/calib3d.hpp"
2 #include "opencv2/features2d/features2d.hpp"
3 #include "opencv2/highgui/highgui.hpp"
4 #include "opencv2/imgproc/imgproc.hpp"
5 #include "opencv2/nonfree/nonfree.hpp"
14 printf("Use the SURF descriptor for matching keypoints between 2 images\n");
15 printf("Format: \n./generic_descriptor_match <image1> <image2> <algorithm> <XML params>\n");
16 printf("For example: ./generic_descriptor_match ../c/scene_l.bmp ../c/scene_r.bmp FERN fern_params.xml\n");
19 Mat DrawCorrespondences(const Mat& img1, const vector<KeyPoint>& features1, const Mat& img2,
20 const vector<KeyPoint>& features2, const vector<DMatch>& desc_idx);
22 int main(int argc, char** argv)
30 std::string img1_name = std::string(argv[1]);
31 std::string img2_name = std::string(argv[2]);
32 std::string alg_name = std::string(argv[3]);
33 std::string params_filename = std::string(argv[4]);
35 Ptr<GenericDescriptorMatcher> descriptorMatcher = GenericDescriptorMatcher::create(alg_name, params_filename);
36 if( !descriptorMatcher )
38 printf ("Cannot create descriptor\n");
42 //printf("Reading the images...\n");
43 Mat img1 = imread(img1_name, IMREAD_GRAYSCALE);
44 Mat img2 = imread(img2_name, IMREAD_GRAYSCALE);
46 // extract keypoints from the first image
47 SURF surf_extractor(5.0e3);
48 vector<KeyPoint> keypoints1;
50 // printf("Extracting keypoints\n");
51 surf_extractor(img1, Mat(), keypoints1);
53 printf("Extracted %d keypoints from the first image\n", (int)keypoints1.size());
55 vector<KeyPoint> keypoints2;
56 surf_extractor(img2, Mat(), keypoints2);
57 printf("Extracted %d keypoints from the second image\n", (int)keypoints2.size());
59 printf("Finding nearest neighbors... \n");
60 // find NN for each of keypoints2 in keypoints1
61 vector<DMatch> matches2to1;
62 descriptorMatcher->match( img2, keypoints2, img1, keypoints1, matches2to1 );
65 Mat img_corr = DrawCorrespondences(img1, keypoints1, img2, keypoints2, matches2to1);
67 imshow("correspondences", img_corr);
71 Mat DrawCorrespondences(const Mat& img1, const vector<KeyPoint>& features1, const Mat& img2,
72 const vector<KeyPoint>& features2, const vector<DMatch>& desc_idx)
74 Mat part, img_corr(Size(img1.cols + img2.cols, MAX(img1.rows, img2.rows)), CV_8UC3);
75 img_corr = Scalar::all(0);
76 part = img_corr(Rect(0, 0, img1.cols, img1.rows));
77 cvtColor(img1, part, COLOR_GRAY2RGB);
78 part = img_corr(Rect(img1.cols, 0, img2.cols, img2.rows));
79 cvtColor(img1, part, COLOR_GRAY2RGB);
81 for (size_t i = 0; i < features1.size(); i++)
83 circle(img_corr, features1[i].pt, 3, Scalar(0, 0, 255));
86 for (size_t i = 0; i < features2.size(); i++)
88 Point pt(cvRound(features2[i].pt.x + img1.cols), cvRound(features2[i].pt.y));
89 circle(img_corr, pt, 3, Scalar(0, 0, 255));
90 line(img_corr, features1[desc_idx[i].trainIdx].pt, pt, Scalar(0, 255, 0));