CLAHE Python bindings
[profile/ivi/opencv.git] / modules / nonfree / test / test_features2d.cpp
1 /*M///////////////////////////////////////////////////////////////////////////////////////
2 //
3 //  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
4 //
5 //  By downloading, copying, installing or using the software you agree to this license.
6 //  If you do not agree to this license, do not download, install,
7 //  copy or use the software.
8 //
9 //
10 //                        Intel License Agreement
11 //                For Open Source Computer Vision Library
12 //
13 // Copyright (C) 2000, Intel Corporation, all rights reserved.
14 // Third party copyrights are property of their respective owners.
15 //
16 // Redistribution and use in source and binary forms, with or without modification,
17 // are permitted provided that the following conditions are met:
18 //
19 //   * Redistribution's of source code must retain the above copyright notice,
20 //     this list of conditions and the following disclaimer.
21 //
22 //   * Redistribution's in binary form must reproduce the above copyright notice,
23 //     this list of conditions and the following disclaimer in the documentation
24 //     and/or other materials provided with the distribution.
25 //
26 //   * The name of Intel Corporation may not be used to endorse or promote products
27 //     derived from this software without specific prior written permission.
28 //
29 // This software is provided by the copyright holders and contributors "as is" and
30 // any express or implied warranties, including, but not limited to, the implied
31 // warranties of merchantability and fitness for a particular purpose are disclaimed.
32 // In no event shall the Intel Corporation or contributors be liable for any direct,
33 // indirect, incidental, special, exemplary, or consequential damages
34 // (including, but not limited to, procurement of substitute goods or services;
35 // loss of use, data, or profits; or business interruption) however caused
36 // and on any theory of liability, whether in contract, strict liability,
37 // or tort (including negligence or otherwise) arising in any way out of
38 // the use of this software, even if advised of the possibility of such damage.
39 //
40 //M*/
41
42 #include "test_precomp.hpp"
43 #include "opencv2/calib3d/calib3d.hpp"
44
45 using namespace std;
46 using namespace cv;
47
48 const string FEATURES2D_DIR = "features2d";
49 const string DETECTOR_DIR = FEATURES2D_DIR + "/feature_detectors";
50 const string DESCRIPTOR_DIR = FEATURES2D_DIR + "/descriptor_extractors";
51 const string IMAGE_FILENAME = "tsukuba.png";
52
53 /****************************************************************************************\
54 *            Regression tests for feature detectors comparing keypoints.                 *
55 \****************************************************************************************/
56
57 class CV_FeatureDetectorTest : public cvtest::BaseTest
58 {
59 public:
60     CV_FeatureDetectorTest( const string& _name, const Ptr<FeatureDetector>& _fdetector ) :
61         name(_name), fdetector(_fdetector) {}
62
63 protected:
64     bool isSimilarKeypoints( const KeyPoint& p1, const KeyPoint& p2 );
65     void compareKeypointSets( const vector<KeyPoint>& validKeypoints, const vector<KeyPoint>& calcKeypoints );
66
67     void emptyDataTest();
68     void regressionTest(); // TODO test of detect() with mask
69
70     virtual void run( int );
71
72     string name;
73     Ptr<FeatureDetector> fdetector;
74 };
75
76 void CV_FeatureDetectorTest::emptyDataTest()
77 {
78     // One image.
79     Mat image;
80     vector<KeyPoint> keypoints;
81     try
82     {
83         fdetector->detect( image, keypoints );
84     }
85     catch(...)
86     {
87         ts->printf( cvtest::TS::LOG, "detect() on empty image must not generate exception (1).\n" );
88         ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
89     }
90
91     if( !keypoints.empty() )
92     {
93         ts->printf( cvtest::TS::LOG, "detect() on empty image must return empty keypoints vector (1).\n" );
94         ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
95         return;
96     }
97
98     // Several images.
99     vector<Mat> images;
100     vector<vector<KeyPoint> > keypointCollection;
101     try
102     {
103         fdetector->detect( images, keypointCollection );
104     }
105     catch(...)
106     {
107         ts->printf( cvtest::TS::LOG, "detect() on empty image vector must not generate exception (2).\n" );
108         ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
109     }
110 }
111
112 bool CV_FeatureDetectorTest::isSimilarKeypoints( const KeyPoint& p1, const KeyPoint& p2 )
113 {
114     const float maxPtDif = 1.f;
115     const float maxSizeDif = 1.f;
116     const float maxAngleDif = 2.f;
117     const float maxResponseDif = 0.1f;
118
119     float dist = (float)norm( p1.pt - p2.pt );
120     return (dist < maxPtDif &&
121             fabs(p1.size - p2.size) < maxSizeDif &&
122             abs(p1.angle - p2.angle) < maxAngleDif &&
123             abs(p1.response - p2.response) < maxResponseDif &&
124             p1.octave == p2.octave &&
125             p1.class_id == p2.class_id );
126 }
127
128 void CV_FeatureDetectorTest::compareKeypointSets( const vector<KeyPoint>& validKeypoints, const vector<KeyPoint>& calcKeypoints )
129 {
130     const float maxCountRatioDif = 0.01f;
131
132     // Compare counts of validation and calculated keypoints.
133     float countRatio = (float)validKeypoints.size() / (float)calcKeypoints.size();
134     if( countRatio < 1 - maxCountRatioDif || countRatio > 1.f + maxCountRatioDif )
135     {
136         ts->printf( cvtest::TS::LOG, "Bad keypoints count ratio (validCount = %d, calcCount = %d).\n",
137                     validKeypoints.size(), calcKeypoints.size() );
138         ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
139         return;
140     }
141
142     int progress = 0, progressCount = (int)(validKeypoints.size() * calcKeypoints.size());
143     int badPointCount = 0, commonPointCount = max((int)validKeypoints.size(), (int)calcKeypoints.size());
144     for( size_t v = 0; v < validKeypoints.size(); v++ )
145     {
146         int nearestIdx = -1;
147         float minDist = std::numeric_limits<float>::max();
148
149         for( size_t c = 0; c < calcKeypoints.size(); c++ )
150         {
151             progress = update_progress( progress, (int)(v*calcKeypoints.size() + c), progressCount, 0 );
152             float curDist = (float)norm( calcKeypoints[c].pt - validKeypoints[v].pt );
153             if( curDist < minDist )
154             {
155                 minDist = curDist;
156                 nearestIdx = (int)c;
157             }
158         }
159
160         assert( minDist >= 0 );
161         if( !isSimilarKeypoints( validKeypoints[v], calcKeypoints[nearestIdx] ) )
162             badPointCount++;
163     }
164     ts->printf( cvtest::TS::LOG, "badPointCount = %d; validPointCount = %d; calcPointCount = %d\n",
165                 badPointCount, validKeypoints.size(), calcKeypoints.size() );
166     if( badPointCount > 0.9 * commonPointCount )
167     {
168         ts->printf( cvtest::TS::LOG, " - Bad accuracy!\n" );
169         ts->set_failed_test_info( cvtest::TS::FAIL_BAD_ACCURACY );
170         return;
171     }
172     ts->printf( cvtest::TS::LOG, " - OK\n" );
173 }
174
175 void CV_FeatureDetectorTest::regressionTest()
176 {
177     assert( !fdetector.empty() );
178     string imgFilename = string(ts->get_data_path()) + FEATURES2D_DIR + "/" + IMAGE_FILENAME;
179     string resFilename = string(ts->get_data_path()) + DETECTOR_DIR + "/" + string(name) + ".xml.gz";
180
181     // Read the test image.
182     Mat image = imread( imgFilename );
183     if( image.empty() )
184     {
185         ts->printf( cvtest::TS::LOG, "Image %s can not be read.\n", imgFilename.c_str() );
186         ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_TEST_DATA );
187         return;
188     }
189
190     FileStorage fs( resFilename, FileStorage::READ );
191
192     // Compute keypoints.
193     vector<KeyPoint> calcKeypoints;
194     fdetector->detect( image, calcKeypoints );
195
196     if( fs.isOpened() ) // Compare computed and valid keypoints.
197     {
198         // TODO compare saved feature detector params with current ones
199
200         // Read validation keypoints set.
201         vector<KeyPoint> validKeypoints;
202         read( fs["keypoints"], validKeypoints );
203         if( validKeypoints.empty() )
204         {
205             ts->printf( cvtest::TS::LOG, "Keypoints can not be read.\n" );
206             ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_TEST_DATA );
207             return;
208         }
209
210         compareKeypointSets( validKeypoints, calcKeypoints );
211     }
212     else // Write detector parameters and computed keypoints as validation data.
213     {
214         fs.open( resFilename, FileStorage::WRITE );
215         if( !fs.isOpened() )
216         {
217             ts->printf( cvtest::TS::LOG, "File %s can not be opened to write.\n", resFilename.c_str() );
218             ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_TEST_DATA );
219             return;
220         }
221         else
222         {
223             fs << "detector_params" << "{";
224             fdetector->write( fs );
225             fs << "}";
226
227             write( fs, "keypoints", calcKeypoints );
228         }
229     }
230 }
231
232 void CV_FeatureDetectorTest::run( int /*start_from*/ )
233 {
234     if( fdetector.empty() )
235     {
236         ts->printf( cvtest::TS::LOG, "Feature detector is empty.\n" );
237         ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_TEST_DATA );
238         return;
239     }
240
241     emptyDataTest();
242     regressionTest();
243
244     ts->set_failed_test_info( cvtest::TS::OK );
245 }
246
247 /****************************************************************************************\
248 *                     Regression tests for descriptor extractors.                        *
249 \****************************************************************************************/
250 static void writeMatInBin( const Mat& mat, const string& filename )
251 {
252     FILE* f = fopen( filename.c_str(), "wb");
253     if( f )
254     {
255         int type = mat.type();
256         fwrite( (void*)&mat.rows, sizeof(int), 1, f );
257         fwrite( (void*)&mat.cols, sizeof(int), 1, f );
258         fwrite( (void*)&type, sizeof(int), 1, f );
259         int dataSize = (int)(mat.step * mat.rows * mat.channels());
260         fwrite( (void*)&dataSize, sizeof(int), 1, f );
261         fwrite( (void*)mat.data, 1, dataSize, f );
262         fclose(f);
263     }
264 }
265
266 static Mat readMatFromBin( const string& filename )
267 {
268     FILE* f = fopen( filename.c_str(), "rb" );
269     if( f )
270     {
271         int rows, cols, type, dataSize;
272         size_t elements_read1 = fread( (void*)&rows, sizeof(int), 1, f );
273         size_t elements_read2 = fread( (void*)&cols, sizeof(int), 1, f );
274         size_t elements_read3 = fread( (void*)&type, sizeof(int), 1, f );
275         size_t elements_read4 = fread( (void*)&dataSize, sizeof(int), 1, f );
276         CV_Assert(elements_read1 == 1 && elements_read2 == 1 && elements_read3 == 1 && elements_read4 == 1);
277
278         uchar* data = (uchar*)cvAlloc(dataSize);
279         size_t elements_read = fread( (void*)data, 1, dataSize, f );
280         CV_Assert(elements_read == (size_t)(dataSize));
281         fclose(f);
282
283         return Mat( rows, cols, type, data );
284     }
285     return Mat();
286 }
287
288 template<class Distance>
289 class CV_DescriptorExtractorTest : public cvtest::BaseTest
290 {
291 public:
292     typedef typename Distance::ValueType ValueType;
293     typedef typename Distance::ResultType DistanceType;
294
295     CV_DescriptorExtractorTest( const string _name, DistanceType _maxDist, const Ptr<DescriptorExtractor>& _dextractor,
296                                 Distance d = Distance() ):
297             name(_name), maxDist(_maxDist), dextractor(_dextractor), distance(d) {}
298 protected:
299     virtual void createDescriptorExtractor() {}
300
301     void compareDescriptors( const Mat& validDescriptors, const Mat& calcDescriptors )
302     {
303         if( validDescriptors.size != calcDescriptors.size || validDescriptors.type() != calcDescriptors.type() )
304         {
305             ts->printf(cvtest::TS::LOG, "Valid and computed descriptors matrices must have the same size and type.\n");
306             ts->printf(cvtest::TS::LOG, "Valid size is (%d x %d) actual size is (%d x %d).\n", validDescriptors.rows, validDescriptors.cols, calcDescriptors.rows, calcDescriptors.cols);
307             ts->printf(cvtest::TS::LOG, "Valid type is %d  actual type is %d.\n", validDescriptors.type(), calcDescriptors.type());
308             ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_TEST_DATA );
309             return;
310         }
311
312         CV_Assert( DataType<ValueType>::type == validDescriptors.type() );
313
314         int dimension = validDescriptors.cols;
315         DistanceType curMaxDist = std::numeric_limits<DistanceType>::min();
316         for( int y = 0; y < validDescriptors.rows; y++ )
317         {
318             DistanceType dist = distance( validDescriptors.ptr<ValueType>(y), calcDescriptors.ptr<ValueType>(y), dimension );
319             if( dist > curMaxDist )
320                 curMaxDist = dist;
321         }
322
323         stringstream ss;
324         ss << "Max distance between valid and computed descriptors " << curMaxDist;
325         if( curMaxDist < maxDist )
326             ss << "." << endl;
327         else
328         {
329             ss << ">" << maxDist  << " - bad accuracy!"<< endl;
330             ts->set_failed_test_info( cvtest::TS::FAIL_BAD_ACCURACY );
331         }
332         ts->printf(cvtest::TS::LOG,  ss.str().c_str() );
333     }
334
335     void emptyDataTest()
336     {
337         assert( !dextractor.empty() );
338
339         // One image.
340         Mat image;
341         vector<KeyPoint> keypoints;
342         Mat descriptors;
343
344         try
345         {
346             dextractor->compute( image, keypoints, descriptors );
347         }
348         catch(...)
349         {
350             ts->printf( cvtest::TS::LOG, "compute() on empty image and empty keypoints must not generate exception (1).\n");
351             ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_TEST_DATA );
352         }
353
354         image.create( 50, 50, CV_8UC3 );
355         try
356         {
357             dextractor->compute( image, keypoints, descriptors );
358         }
359         catch(...)
360         {
361             ts->printf( cvtest::TS::LOG, "compute() on nonempty image and empty keypoints must not generate exception (1).\n");
362             ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_TEST_DATA );
363         }
364
365         // Several images.
366         vector<Mat> images;
367         vector<vector<KeyPoint> > keypointsCollection;
368         vector<Mat> descriptorsCollection;
369         try
370         {
371             dextractor->compute( images, keypointsCollection, descriptorsCollection );
372         }
373         catch(...)
374         {
375             ts->printf( cvtest::TS::LOG, "compute() on empty images and empty keypoints collection must not generate exception (2).\n");
376             ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_TEST_DATA );
377         }
378     }
379
380     void regressionTest()
381     {
382         assert( !dextractor.empty() );
383
384         // Read the test image.
385         string imgFilename =  string(ts->get_data_path()) + FEATURES2D_DIR + "/" + IMAGE_FILENAME;
386
387         Mat img = imread( imgFilename );
388         if( img.empty() )
389         {
390             ts->printf( cvtest::TS::LOG, "Image %s can not be read.\n", imgFilename.c_str() );
391             ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_TEST_DATA );
392             return;
393         }
394
395         vector<KeyPoint> keypoints;
396         FileStorage fs( string(ts->get_data_path()) + FEATURES2D_DIR + "/keypoints.xml.gz", FileStorage::READ );
397         if( fs.isOpened() )
398         {
399             read( fs.getFirstTopLevelNode(), keypoints );
400
401             Mat calcDescriptors;
402             double t = (double)getTickCount();
403             dextractor->compute( img, keypoints, calcDescriptors );
404             t = getTickCount() - t;
405             ts->printf(cvtest::TS::LOG, "\nAverage time of computing one descriptor = %g ms.\n", t/((double)cvGetTickFrequency()*1000.)/calcDescriptors.rows );
406
407             if( calcDescriptors.rows != (int)keypoints.size() )
408             {
409                 ts->printf( cvtest::TS::LOG, "Count of computed descriptors and keypoints count must be equal.\n" );
410                 ts->printf( cvtest::TS::LOG, "Count of keypoints is            %d.\n", (int)keypoints.size() );
411                 ts->printf( cvtest::TS::LOG, "Count of computed descriptors is %d.\n", calcDescriptors.rows );
412                 ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
413                 return;
414             }
415
416             if( calcDescriptors.cols != dextractor->descriptorSize() || calcDescriptors.type() != dextractor->descriptorType() )
417             {
418                 ts->printf( cvtest::TS::LOG, "Incorrect descriptor size or descriptor type.\n" );
419                 ts->printf( cvtest::TS::LOG, "Expected size is   %d.\n", dextractor->descriptorSize() );
420                 ts->printf( cvtest::TS::LOG, "Calculated size is %d.\n", calcDescriptors.cols );
421                 ts->printf( cvtest::TS::LOG, "Expected type is   %d.\n", dextractor->descriptorType() );
422                 ts->printf( cvtest::TS::LOG, "Calculated type is %d.\n", calcDescriptors.type() );
423                 ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
424                 return;
425             }
426
427             // TODO read and write descriptor extractor parameters and check them
428             Mat validDescriptors = readDescriptors();
429             if( !validDescriptors.empty() )
430                 compareDescriptors( validDescriptors, calcDescriptors );
431             else
432             {
433                 if( !writeDescriptors( calcDescriptors ) )
434                 {
435                     ts->printf( cvtest::TS::LOG, "Descriptors can not be written.\n" );
436                     ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_TEST_DATA );
437                     return;
438                 }
439             }
440         }
441         else
442         {
443             ts->printf( cvtest::TS::LOG, "Compute and write keypoints.\n" );
444             fs.open( string(ts->get_data_path()) + FEATURES2D_DIR + "/keypoints.xml.gz", FileStorage::WRITE );
445             if( fs.isOpened() )
446             {
447                 SurfFeatureDetector fd;
448                 fd.detect(img, keypoints);
449                 write( fs, "keypoints", keypoints );
450             }
451             else
452             {
453                 ts->printf(cvtest::TS::LOG, "File for writting keypoints can not be opened.\n");
454                 ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_TEST_DATA );
455                 return;
456             }
457         }
458     }
459
460     void run(int)
461     {
462         createDescriptorExtractor();
463         if( dextractor.empty() )
464         {
465             ts->printf(cvtest::TS::LOG, "Descriptor extractor is empty.\n");
466             ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_TEST_DATA );
467             return;
468         }
469
470         emptyDataTest();
471         regressionTest();
472
473         ts->set_failed_test_info( cvtest::TS::OK );
474     }
475
476     virtual Mat readDescriptors()
477     {
478         Mat res = readMatFromBin( string(ts->get_data_path()) + DESCRIPTOR_DIR + "/" + string(name) );
479         return res;
480     }
481
482     virtual bool writeDescriptors( Mat& descs )
483     {
484         writeMatInBin( descs,  string(ts->get_data_path()) + DESCRIPTOR_DIR + "/" + string(name) );
485         return true;
486     }
487
488     string name;
489     const DistanceType maxDist;
490     Ptr<DescriptorExtractor> dextractor;
491     Distance distance;
492
493 private:
494     CV_DescriptorExtractorTest& operator=(const CV_DescriptorExtractorTest&) { return *this; }
495 };
496
497 /*template<typename T, typename Distance>
498 class CV_CalonderDescriptorExtractorTest : public CV_DescriptorExtractorTest<Distance>
499 {
500 public:
501     CV_CalonderDescriptorExtractorTest( const char* testName, float _normDif, float _prevTime ) :
502             CV_DescriptorExtractorTest<Distance>( testName, _normDif, Ptr<DescriptorExtractor>(), _prevTime )
503     {}
504
505 protected:
506     virtual void createDescriptorExtractor()
507     {
508         CV_DescriptorExtractorTest<Distance>::dextractor =
509                 new CalonderDescriptorExtractor<T>( string(CV_DescriptorExtractorTest<Distance>::ts->get_data_path()) +
510                                                     FEATURES2D_DIR + "/calonder_classifier.rtc");
511     }
512 };*/
513
514 /****************************************************************************************\
515 *                       Algorithmic tests for descriptor matchers                        *
516 \****************************************************************************************/
517 class CV_DescriptorMatcherTest : public cvtest::BaseTest
518 {
519 public:
520     CV_DescriptorMatcherTest( const string& _name, const Ptr<DescriptorMatcher>& _dmatcher, float _badPart ) :
521         badPart(_badPart), name(_name), dmatcher(_dmatcher)
522         {}
523 protected:
524     static const int dim = 500;
525     static const int queryDescCount = 300; // must be even number because we split train data in some cases in two
526     static const int countFactor = 4; // do not change it
527     const float badPart;
528
529     virtual void run( int );
530     void generateData( Mat& query, Mat& train );
531
532     void emptyDataTest();
533     void matchTest( const Mat& query, const Mat& train );
534     void knnMatchTest( const Mat& query, const Mat& train );
535     void radiusMatchTest( const Mat& query, const Mat& train );
536
537     string name;
538     Ptr<DescriptorMatcher> dmatcher;
539
540 private:
541     CV_DescriptorMatcherTest& operator=(const CV_DescriptorMatcherTest&) { return *this; }
542 };
543
544 void CV_DescriptorMatcherTest::emptyDataTest()
545 {
546     assert( !dmatcher.empty() );
547     Mat queryDescriptors, trainDescriptors, mask;
548     vector<Mat> trainDescriptorCollection, masks;
549     vector<DMatch> matches;
550     vector<vector<DMatch> > vmatches;
551
552     try
553     {
554         dmatcher->match( queryDescriptors, trainDescriptors, matches, mask );
555     }
556     catch(...)
557     {
558         ts->printf( cvtest::TS::LOG, "match() on empty descriptors must not generate exception (1).\n" );
559         ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
560     }
561
562     try
563     {
564         dmatcher->knnMatch( queryDescriptors, trainDescriptors, vmatches, 2, mask );
565     }
566     catch(...)
567     {
568         ts->printf( cvtest::TS::LOG, "knnMatch() on empty descriptors must not generate exception (1).\n" );
569         ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
570     }
571
572     try
573     {
574         dmatcher->radiusMatch( queryDescriptors, trainDescriptors, vmatches, 10.f, mask );
575     }
576     catch(...)
577     {
578         ts->printf( cvtest::TS::LOG, "radiusMatch() on empty descriptors must not generate exception (1).\n" );
579         ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
580     }
581
582     try
583     {
584         dmatcher->add( trainDescriptorCollection );
585     }
586     catch(...)
587     {
588         ts->printf( cvtest::TS::LOG, "add() on empty descriptors must not generate exception.\n" );
589         ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
590     }
591
592     try
593     {
594         dmatcher->match( queryDescriptors, matches, masks );
595     }
596     catch(...)
597     {
598         ts->printf( cvtest::TS::LOG, "match() on empty descriptors must not generate exception (2).\n" );
599         ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
600     }
601
602     try
603     {
604         dmatcher->knnMatch( queryDescriptors, vmatches, 2, masks );
605     }
606     catch(...)
607     {
608         ts->printf( cvtest::TS::LOG, "knnMatch() on empty descriptors must not generate exception (2).\n" );
609         ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
610     }
611
612     try
613     {
614         dmatcher->radiusMatch( queryDescriptors, vmatches, 10.f, masks );
615     }
616     catch(...)
617     {
618         ts->printf( cvtest::TS::LOG, "radiusMatch() on empty descriptors must not generate exception (2).\n" );
619         ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
620     }
621
622 }
623
624 void CV_DescriptorMatcherTest::generateData( Mat& query, Mat& train )
625 {
626     RNG& rng = theRNG();
627
628     // Generate query descriptors randomly.
629     // Descriptor vector elements are integer values.
630     Mat buf( queryDescCount, dim, CV_32SC1 );
631     rng.fill( buf, RNG::UNIFORM, Scalar::all(0), Scalar(3) );
632     buf.convertTo( query, CV_32FC1 );
633
634     // Generate train decriptors as follows:
635     // copy each query descriptor to train set countFactor times
636     // and perturb some one element of the copied descriptors in
637     // in ascending order. General boundaries of the perturbation
638     // are (0.f, 1.f).
639     train.create( query.rows*countFactor, query.cols, CV_32FC1 );
640     float step = 1.f / countFactor;
641     for( int qIdx = 0; qIdx < query.rows; qIdx++ )
642     {
643         Mat queryDescriptor = query.row(qIdx);
644         for( int c = 0; c < countFactor; c++ )
645         {
646             int tIdx = qIdx * countFactor + c;
647             Mat trainDescriptor = train.row(tIdx);
648             queryDescriptor.copyTo( trainDescriptor );
649             int elem = rng(dim);
650             float diff = rng.uniform( step*c, step*(c+1) );
651             trainDescriptor.at<float>(0, elem) += diff;
652         }
653     }
654 }
655
656 void CV_DescriptorMatcherTest::matchTest( const Mat& query, const Mat& train )
657 {
658     dmatcher->clear();
659
660     // test const version of match()
661     {
662         vector<DMatch> matches;
663         dmatcher->match( query, train, matches );
664
665         if( (int)matches.size() != queryDescCount )
666         {
667             ts->printf(cvtest::TS::LOG, "Incorrect matches count while test match() function (1).\n");
668             ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
669         }
670         else
671         {
672             int badCount = 0;
673             for( size_t i = 0; i < matches.size(); i++ )
674             {
675                 DMatch match = matches[i];
676                 if( (match.queryIdx != (int)i) || (match.trainIdx != (int)i*countFactor) || (match.imgIdx != 0) )
677                     badCount++;
678             }
679             if( (float)badCount > (float)queryDescCount*badPart )
680             {
681                 ts->printf( cvtest::TS::LOG, "%f - too large bad matches part while test match() function (1).\n",
682                             (float)badCount/(float)queryDescCount );
683                 ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
684             }
685         }
686     }
687
688     // test version of match() with add()
689     {
690         vector<DMatch> matches;
691         // make add() twice to test such case
692         dmatcher->add( vector<Mat>(1,train.rowRange(0, train.rows/2)) );
693         dmatcher->add( vector<Mat>(1,train.rowRange(train.rows/2, train.rows)) );
694         // prepare masks (make first nearest match illegal)
695         vector<Mat> masks(2);
696         for(int mi = 0; mi < 2; mi++ )
697         {
698             masks[mi] = Mat(query.rows, train.rows/2, CV_8UC1, Scalar::all(1));
699             for( int di = 0; di < queryDescCount/2; di++ )
700                 masks[mi].col(di*countFactor).setTo(Scalar::all(0));
701         }
702
703         dmatcher->match( query, matches, masks );
704
705         if( (int)matches.size() != queryDescCount )
706         {
707             ts->printf(cvtest::TS::LOG, "Incorrect matches count while test match() function (2).\n");
708             ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
709         }
710         else
711         {
712             int badCount = 0;
713             for( size_t i = 0; i < matches.size(); i++ )
714             {
715                 DMatch match = matches[i];
716                 int shift = dmatcher->isMaskSupported() ? 1 : 0;
717                 {
718                     if( i < queryDescCount/2 )
719                     {
720                         if( (match.queryIdx != (int)i) || (match.trainIdx != (int)i*countFactor + shift) || (match.imgIdx != 0) )
721                             badCount++;
722                     }
723                     else
724                     {
725                         if( (match.queryIdx != (int)i) || (match.trainIdx != ((int)i-queryDescCount/2)*countFactor + shift) || (match.imgIdx != 1) )
726                             badCount++;
727                     }
728                 }
729             }
730             if( (float)badCount > (float)queryDescCount*badPart )
731             {
732                 ts->printf( cvtest::TS::LOG, "%f - too large bad matches part while test match() function (2).\n",
733                             (float)badCount/(float)queryDescCount );
734                 ts->set_failed_test_info( cvtest::TS::FAIL_BAD_ACCURACY );
735             }
736         }
737     }
738 }
739
740 void CV_DescriptorMatcherTest::knnMatchTest( const Mat& query, const Mat& train )
741 {
742     dmatcher->clear();
743
744     // test const version of knnMatch()
745     {
746         const int knn = 3;
747
748         vector<vector<DMatch> > matches;
749         dmatcher->knnMatch( query, train, matches, knn );
750
751         if( (int)matches.size() != queryDescCount )
752         {
753             ts->printf(cvtest::TS::LOG, "Incorrect matches count while test knnMatch() function (1).\n");
754             ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
755         }
756         else
757         {
758             int badCount = 0;
759             for( size_t i = 0; i < matches.size(); i++ )
760             {
761                 if( (int)matches[i].size() != knn )
762                     badCount++;
763                 else
764                 {
765                     int localBadCount = 0;
766                     for( int k = 0; k < knn; k++ )
767                     {
768                         DMatch match = matches[i][k];
769                         if( (match.queryIdx != (int)i) || (match.trainIdx != (int)i*countFactor+k) || (match.imgIdx != 0) )
770                             localBadCount++;
771                     }
772                     badCount += localBadCount > 0 ? 1 : 0;
773                 }
774             }
775             if( (float)badCount > (float)queryDescCount*badPart )
776             {
777                 ts->printf( cvtest::TS::LOG, "%f - too large bad matches part while test knnMatch() function (1).\n",
778                             (float)badCount/(float)queryDescCount );
779                 ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
780             }
781         }
782     }
783
784     // test version of knnMatch() with add()
785     {
786         const int knn = 2;
787         vector<vector<DMatch> > matches;
788         // make add() twice to test such case
789         dmatcher->add( vector<Mat>(1,train.rowRange(0, train.rows/2)) );
790         dmatcher->add( vector<Mat>(1,train.rowRange(train.rows/2, train.rows)) );
791         // prepare masks (make first nearest match illegal)
792         vector<Mat> masks(2);
793         for(int mi = 0; mi < 2; mi++ )
794         {
795             masks[mi] = Mat(query.rows, train.rows/2, CV_8UC1, Scalar::all(1));
796             for( int di = 0; di < queryDescCount/2; di++ )
797                 masks[mi].col(di*countFactor).setTo(Scalar::all(0));
798         }
799
800         dmatcher->knnMatch( query, matches, knn, masks );
801
802         if( (int)matches.size() != queryDescCount )
803         {
804             ts->printf(cvtest::TS::LOG, "Incorrect matches count while test knnMatch() function (2).\n");
805             ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
806         }
807         else
808         {
809             int badCount = 0;
810             int shift = dmatcher->isMaskSupported() ? 1 : 0;
811             for( size_t i = 0; i < matches.size(); i++ )
812             {
813                 if( (int)matches[i].size() != knn )
814                     badCount++;
815                 else
816                 {
817                     int localBadCount = 0;
818                     for( int k = 0; k < knn; k++ )
819                     {
820                         DMatch match = matches[i][k];
821                         {
822                             if( i < queryDescCount/2 )
823                             {
824                                 if( (match.queryIdx != (int)i) || (match.trainIdx != (int)i*countFactor + k + shift) ||
825                                     (match.imgIdx != 0) )
826                                     localBadCount++;
827                             }
828                             else
829                             {
830                                 if( (match.queryIdx != (int)i) || (match.trainIdx != ((int)i-queryDescCount/2)*countFactor + k + shift) ||
831                                     (match.imgIdx != 1) )
832                                     localBadCount++;
833                             }
834                         }
835                     }
836                     badCount += localBadCount > 0 ? 1 : 0;
837                 }
838             }
839             if( (float)badCount > (float)queryDescCount*badPart )
840             {
841                 ts->printf( cvtest::TS::LOG, "%f - too large bad matches part while test knnMatch() function (2).\n",
842                             (float)badCount/(float)queryDescCount );
843                 ts->set_failed_test_info( cvtest::TS::FAIL_BAD_ACCURACY );
844             }
845         }
846     }
847 }
848
849 void CV_DescriptorMatcherTest::radiusMatchTest( const Mat& query, const Mat& train )
850 {
851     dmatcher->clear();
852     // test const version of match()
853     {
854         const float radius = 1.f/countFactor;
855         vector<vector<DMatch> > matches;
856         dmatcher->radiusMatch( query, train, matches, radius );
857
858         if( (int)matches.size() != queryDescCount )
859         {
860             ts->printf(cvtest::TS::LOG, "Incorrect matches count while test radiusMatch() function (1).\n");
861             ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
862         }
863         else
864         {
865             int badCount = 0;
866             for( size_t i = 0; i < matches.size(); i++ )
867             {
868                 if( (int)matches[i].size() != 1 )
869                     badCount++;
870                 else
871                 {
872                     DMatch match = matches[i][0];
873                     if( (match.queryIdx != (int)i) || (match.trainIdx != (int)i*countFactor) || (match.imgIdx != 0) )
874                         badCount++;
875                 }
876             }
877             if( (float)badCount > (float)queryDescCount*badPart )
878             {
879                 ts->printf( cvtest::TS::LOG, "%f - too large bad matches part while test radiusMatch() function (1).\n",
880                             (float)badCount/(float)queryDescCount );
881                 ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
882             }
883         }
884     }
885
886     // test version of match() with add()
887     {
888         int n = 3;
889         const float radius = 1.f/countFactor * n;
890         vector<vector<DMatch> > matches;
891         // make add() twice to test such case
892         dmatcher->add( vector<Mat>(1,train.rowRange(0, train.rows/2)) );
893         dmatcher->add( vector<Mat>(1,train.rowRange(train.rows/2, train.rows)) );
894         // prepare masks (make first nearest match illegal)
895         vector<Mat> masks(2);
896         for(int mi = 0; mi < 2; mi++ )
897         {
898             masks[mi] = Mat(query.rows, train.rows/2, CV_8UC1, Scalar::all(1));
899             for( int di = 0; di < queryDescCount/2; di++ )
900                 masks[mi].col(di*countFactor).setTo(Scalar::all(0));
901         }
902
903         dmatcher->radiusMatch( query, matches, radius, masks );
904
905         //int curRes = cvtest::TS::OK;
906         if( (int)matches.size() != queryDescCount )
907         {
908             ts->printf(cvtest::TS::LOG, "Incorrect matches count while test radiusMatch() function (1).\n");
909             ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
910         }
911
912         int badCount = 0;
913         int shift = dmatcher->isMaskSupported() ? 1 : 0;
914         int needMatchCount = dmatcher->isMaskSupported() ? n-1 : n;
915         for( size_t i = 0; i < matches.size(); i++ )
916         {
917             if( (int)matches[i].size() != needMatchCount )
918                 badCount++;
919             else
920             {
921                 int localBadCount = 0;
922                 for( int k = 0; k < needMatchCount; k++ )
923                 {
924                     DMatch match = matches[i][k];
925                     {
926                         if( i < queryDescCount/2 )
927                         {
928                             if( (match.queryIdx != (int)i) || (match.trainIdx != (int)i*countFactor + k + shift) ||
929                                 (match.imgIdx != 0) )
930                                 localBadCount++;
931                         }
932                         else
933                         {
934                             if( (match.queryIdx != (int)i) || (match.trainIdx != ((int)i-queryDescCount/2)*countFactor + k + shift) ||
935                                 (match.imgIdx != 1) )
936                                 localBadCount++;
937                         }
938                     }
939                 }
940                 badCount += localBadCount > 0 ? 1 : 0;
941             }
942         }
943         if( (float)badCount > (float)queryDescCount*badPart )
944         {
945             ts->printf( cvtest::TS::LOG, "%f - too large bad matches part while test radiusMatch() function (2).\n",
946                         (float)badCount/(float)queryDescCount );
947             ts->set_failed_test_info( cvtest::TS::FAIL_BAD_ACCURACY );
948         }
949     }
950 }
951
952 void CV_DescriptorMatcherTest::run( int )
953 {
954     Mat query, train;
955     generateData( query, train );
956
957     matchTest( query, train );
958
959     knnMatchTest( query, train );
960
961     radiusMatchTest( query, train );
962 }
963
964 /****************************************************************************************\
965 *                                Tests registrations                                     *
966 \****************************************************************************************/
967
968 /*
969  * Detectors
970  */
971
972
973 TEST( Features2d_Detector_SIFT, regression )
974 {
975     CV_FeatureDetectorTest test( "detector-sift", FeatureDetector::create("SIFT") );
976     test.safe_run();
977 }
978
979 TEST( Features2d_Detector_SURF, regression )
980 {
981     CV_FeatureDetectorTest test( "detector-surf", FeatureDetector::create("SURF") );
982     test.safe_run();
983 }
984
985 /*
986  * Descriptors
987  */
988 TEST( Features2d_DescriptorExtractor_SIFT, regression )
989 {
990     CV_DescriptorExtractorTest<L2<float> > test( "descriptor-sift", 0.03f,
991                                                   DescriptorExtractor::create("SIFT") );
992     test.safe_run();
993 }
994
995 TEST( Features2d_DescriptorExtractor_SURF, regression )
996 {
997     CV_DescriptorExtractorTest<L2<float> > test( "descriptor-surf",  0.05f,
998                                                  DescriptorExtractor::create("SURF") );
999     test.safe_run();
1000 }
1001
1002 TEST( Features2d_DescriptorExtractor_OpponentSIFT, regression )
1003 {
1004     CV_DescriptorExtractorTest<L2<float> > test( "descriptor-opponent-sift", 0.18f,
1005                                                  DescriptorExtractor::create("OpponentSIFT") );
1006     test.safe_run();
1007 }
1008
1009 TEST( Features2d_DescriptorExtractor_OpponentSURF, regression )
1010 {
1011     CV_DescriptorExtractorTest<L2<float> > test( "descriptor-opponent-surf",  0.3f,
1012                                                  DescriptorExtractor::create("OpponentSURF") );
1013     test.safe_run();
1014 }
1015
1016 /*#if CV_SSE2
1017 TEST( Features2d_DescriptorExtractor_Calonder_uchar, regression )
1018 {
1019     CV_CalonderDescriptorExtractorTest<uchar, L2<uchar> > test( "descriptor-calonder-uchar",
1020                                                                 std::numeric_limits<float>::epsilon() + 1,
1021                                                                 0.0132175f );
1022     test.safe_run();
1023 }
1024
1025 TEST( Features2d_DescriptorExtractor_Calonder_float, regression )
1026 {
1027     CV_CalonderDescriptorExtractorTest<float, L2<float> > test( "descriptor-calonder-float",
1028                                                                 std::numeric_limits<float>::epsilon(),
1029                                                                 0.0221308f );
1030     test.safe_run();
1031 }
1032 #endif*/ // CV_SSE2
1033
1034 TEST(Features2d_BruteForceDescriptorMatcher_knnMatch, regression)
1035 {
1036     const int sz = 100;
1037     const int k = 3;
1038
1039     Ptr<DescriptorExtractor> ext = DescriptorExtractor::create("SURF");
1040     ASSERT_TRUE(ext != NULL);
1041
1042     Ptr<FeatureDetector> det = FeatureDetector::create("SURF");
1043     //"%YAML:1.0\nhessianThreshold: 8000.\noctaves: 3\noctaveLayers: 4\nupright: 0\n"
1044     ASSERT_TRUE(det != NULL);
1045
1046     Ptr<DescriptorMatcher> matcher = DescriptorMatcher::create("BruteForce");
1047     ASSERT_TRUE(matcher != NULL);
1048
1049     Mat imgT(sz, sz, CV_8U, Scalar(255));
1050     line(imgT, Point(20, sz/2), Point(sz-21, sz/2), Scalar(100), 2);
1051     line(imgT, Point(sz/2, 20), Point(sz/2, sz-21), Scalar(100), 2);
1052     vector<KeyPoint> kpT;
1053     kpT.push_back( KeyPoint(50, 50, 16, 0, 20000, 1, -1) );
1054     kpT.push_back( KeyPoint(42, 42, 16, 160, 10000, 1, -1) );
1055     Mat descT;
1056     ext->compute(imgT, kpT, descT);
1057
1058     Mat imgQ(sz, sz, CV_8U, Scalar(255));
1059     line(imgQ, Point(30, sz/2), Point(sz-31, sz/2), Scalar(100), 3);
1060     line(imgQ, Point(sz/2, 30), Point(sz/2, sz-31), Scalar(100), 3);
1061     vector<KeyPoint> kpQ;
1062     det->detect(imgQ, kpQ);
1063     Mat descQ;
1064     ext->compute(imgQ, kpQ, descQ);
1065
1066     vector<vector<DMatch> > matches;
1067
1068     matcher->knnMatch(descQ, descT, matches, k);
1069
1070     //cout << "\nBest " << k << " matches to " << descT.rows << " train desc-s." << endl;
1071     ASSERT_EQ(descQ.rows, static_cast<int>(matches.size()));
1072     for(size_t i = 0; i<matches.size(); i++)
1073     {
1074         //cout << "\nmatches[" << i << "].size()==" << matches[i].size() << endl;
1075         ASSERT_GE(min(k, descT.rows), static_cast<int>(matches[i].size()));
1076         for(size_t j = 0; j<matches[i].size(); j++)
1077         {
1078             //cout << "\t" << matches[i][j].queryIdx << " -> " << matches[i][j].trainIdx << endl;
1079             ASSERT_EQ(matches[i][j].queryIdx, static_cast<int>(i));
1080         }
1081     }
1082 }
1083
1084 /*TEST(Features2d_DescriptorExtractorParamTest, regression)
1085 {
1086     Ptr<DescriptorExtractor> s = DescriptorExtractor::create("SURF");
1087     ASSERT_STREQ(s->paramHelp("extended").c_str(), "");
1088 }
1089 */
1090
1091 class CV_DetectPlanarTest : public cvtest::BaseTest
1092 {
1093 public:
1094     CV_DetectPlanarTest(const string& _fname, int _min_ninliers) : fname(_fname), min_ninliers(_min_ninliers) {}
1095
1096 protected:
1097     void run(int)
1098     {
1099         Ptr<Feature2D> f = Algorithm::create<Feature2D>("Feature2D." + fname);
1100         if(f.empty())
1101             return;
1102         string path = string(ts->get_data_path()) + "detectors_descriptors_evaluation/planar/";
1103         string imgname1 = path + "box.png";
1104         string imgname2 = path + "box_in_scene.png";
1105         Mat img1 = imread(imgname1, 0);
1106         Mat img2 = imread(imgname2, 0);
1107         if( img1.empty() || img2.empty() )
1108         {
1109             ts->printf( cvtest::TS::LOG, "missing %s and/or %s\n", imgname1.c_str(), imgname2.c_str());
1110             ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_TEST_DATA );
1111             return;
1112         }
1113         vector<KeyPoint> kpt1, kpt2;
1114         Mat d1, d2;
1115         f->operator()(img1, Mat(), kpt1, d1);
1116         f->operator()(img1, Mat(), kpt2, d2);
1117         for( size_t i = 0; i < kpt1.size(); i++ )
1118             CV_Assert(kpt1[i].response > 0 );
1119         for( size_t i = 0; i < kpt2.size(); i++ )
1120             CV_Assert(kpt2[i].response > 0 );
1121
1122         vector<DMatch> matches;
1123         BFMatcher(NORM_L2, true).match(d1, d2, matches);
1124
1125         vector<Point2f> pt1, pt2;
1126         for( size_t i = 0; i < matches.size(); i++ ) {
1127             pt1.push_back(kpt1[matches[i].queryIdx].pt);
1128             pt2.push_back(kpt2[matches[i].trainIdx].pt);
1129         }
1130
1131         Mat inliers, H = findHomography(pt1, pt2, RANSAC, 10, inliers);
1132         int ninliers = countNonZero(inliers);
1133
1134         if( ninliers < min_ninliers )
1135         {
1136             ts->printf( cvtest::TS::LOG, "too little inliers (%d) vs expected %d\n", ninliers, min_ninliers);
1137             ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_TEST_DATA );
1138             return;
1139         }
1140     }
1141
1142     string fname;
1143     int min_ninliers;
1144 };
1145
1146 TEST(Features2d_SIFTHomographyTest, regression) { CV_DetectPlanarTest test("SIFT", 80); test.safe_run(); }
1147 TEST(Features2d_SURFHomographyTest, regression) { CV_DetectPlanarTest test("SURF", 80); test.safe_run(); }
1148