1 #include "opencv2/highgui/highgui.hpp"
2 #include "opencv2/calib3d/calib3d.hpp"
3 #include "opencv2/imgproc/imgproc.hpp"
4 #include "opencv2/features2d/features2d.hpp"
5 #include "opencv2/nonfree/nonfree.hpp"
12 static void help(char** argv)
14 cout << "\nThis program demonstrats keypoint finding and matching between 2 images using features2d framework.\n"
15 << " In one case, the 2nd image is synthesized by homography from the first, in the second case, there are 2 images\n"
17 << "Case1: second image is obtained from the first (given) image using random generated homography matrix\n"
18 << argv[0] << " [detectorType] [descriptorType] [matcherType] [matcherFilterType] [image] [evaluate(0 or 1)]\n"
19 << "Example of case1:\n"
20 << "./descriptor_extractor_matcher SURF SURF FlannBased NoneFilter cola.jpg 0\n"
22 << "Case2: both images are given. If ransacReprojThreshold>=0 then homography matrix are calculated\n"
23 << argv[0] << " [detectorType] [descriptorType] [matcherType] [matcherFilterType] [image1] [image2] [ransacReprojThreshold]\n"
25 << "Matches are filtered using homography matrix in case1 and case2 (if ransacReprojThreshold>=0)\n"
26 << "Example of case2:\n"
27 << "./descriptor_extractor_matcher SURF SURF BruteForce CrossCheckFilter cola1.jpg cola2.jpg 3\n"
29 << "Possible detectorType values: see in documentation on createFeatureDetector().\n"
30 << "Possible descriptorType values: see in documentation on createDescriptorExtractor().\n"
31 << "Possible matcherType values: see in documentation on createDescriptorMatcher().\n"
32 << "Possible matcherFilterType values: NoneFilter, CrossCheckFilter." << endl;
35 #define DRAW_RICH_KEYPOINTS_MODE 0
36 #define DRAW_OUTLIERS_MODE 0
38 const string winName = "correspondences";
40 enum { NONE_FILTER = 0, CROSS_CHECK_FILTER = 1 };
42 static int getMatcherFilterType( const string& str )
44 if( str == "NoneFilter" )
46 if( str == "CrossCheckFilter" )
47 return CROSS_CHECK_FILTER;
48 CV_Error(Error::StsBadArg, "Invalid filter name");
52 static void simpleMatching( Ptr<DescriptorMatcher>& descriptorMatcher,
53 const Mat& descriptors1, const Mat& descriptors2,
54 vector<DMatch>& matches12 )
56 vector<DMatch> matches;
57 descriptorMatcher->match( descriptors1, descriptors2, matches12 );
60 static void crossCheckMatching( Ptr<DescriptorMatcher>& descriptorMatcher,
61 const Mat& descriptors1, const Mat& descriptors2,
62 vector<DMatch>& filteredMatches12, int knn=1 )
64 filteredMatches12.clear();
65 vector<vector<DMatch> > matches12, matches21;
66 descriptorMatcher->knnMatch( descriptors1, descriptors2, matches12, knn );
67 descriptorMatcher->knnMatch( descriptors2, descriptors1, matches21, knn );
68 for( size_t m = 0; m < matches12.size(); m++ )
70 bool findCrossCheck = false;
71 for( size_t fk = 0; fk < matches12[m].size(); fk++ )
73 DMatch forward = matches12[m][fk];
75 for( size_t bk = 0; bk < matches21[forward.trainIdx].size(); bk++ )
77 DMatch backward = matches21[forward.trainIdx][bk];
78 if( backward.trainIdx == forward.queryIdx )
80 filteredMatches12.push_back(forward);
81 findCrossCheck = true;
85 if( findCrossCheck ) break;
90 static void warpPerspectiveRand( const Mat& src, Mat& dst, Mat& H, RNG& rng )
92 H.create(3, 3, CV_32FC1);
93 H.at<float>(0,0) = rng.uniform( 0.8f, 1.2f);
94 H.at<float>(0,1) = rng.uniform(-0.1f, 0.1f);
95 H.at<float>(0,2) = rng.uniform(-0.1f, 0.1f)*src.cols;
96 H.at<float>(1,0) = rng.uniform(-0.1f, 0.1f);
97 H.at<float>(1,1) = rng.uniform( 0.8f, 1.2f);
98 H.at<float>(1,2) = rng.uniform(-0.1f, 0.1f)*src.rows;
99 H.at<float>(2,0) = rng.uniform( -1e-4f, 1e-4f);
100 H.at<float>(2,1) = rng.uniform( -1e-4f, 1e-4f);
101 H.at<float>(2,2) = rng.uniform( 0.8f, 1.2f);
103 warpPerspective( src, dst, H, src.size() );
106 static void doIteration( const Mat& img1, Mat& img2, bool isWarpPerspective,
107 vector<KeyPoint>& keypoints1, const Mat& descriptors1,
108 Ptr<FeatureDetector>& detector, Ptr<DescriptorExtractor>& descriptorExtractor,
109 Ptr<DescriptorMatcher>& descriptorMatcher, int matcherFilter, bool eval,
110 double ransacReprojThreshold, RNG& rng )
112 CV_Assert( !img1.empty() );
114 if( isWarpPerspective )
115 warpPerspectiveRand(img1, img2, H12, rng );
117 CV_Assert( !img2.empty()/* && img2.cols==img1.cols && img2.rows==img1.rows*/ );
119 cout << endl << "< Extracting keypoints from second image..." << endl;
120 vector<KeyPoint> keypoints2;
121 detector->detect( img2, keypoints2 );
122 cout << keypoints2.size() << " points" << endl << ">" << endl;
124 if( !H12.empty() && eval )
126 cout << "< Evaluate feature detector..." << endl;
129 evaluateFeatureDetector( img1, img2, H12, &keypoints1, &keypoints2, repeatability, correspCount );
130 cout << "repeatability = " << repeatability << endl;
131 cout << "correspCount = " << correspCount << endl;
135 cout << "< Computing descriptors for keypoints from second image..." << endl;
137 descriptorExtractor->compute( img2, keypoints2, descriptors2 );
140 cout << "< Matching descriptors..." << endl;
141 vector<DMatch> filteredMatches;
142 switch( matcherFilter )
144 case CROSS_CHECK_FILTER :
145 crossCheckMatching( descriptorMatcher, descriptors1, descriptors2, filteredMatches, 1 );
148 simpleMatching( descriptorMatcher, descriptors1, descriptors2, filteredMatches );
152 if( !H12.empty() && eval )
154 cout << "< Evaluate descriptor matcher..." << endl;
155 vector<Point2f> curve;
156 Ptr<GenericDescriptorMatcher> gdm = makePtr<VectorDescriptorMatcher>( descriptorExtractor, descriptorMatcher );
157 evaluateGenericDescriptorMatcher( img1, img2, H12, keypoints1, keypoints2, 0, 0, curve, gdm );
159 Point2f firstPoint = *curve.begin();
160 Point2f lastPoint = *curve.rbegin();
161 int prevPointIndex = -1;
162 cout << "1-precision = " << firstPoint.x << "; recall = " << firstPoint.y << endl;
163 for( float l_p = 0; l_p <= 1 + FLT_EPSILON; l_p+=0.05f )
165 int nearest = getNearestPoint( curve, l_p );
168 Point2f curPoint = curve[nearest];
169 if( curPoint.x > firstPoint.x && curPoint.x < lastPoint.x && nearest != prevPointIndex )
171 cout << "1-precision = " << curPoint.x << "; recall = " << curPoint.y << endl;
172 prevPointIndex = nearest;
176 cout << "1-precision = " << lastPoint.x << "; recall = " << lastPoint.y << endl;
180 vector<int> queryIdxs( filteredMatches.size() ), trainIdxs( filteredMatches.size() );
181 for( size_t i = 0; i < filteredMatches.size(); i++ )
183 queryIdxs[i] = filteredMatches[i].queryIdx;
184 trainIdxs[i] = filteredMatches[i].trainIdx;
187 if( !isWarpPerspective && ransacReprojThreshold >= 0 )
189 cout << "< Computing homography (RANSAC)..." << endl;
190 vector<Point2f> points1; KeyPoint::convert(keypoints1, points1, queryIdxs);
191 vector<Point2f> points2; KeyPoint::convert(keypoints2, points2, trainIdxs);
192 H12 = findHomography( Mat(points1), Mat(points2), RANSAC, ransacReprojThreshold );
197 if( !H12.empty() ) // filter outliers
199 vector<char> matchesMask( filteredMatches.size(), 0 );
200 vector<Point2f> points1; KeyPoint::convert(keypoints1, points1, queryIdxs);
201 vector<Point2f> points2; KeyPoint::convert(keypoints2, points2, trainIdxs);
202 Mat points1t; perspectiveTransform(Mat(points1), points1t, H12);
204 double maxInlierDist = ransacReprojThreshold < 0 ? 3 : ransacReprojThreshold;
205 for( size_t i1 = 0; i1 < points1.size(); i1++ )
207 if( norm(points2[i1] - points1t.at<Point2f>((int)i1,0)) <= maxInlierDist ) // inlier
211 drawMatches( img1, keypoints1, img2, keypoints2, filteredMatches, drawImg, Scalar(0, 255, 0), Scalar(255, 0, 0), matchesMask
212 #if DRAW_RICH_KEYPOINTS_MODE
213 , DrawMatchesFlags::DRAW_RICH_KEYPOINTS
217 #if DRAW_OUTLIERS_MODE
219 for( size_t i1 = 0; i1 < matchesMask.size(); i1++ )
220 matchesMask[i1] = !matchesMask[i1];
221 drawMatches( img1, keypoints1, img2, keypoints2, filteredMatches, drawImg, Scalar(255, 0, 0), Scalar(0, 0, 255), matchesMask,
222 DrawMatchesFlags::DRAW_OVER_OUTIMG | DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS );
225 cout << "Number of inliers: " << countNonZero(matchesMask) << endl;
228 drawMatches( img1, keypoints1, img2, keypoints2, filteredMatches, drawImg );
230 imshow( winName, drawImg );
234 int main(int argc, char** argv)
236 if( argc != 7 && argc != 8 )
242 cv::initModule_nonfree();
244 bool isWarpPerspective = argc == 7;
245 double ransacReprojThreshold = -1;
246 if( !isWarpPerspective )
247 ransacReprojThreshold = atof(argv[7]);
249 cout << "< Creating detector, descriptor extractor and descriptor matcher ..." << endl;
250 Ptr<FeatureDetector> detector = FeatureDetector::create( argv[1] );
251 Ptr<DescriptorExtractor> descriptorExtractor = DescriptorExtractor::create( argv[2] );
252 Ptr<DescriptorMatcher> descriptorMatcher = DescriptorMatcher::create( argv[3] );
253 int mactherFilterType = getMatcherFilterType( argv[4] );
254 bool eval = !isWarpPerspective ? false : (atoi(argv[6]) == 0 ? false : true);
256 if( !detector || !descriptorExtractor || !descriptorMatcher )
258 cout << "Can not create detector or descriptor exstractor or descriptor matcher of given types" << endl;
262 cout << "< Reading the images..." << endl;
263 Mat img1 = imread( argv[5] ), img2;
264 if( !isWarpPerspective )
265 img2 = imread( argv[6] );
267 if( img1.empty() || (!isWarpPerspective && img2.empty()) )
269 cout << "Can not read images" << endl;
273 cout << endl << "< Extracting keypoints from first image..." << endl;
274 vector<KeyPoint> keypoints1;
275 detector->detect( img1, keypoints1 );
276 cout << keypoints1.size() << " points" << endl << ">" << endl;
278 cout << "< Computing descriptors for keypoints from first image..." << endl;
280 descriptorExtractor->compute( img1, keypoints1, descriptors1 );
283 namedWindow(winName, 1);
285 doIteration( img1, img2, isWarpPerspective, keypoints1, descriptors1,
286 detector, descriptorExtractor, descriptorMatcher, mactherFilterType, eval,
287 ransacReprojThreshold, rng );
290 char c = (char)waitKey(0);
291 if( c == '\x1b' ) // esc
293 cout << "Exiting ..." << endl;
296 else if( isWarpPerspective )
298 doIteration( img1, img2, isWarpPerspective, keypoints1, descriptors1,
299 detector, descriptorExtractor, descriptorMatcher, mactherFilterType, eval,
300 ransacReprojThreshold, rng );