Merge remote-tracking branch 'origin/2.4' into merge-2.4
[profile/ivi/opencv.git] / samples / cpp / descriptor_extractor_matcher.cpp
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"
6
7 #include <iostream>
8
9 using namespace cv;
10 using namespace std;
11
12 static void help(char** argv)
13 {
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"
16      << "\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"
21      << "\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"
24      << "\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"
28      << "\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;
33 }
34
35 #define DRAW_RICH_KEYPOINTS_MODE     0
36 #define DRAW_OUTLIERS_MODE           0
37
38 const string winName = "correspondences";
39
40 enum { NONE_FILTER = 0, CROSS_CHECK_FILTER = 1 };
41
42 static int getMatcherFilterType( const string& str )
43 {
44     if( str == "NoneFilter" )
45         return NONE_FILTER;
46     if( str == "CrossCheckFilter" )
47         return CROSS_CHECK_FILTER;
48     CV_Error(Error::StsBadArg, "Invalid filter name");
49     return -1;
50 }
51
52 static void simpleMatching( Ptr<DescriptorMatcher>& descriptorMatcher,
53                      const Mat& descriptors1, const Mat& descriptors2,
54                      vector<DMatch>& matches12 )
55 {
56     vector<DMatch> matches;
57     descriptorMatcher->match( descriptors1, descriptors2, matches12 );
58 }
59
60 static void crossCheckMatching( Ptr<DescriptorMatcher>& descriptorMatcher,
61                          const Mat& descriptors1, const Mat& descriptors2,
62                          vector<DMatch>& filteredMatches12, int knn=1 )
63 {
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++ )
69     {
70         bool findCrossCheck = false;
71         for( size_t fk = 0; fk < matches12[m].size(); fk++ )
72         {
73             DMatch forward = matches12[m][fk];
74
75             for( size_t bk = 0; bk < matches21[forward.trainIdx].size(); bk++ )
76             {
77                 DMatch backward = matches21[forward.trainIdx][bk];
78                 if( backward.trainIdx == forward.queryIdx )
79                 {
80                     filteredMatches12.push_back(forward);
81                     findCrossCheck = true;
82                     break;
83                 }
84             }
85             if( findCrossCheck ) break;
86         }
87     }
88 }
89
90 static void warpPerspectiveRand( const Mat& src, Mat& dst, Mat& H, RNG& rng )
91 {
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);
102
103     warpPerspective( src, dst, H, src.size() );
104 }
105
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 )
111 {
112     CV_Assert( !img1.empty() );
113     Mat H12;
114     if( isWarpPerspective )
115         warpPerspectiveRand(img1, img2, H12, rng );
116     else
117         CV_Assert( !img2.empty()/* && img2.cols==img1.cols && img2.rows==img1.rows*/ );
118
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;
123
124     if( !H12.empty() && eval )
125     {
126         cout << "< Evaluate feature detector..." << endl;
127         float repeatability;
128         int correspCount;
129         evaluateFeatureDetector( img1, img2, H12, &keypoints1, &keypoints2, repeatability, correspCount );
130         cout << "repeatability = " << repeatability << endl;
131         cout << "correspCount = " << correspCount << endl;
132         cout << ">" << endl;
133     }
134
135     cout << "< Computing descriptors for keypoints from second image..." << endl;
136     Mat descriptors2;
137     descriptorExtractor->compute( img2, keypoints2, descriptors2 );
138     cout << ">" << endl;
139
140     cout << "< Matching descriptors..." << endl;
141     vector<DMatch> filteredMatches;
142     switch( matcherFilter )
143     {
144     case CROSS_CHECK_FILTER :
145         crossCheckMatching( descriptorMatcher, descriptors1, descriptors2, filteredMatches, 1 );
146         break;
147     default :
148         simpleMatching( descriptorMatcher, descriptors1, descriptors2, filteredMatches );
149     }
150     cout << ">" << endl;
151
152     if( !H12.empty() && eval )
153     {
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 );
158
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 )
164         {
165             int nearest = getNearestPoint( curve, l_p );
166             if( nearest >= 0 )
167             {
168                 Point2f curPoint = curve[nearest];
169                 if( curPoint.x > firstPoint.x && curPoint.x < lastPoint.x && nearest != prevPointIndex )
170                 {
171                     cout << "1-precision = " << curPoint.x << "; recall = " << curPoint.y << endl;
172                     prevPointIndex = nearest;
173                 }
174             }
175         }
176         cout << "1-precision = " << lastPoint.x << "; recall = " << lastPoint.y << endl;
177         cout << ">" << endl;
178     }
179
180     vector<int> queryIdxs( filteredMatches.size() ), trainIdxs( filteredMatches.size() );
181     for( size_t i = 0; i < filteredMatches.size(); i++ )
182     {
183         queryIdxs[i] = filteredMatches[i].queryIdx;
184         trainIdxs[i] = filteredMatches[i].trainIdx;
185     }
186
187     if( !isWarpPerspective && ransacReprojThreshold >= 0 )
188     {
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 );
193         cout << ">" << endl;
194     }
195
196     Mat drawImg;
197     if( !H12.empty() ) // filter outliers
198     {
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);
203
204         double maxInlierDist = ransacReprojThreshold < 0 ? 3 : ransacReprojThreshold;
205         for( size_t i1 = 0; i1 < points1.size(); i1++ )
206         {
207             if( norm(points2[i1] - points1t.at<Point2f>((int)i1,0)) <= maxInlierDist ) // inlier
208                 matchesMask[i1] = 1;
209         }
210         // draw inliers
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
214 #endif
215                    );
216
217 #if DRAW_OUTLIERS_MODE
218         // draw outliers
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 );
223 #endif
224
225         cout << "Number of inliers: " << countNonZero(matchesMask) << endl;
226     }
227     else
228         drawMatches( img1, keypoints1, img2, keypoints2, filteredMatches, drawImg );
229
230     imshow( winName, drawImg );
231 }
232
233
234 int main(int argc, char** argv)
235 {
236     if( argc != 7 && argc != 8 )
237     {
238         help(argv);
239         return -1;
240     }
241
242     cv::initModule_nonfree();
243
244     bool isWarpPerspective = argc == 7;
245     double ransacReprojThreshold = -1;
246     if( !isWarpPerspective )
247         ransacReprojThreshold = atof(argv[7]);
248
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);
255     cout << ">" << endl;
256     if( !detector || !descriptorExtractor || !descriptorMatcher )
257     {
258         cout << "Can not create detector or descriptor exstractor or descriptor matcher of given types" << endl;
259         return -1;
260     }
261
262     cout << "< Reading the images..." << endl;
263     Mat img1 = imread( argv[5] ), img2;
264     if( !isWarpPerspective )
265         img2 = imread( argv[6] );
266     cout << ">" << endl;
267     if( img1.empty() || (!isWarpPerspective && img2.empty()) )
268     {
269         cout << "Can not read images" << endl;
270         return -1;
271     }
272
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;
277
278     cout << "< Computing descriptors for keypoints from first image..." << endl;
279     Mat descriptors1;
280     descriptorExtractor->compute( img1, keypoints1, descriptors1 );
281     cout << ">" << endl;
282
283     namedWindow(winName, 1);
284     RNG rng = theRNG();
285     doIteration( img1, img2, isWarpPerspective, keypoints1, descriptors1,
286                  detector, descriptorExtractor, descriptorMatcher, mactherFilterType, eval,
287                  ransacReprojThreshold, rng );
288     for(;;)
289     {
290         char c = (char)waitKey(0);
291         if( c == '\x1b' ) // esc
292         {
293             cout << "Exiting ..." << endl;
294             break;
295         }
296         else if( isWarpPerspective )
297         {
298             doIteration( img1, img2, isWarpPerspective, keypoints1, descriptors1,
299                          detector, descriptorExtractor, descriptorMatcher, mactherFilterType, eval,
300                          ransacReprojThreshold, rng );
301         }
302     }
303     return 0;
304 }