asift.cpp 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. #include <opencv2/core.hpp>
  2. #include <opencv2/imgproc.hpp>
  3. #include <opencv2/features2d.hpp>
  4. #include <opencv2/highgui.hpp>
  5. #include <opencv2/calib3d.hpp>
  6. #include <iostream>
  7. #include <iomanip>
  8. using namespace std;
  9. using namespace cv;
  10. static void help(char** argv)
  11. {
  12. cout
  13. << "This is a sample usage of AffineFeature detector/extractor.\n"
  14. << "And this is a C++ version of samples/python/asift.py\n"
  15. << "Usage: " << argv[0] << "\n"
  16. << " [ --feature=<sift|orb|brisk> ] # Feature to use.\n"
  17. << " [ --flann ] # use Flann-based matcher instead of bruteforce.\n"
  18. << " [ --maxlines=<number(50 as default)> ] # The maximum number of lines in visualizing the matching result.\n"
  19. << " [ --image1=<image1(aero1.jpg as default)> ]\n"
  20. << " [ --image2=<image2(aero3.jpg as default)> ] # Path to images to compare."
  21. << endl;
  22. }
  23. static double timer()
  24. {
  25. return getTickCount() / getTickFrequency();
  26. }
  27. int main(int argc, char** argv)
  28. {
  29. vector<String> fileName;
  30. cv::CommandLineParser parser(argc, argv,
  31. "{help h ||}"
  32. "{feature|brisk|}"
  33. "{flann||}"
  34. "{maxlines|50|}"
  35. "{image1|aero1.jpg|}{image2|aero3.jpg|}");
  36. if (parser.has("help"))
  37. {
  38. help(argv);
  39. return 0;
  40. }
  41. string feature = parser.get<string>("feature");
  42. bool useFlann = parser.has("flann");
  43. int maxlines = parser.get<int>("maxlines");
  44. fileName.push_back(samples::findFile(parser.get<string>("image1")));
  45. fileName.push_back(samples::findFile(parser.get<string>("image2")));
  46. if (!parser.check())
  47. {
  48. parser.printErrors();
  49. cout << "See --help (or missing '=' between argument name and value?)" << endl;
  50. return 1;
  51. }
  52. Mat img1 = imread(fileName[0], IMREAD_GRAYSCALE);
  53. Mat img2 = imread(fileName[1], IMREAD_GRAYSCALE);
  54. if (img1.empty())
  55. {
  56. cerr << "Image " << fileName[0] << " is empty or cannot be found" << endl;
  57. return 1;
  58. }
  59. if (img2.empty())
  60. {
  61. cerr << "Image " << fileName[1] << " is empty or cannot be found" << endl;
  62. return 1;
  63. }
  64. Ptr<Feature2D> backend;
  65. Ptr<DescriptorMatcher> matcher;
  66. if (feature == "sift")
  67. {
  68. backend = SIFT::create();
  69. if (useFlann)
  70. matcher = DescriptorMatcher::create("FlannBased");
  71. else
  72. matcher = DescriptorMatcher::create("BruteForce");
  73. }
  74. else if (feature == "orb")
  75. {
  76. backend = ORB::create();
  77. if (useFlann)
  78. matcher = makePtr<FlannBasedMatcher>(makePtr<flann::LshIndexParams>(6, 12, 1));
  79. else
  80. matcher = DescriptorMatcher::create("BruteForce-Hamming");
  81. }
  82. else if (feature == "brisk")
  83. {
  84. backend = BRISK::create();
  85. if (useFlann)
  86. matcher = makePtr<FlannBasedMatcher>(makePtr<flann::LshIndexParams>(6, 12, 1));
  87. else
  88. matcher = DescriptorMatcher::create("BruteForce-Hamming");
  89. }
  90. else
  91. {
  92. cerr << feature << " is not supported. See --help" << endl;
  93. return 1;
  94. }
  95. cout << "extracting with " << feature << "..." << endl;
  96. Ptr<AffineFeature> ext = AffineFeature::create(backend);
  97. vector<KeyPoint> kp1, kp2;
  98. Mat desc1, desc2;
  99. ext->detectAndCompute(img1, Mat(), kp1, desc1);
  100. ext->detectAndCompute(img2, Mat(), kp2, desc2);
  101. cout << "img1 - " << kp1.size() << " features, "
  102. << "img2 - " << kp2.size() << " features"
  103. << endl;
  104. cout << "matching with " << (useFlann ? "flann" : "bruteforce") << "..." << endl;
  105. double start = timer();
  106. // match and draw
  107. vector< vector<DMatch> > rawMatches;
  108. vector<Point2f> p1, p2;
  109. vector<float> distances;
  110. matcher->knnMatch(desc1, desc2, rawMatches, 2);
  111. // filter_matches
  112. for (size_t i = 0; i < rawMatches.size(); i++)
  113. {
  114. const vector<DMatch>& m = rawMatches[i];
  115. if (m.size() == 2 && m[0].distance < m[1].distance * 0.75)
  116. {
  117. p1.push_back(kp1[m[0].queryIdx].pt);
  118. p2.push_back(kp2[m[0].trainIdx].pt);
  119. distances.push_back(m[0].distance);
  120. }
  121. }
  122. vector<uchar> status;
  123. vector< pair<Point2f, Point2f> > pointPairs;
  124. Mat H = findHomography(p1, p2, status, RANSAC);
  125. int inliers = 0;
  126. for (size_t i = 0; i < status.size(); i++)
  127. {
  128. if (status[i])
  129. {
  130. pointPairs.push_back(make_pair(p1[i], p2[i]));
  131. distances[inliers] = distances[i];
  132. // CV_Assert(inliers <= (int)i);
  133. inliers++;
  134. }
  135. }
  136. distances.resize(inliers);
  137. cout << "execution time: " << fixed << setprecision(2) << (timer()-start)*1000 << " ms" << endl;
  138. cout << inliers << " / " << status.size() << " inliers/matched" << endl;
  139. cout << "visualizing..." << endl;
  140. vector<int> indices(inliers);
  141. cv::sortIdx(distances, indices, SORT_EVERY_ROW+SORT_ASCENDING);
  142. // explore_match
  143. int h1 = img1.size().height;
  144. int w1 = img1.size().width;
  145. int h2 = img2.size().height;
  146. int w2 = img2.size().width;
  147. Mat vis = Mat::zeros(max(h1, h2), w1+w2, CV_8U);
  148. img1.copyTo(Mat(vis, Rect(0, 0, w1, h1)));
  149. img2.copyTo(Mat(vis, Rect(w1, 0, w2, h2)));
  150. cvtColor(vis, vis, COLOR_GRAY2BGR);
  151. vector<Point2f> corners(4);
  152. corners[0] = Point2f(0, 0);
  153. corners[1] = Point2f((float)w1, 0);
  154. corners[2] = Point2f((float)w1, (float)h1);
  155. corners[3] = Point2f(0, (float)h1);
  156. vector<Point2i> icorners;
  157. perspectiveTransform(corners, corners, H);
  158. transform(corners, corners, Matx23f(1,0,(float)w1,0,1,0));
  159. Mat(corners).convertTo(icorners, CV_32S);
  160. polylines(vis, icorners, true, Scalar(255,255,255));
  161. for (int i = 0; i < min(inliers, maxlines); i++)
  162. {
  163. int idx = indices[i];
  164. const Point2f& pi1 = pointPairs[idx].first;
  165. const Point2f& pi2 = pointPairs[idx].second;
  166. circle(vis, pi1, 2, Scalar(0,255,0), -1);
  167. circle(vis, pi2 + Point2f((float)w1,0), 2, Scalar(0,255,0), -1);
  168. line(vis, pi1, pi2 + Point2f((float)w1,0), Scalar(0,255,0));
  169. }
  170. if (inliers > maxlines)
  171. cout << "only " << maxlines << " inliers are visualized" << endl;
  172. imshow("affine find_obj", vis);
  173. // Mat vis2 = Mat::zeros(max(h1, h2), w1+w2, CV_8U);
  174. // Mat warp1;
  175. // warpPerspective(img1, warp1, H, Size(w1, h1));
  176. // warp1.copyTo(Mat(vis2, Rect(0, 0, w1, h1)));
  177. // img2.copyTo(Mat(vis2, Rect(w1, 0, w2, h2)));
  178. // imshow("warped", vis2);
  179. waitKey();
  180. cout << "done" << endl;
  181. return 0;
  182. }