fixed many warnings from GCC 4.6.1
[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
44 using namespace std;
45 using namespace cv;
46
47 const string FEATURES2D_DIR = "features2d";
48 const string DETECTOR_DIR = FEATURES2D_DIR + "/feature_detectors";
49 const string DESCRIPTOR_DIR = FEATURES2D_DIR + "/descriptor_extractors";
50 const string IMAGE_FILENAME = "tsukuba.png";
51
52 /****************************************************************************************\
53 *            Regression tests for feature detectors comparing keypoints.                 *
54 \****************************************************************************************/
55
56 class CV_FeatureDetectorTest : public cvtest::BaseTest
57 {
58 public:
59     CV_FeatureDetectorTest( const string& _name, const Ptr<FeatureDetector>& _fdetector ) :
60         name(_name), fdetector(_fdetector) {}
61
62 protected:
63     bool isSimilarKeypoints( const KeyPoint& p1, const KeyPoint& p2 );
64     void compareKeypointSets( const vector<KeyPoint>& validKeypoints, const vector<KeyPoint>& calcKeypoints );
65
66     void emptyDataTest();
67     void regressionTest(); // TODO test of detect() with mask
68
69     virtual void run( int );
70
71     string name;
72     Ptr<FeatureDetector> fdetector;
73 };
74
75 void CV_FeatureDetectorTest::emptyDataTest()
76 {
77     // One image.
78     Mat image;
79     vector<KeyPoint> keypoints;
80     try
81     {
82         fdetector->detect( image, keypoints );
83     }
84     catch(...)
85     {
86         ts->printf( cvtest::TS::LOG, "detect() on empty image must not generate exception (1).\n" );
87         ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
88     }
89
90     if( !keypoints.empty() )
91     {
92         ts->printf( cvtest::TS::LOG, "detect() on empty image must return empty keypoints vector (1).\n" );
93         ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
94         return;
95     }
96
97     // Several images.
98     vector<Mat> images;
99     vector<vector<KeyPoint> > keypointCollection;
100     try
101     {
102         fdetector->detect( images, keypointCollection );
103     }
104     catch(...)
105     {
106         ts->printf( cvtest::TS::LOG, "detect() on empty image vector must not generate exception (2).\n" );
107         ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
108     }
109 }
110
111 bool CV_FeatureDetectorTest::isSimilarKeypoints( const KeyPoint& p1, const KeyPoint& p2 )
112 {
113     const float maxPtDif = 1.f;
114     const float maxSizeDif = 1.f;
115     const float maxAngleDif = 2.f;
116     const float maxResponseDif = 0.1f;
117
118     float dist = (float)norm( p1.pt - p2.pt );
119     return (dist < maxPtDif &&
120             fabs(p1.size - p2.size) < maxSizeDif &&
121             abs(p1.angle - p2.angle) < maxAngleDif &&
122             abs(p1.response - p2.response) < maxResponseDif &&
123             p1.octave == p2.octave &&
124             p1.class_id == p2.class_id );
125 }
126
127 void CV_FeatureDetectorTest::compareKeypointSets( const vector<KeyPoint>& validKeypoints, const vector<KeyPoint>& calcKeypoints )
128 {
129     const float maxCountRatioDif = 0.01f;
130
131     // Compare counts of validation and calculated keypoints.
132     float countRatio = (float)validKeypoints.size() / (float)calcKeypoints.size();
133     if( countRatio < 1 - maxCountRatioDif || countRatio > 1.f + maxCountRatioDif )
134     {
135         ts->printf( cvtest::TS::LOG, "Bad keypoints count ratio (validCount = %d, calcCount = %d).\n",
136                     validKeypoints.size(), calcKeypoints.size() );
137         ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
138         return;
139     }
140
141     int progress = 0, progressCount = (int)(validKeypoints.size() * calcKeypoints.size());
142     int badPointCount = 0, commonPointCount = max((int)validKeypoints.size(), (int)calcKeypoints.size());
143     for( size_t v = 0; v < validKeypoints.size(); v++ )
144     {
145         int nearestIdx = -1;
146         float minDist = std::numeric_limits<float>::max();
147
148         for( size_t c = 0; c < calcKeypoints.size(); c++ )
149         {
150             progress = update_progress( progress, (int)(v*calcKeypoints.size() + c), progressCount, 0 );
151             float curDist = (float)norm( calcKeypoints[c].pt - validKeypoints[v].pt );
152             if( curDist < minDist )
153             {
154                 minDist = curDist;
155                 nearestIdx = (int)c;
156             }
157         }
158
159         assert( minDist >= 0 );
160         if( !isSimilarKeypoints( validKeypoints[v], calcKeypoints[nearestIdx] ) )
161             badPointCount++;
162     }
163     ts->printf( cvtest::TS::LOG, "badPointCount = %d; validPointCount = %d; calcPointCount = %d\n",
164                 badPointCount, validKeypoints.size(), calcKeypoints.size() );
165     if( badPointCount > 0.9 * commonPointCount )
166     {
167         ts->printf( cvtest::TS::LOG, " - Bad accuracy!\n" );
168         ts->set_failed_test_info( cvtest::TS::FAIL_BAD_ACCURACY );
169         return;
170     }
171     ts->printf( cvtest::TS::LOG, " - OK\n" );
172 }
173
174 void CV_FeatureDetectorTest::regressionTest()
175 {
176     assert( !fdetector.empty() );
177     string imgFilename = string(ts->get_data_path()) + FEATURES2D_DIR + "/" + IMAGE_FILENAME;
178     string resFilename = string(ts->get_data_path()) + DETECTOR_DIR + "/" + string(name) + ".xml.gz";
179
180     // Read the test image.
181     Mat image = imread( imgFilename );
182     if( image.empty() )
183     {
184         ts->printf( cvtest::TS::LOG, "Image %s can not be read.\n", imgFilename.c_str() );
185         ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_TEST_DATA );
186         return;
187     }
188
189     FileStorage fs( resFilename, FileStorage::READ );
190
191     // Compute keypoints.
192     vector<KeyPoint> calcKeypoints;
193     fdetector->detect( image, calcKeypoints );
194
195     if( fs.isOpened() ) // Compare computed and valid keypoints.
196     {
197         // TODO compare saved feature detector params with current ones
198
199         // Read validation keypoints set.
200         vector<KeyPoint> validKeypoints;
201         read( fs["keypoints"], validKeypoints );
202         if( validKeypoints.empty() )
203         {
204             ts->printf( cvtest::TS::LOG, "Keypoints can not be read.\n" );
205             ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_TEST_DATA );
206             return;
207         }
208
209         compareKeypointSets( validKeypoints, calcKeypoints );
210     }
211     else // Write detector parameters and computed keypoints as validation data.
212     {
213         fs.open( resFilename, FileStorage::WRITE );
214         if( !fs.isOpened() )
215         {
216             ts->printf( cvtest::TS::LOG, "File %s can not be opened to write.\n", resFilename.c_str() );
217             ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_TEST_DATA );
218             return;
219         }
220         else
221         {
222             fs << "detector_params" << "{";
223             fdetector->write( fs );
224             fs << "}";
225
226             write( fs, "keypoints", calcKeypoints );
227         }
228     }
229 }
230
231 void CV_FeatureDetectorTest::run( int /*start_from*/ )
232 {
233     if( fdetector.empty() )
234     {
235         ts->printf( cvtest::TS::LOG, "Feature detector is empty.\n" );
236         ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_TEST_DATA );
237         return;
238     }
239
240     emptyDataTest();
241     regressionTest();
242
243     ts->set_failed_test_info( cvtest::TS::OK );
244 }
245
246 /****************************************************************************************\
247 *                     Regression tests for descriptor extractors.                        *
248 \****************************************************************************************/
249 static void writeMatInBin( const Mat& mat, const string& filename )
250 {
251     FILE* f = fopen( filename.c_str(), "wb");
252     if( f )
253     {
254         int type = mat.type();
255         fwrite( (void*)&mat.rows, sizeof(int), 1, f );
256         fwrite( (void*)&mat.cols, sizeof(int), 1, f );
257         fwrite( (void*)&type, sizeof(int), 1, f );
258         int dataSize = (int)(mat.step * mat.rows * mat.channels());
259         fwrite( (void*)&dataSize, sizeof(int), 1, f );
260         fwrite( (void*)mat.data, 1, dataSize, f );
261         fclose(f);
262     }
263 }
264
265 static Mat readMatFromBin( const string& filename )
266 {
267     FILE* f = fopen( filename.c_str(), "rb" );
268     if( f )
269     {
270         int rows, cols, type, dataSize;
271         fread( (void*)&rows, sizeof(int), 1, f );
272         fread( (void*)&cols, sizeof(int), 1, f );
273         fread( (void*)&type, sizeof(int), 1, f );
274         fread( (void*)&dataSize, sizeof(int), 1, f );
275
276         uchar* data = (uchar*)cvAlloc(dataSize);
277         fread( (void*)data, 1, dataSize, f );
278         fclose(f);
279
280         return Mat( rows, cols, type, data );
281     }
282     return Mat();
283 }
284
285 template<class Distance>
286 class CV_DescriptorExtractorTest : public cvtest::BaseTest
287 {
288 public:
289     typedef typename Distance::ValueType ValueType;
290     typedef typename Distance::ResultType DistanceType;
291
292     CV_DescriptorExtractorTest( const string _name, DistanceType _maxDist, const Ptr<DescriptorExtractor>& _dextractor, float _prevTime,
293                                 Distance d = Distance() ):
294             name(_name), maxDist(_maxDist), prevTime(_prevTime), dextractor(_dextractor), distance(d) {}
295 protected:
296     virtual void createDescriptorExtractor() {}
297
298     void compareDescriptors( const Mat& validDescriptors, const Mat& calcDescriptors )
299     {
300         if( validDescriptors.size != calcDescriptors.size || validDescriptors.type() != calcDescriptors.type() )
301         {
302             ts->printf(cvtest::TS::LOG, "Valid and computed descriptors matrices must have the same size and type.\n");
303             ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_TEST_DATA );
304             return;
305         }
306
307         CV_Assert( DataType<ValueType>::type == validDescriptors.type() );
308
309         int dimension = validDescriptors.cols;
310         DistanceType curMaxDist = std::numeric_limits<DistanceType>::min();
311         for( int y = 0; y < validDescriptors.rows; y++ )
312         {
313             DistanceType dist = distance( validDescriptors.ptr<ValueType>(y), calcDescriptors.ptr<ValueType>(y), dimension );
314             if( dist > curMaxDist )
315                 curMaxDist = dist;
316         }
317
318         stringstream ss;
319         ss << "Max distance between valid and computed descriptors " << curMaxDist;
320         if( curMaxDist < maxDist )
321             ss << "." << endl;
322         else
323         {
324             ss << ">" << maxDist  << " - bad accuracy!"<< endl;
325             ts->set_failed_test_info( cvtest::TS::FAIL_BAD_ACCURACY );
326         }
327         ts->printf(cvtest::TS::LOG,  ss.str().c_str() );
328     }
329
330     void emptyDataTest()
331     {
332         assert( !dextractor.empty() );
333
334         // One image.
335         Mat image;
336         vector<KeyPoint> keypoints;
337         Mat descriptors;
338
339         try
340         {
341             dextractor->compute( image, keypoints, descriptors );
342         }
343         catch(...)
344         {
345             ts->printf( cvtest::TS::LOG, "compute() on empty image and empty keypoints must not generate exception (1).\n");
346             ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_TEST_DATA );
347         }
348
349         image.create( 50, 50, CV_8UC3 );
350         try
351         {
352             dextractor->compute( image, keypoints, descriptors );
353         }
354         catch(...)
355         {
356             ts->printf( cvtest::TS::LOG, "compute() on nonempty image and empty keypoints must not generate exception (1).\n");
357             ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_TEST_DATA );
358         }
359
360         // Several images.
361         vector<Mat> images;
362         vector<vector<KeyPoint> > keypointsCollection;
363         vector<Mat> descriptorsCollection;
364         try
365         {
366             dextractor->compute( images, keypointsCollection, descriptorsCollection );
367         }
368         catch(...)
369         {
370             ts->printf( cvtest::TS::LOG, "compute() on empty images and empty keypoints collection must not generate exception (2).\n");
371             ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_TEST_DATA );
372         }
373     }
374
375     void regressionTest()
376     {
377         assert( !dextractor.empty() );
378
379         // Read the test image.
380         string imgFilename =  string(ts->get_data_path()) + FEATURES2D_DIR + "/" + IMAGE_FILENAME;
381
382         Mat img = imread( imgFilename );
383         if( img.empty() )
384         {
385             ts->printf( cvtest::TS::LOG, "Image %s can not be read.\n", imgFilename.c_str() );
386             ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_TEST_DATA );
387             return;
388         }
389
390         vector<KeyPoint> keypoints;
391         FileStorage fs( string(ts->get_data_path()) + FEATURES2D_DIR + "/keypoints.xml.gz", FileStorage::READ );
392         if( fs.isOpened() )
393         {
394             read( fs.getFirstTopLevelNode(), keypoints );
395
396             Mat calcDescriptors;
397             double t = (double)getTickCount();
398             dextractor->compute( img, keypoints, calcDescriptors );
399             t = getTickCount() - t;
400             ts->printf(cvtest::TS::LOG, "\nAverage time of computing one descriptor = %g ms (previous time = %g ms).\n", t/((double)cvGetTickFrequency()*1000.)/calcDescriptors.rows, prevTime );
401
402             if( calcDescriptors.rows != (int)keypoints.size() )
403             {
404                 ts->printf( cvtest::TS::LOG, "Count of computed descriptors and keypoints count must be equal.\n" );
405                 ts->printf( cvtest::TS::LOG, "Count of keypoints is            %d.\n", (int)keypoints.size() );
406                 ts->printf( cvtest::TS::LOG, "Count of computed descriptors is %d.\n", calcDescriptors.rows );
407                 ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
408                 return;
409             }
410
411             if( calcDescriptors.cols != dextractor->descriptorSize() || calcDescriptors.type() != dextractor->descriptorType() )
412             {
413                 ts->printf( cvtest::TS::LOG, "Incorrect descriptor size or descriptor type.\n" );
414                 ts->printf( cvtest::TS::LOG, "Expected size is   %d.\n", dextractor->descriptorSize() );
415                 ts->printf( cvtest::TS::LOG, "Calculated size is %d.\n", calcDescriptors.cols );
416                 ts->printf( cvtest::TS::LOG, "Expected type is   %d.\n", dextractor->descriptorType() );
417                 ts->printf( cvtest::TS::LOG, "Calculated type is %d.\n", calcDescriptors.type() );
418                 ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
419                 return;
420             }
421
422             // TODO read and write descriptor extractor parameters and check them
423             Mat validDescriptors = readDescriptors();
424             if( !validDescriptors.empty() )
425                 compareDescriptors( validDescriptors, calcDescriptors );
426             else
427             {
428                 if( !writeDescriptors( calcDescriptors ) )
429                 {
430                     ts->printf( cvtest::TS::LOG, "Descriptors can not be written.\n" );
431                     ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_TEST_DATA );
432                     return;
433                 }
434             }
435         }
436         else
437         {
438             ts->printf( cvtest::TS::LOG, "Compute and write keypoints.\n" );
439             fs.open( string(ts->get_data_path()) + FEATURES2D_DIR + "/keypoints.xml.gz", FileStorage::WRITE );
440             if( fs.isOpened() )
441             {
442                 SurfFeatureDetector fd;
443                 fd.detect(img, keypoints);
444                 write( fs, "keypoints", keypoints );
445             }
446             else
447             {
448                 ts->printf(cvtest::TS::LOG, "File for writting keypoints can not be opened.\n");
449                 ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_TEST_DATA );
450                 return;
451             }
452         }
453     }
454
455     void run(int)
456     {
457         createDescriptorExtractor();
458         if( dextractor.empty() )
459         {
460             ts->printf(cvtest::TS::LOG, "Descriptor extractor is empty.\n");
461             ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_TEST_DATA );
462             return;
463         }
464
465         emptyDataTest();
466         regressionTest();
467
468         ts->set_failed_test_info( cvtest::TS::OK );
469     }
470
471     virtual Mat readDescriptors()
472     {
473         Mat res = readMatFromBin( string(ts->get_data_path()) + DESCRIPTOR_DIR + "/" + string(name) );
474         return res;
475     }
476
477     virtual bool writeDescriptors( Mat& descs )
478     {
479         writeMatInBin( descs,  string(ts->get_data_path()) + DESCRIPTOR_DIR + "/" + string(name) );
480         return true;
481     }
482
483     string name;
484     const DistanceType maxDist;
485     const float prevTime;
486     Ptr<DescriptorExtractor> dextractor;
487     Distance distance;
488
489 private:
490     CV_DescriptorExtractorTest& operator=(const CV_DescriptorExtractorTest&) { return *this; }
491 };
492
493 /*template<typename T, typename Distance>
494 class CV_CalonderDescriptorExtractorTest : public CV_DescriptorExtractorTest<Distance>
495 {
496 public:
497     CV_CalonderDescriptorExtractorTest( const char* testName, float _normDif, float _prevTime ) :
498             CV_DescriptorExtractorTest<Distance>( testName, _normDif, Ptr<DescriptorExtractor>(), _prevTime )
499     {}
500
501 protected:
502     virtual void createDescriptorExtractor()
503     {
504         CV_DescriptorExtractorTest<Distance>::dextractor =
505                 new CalonderDescriptorExtractor<T>( string(CV_DescriptorExtractorTest<Distance>::ts->get_data_path()) +
506                                                     FEATURES2D_DIR + "/calonder_classifier.rtc");
507     }
508 };*/
509
510 /****************************************************************************************\
511 *                       Algorithmic tests for descriptor matchers                        *
512 \****************************************************************************************/
513 class CV_DescriptorMatcherTest : public cvtest::BaseTest
514 {
515 public:
516     CV_DescriptorMatcherTest( const string& _name, const Ptr<DescriptorMatcher>& _dmatcher, float _badPart ) :
517         badPart(_badPart), name(_name), dmatcher(_dmatcher)
518         {}
519 protected:
520     static const int dim = 500;
521     static const int queryDescCount = 300; // must be even number because we split train data in some cases in two
522     static const int countFactor = 4; // do not change it
523     const float badPart;
524
525     virtual void run( int );
526     void generateData( Mat& query, Mat& train );
527
528     void emptyDataTest();
529     void matchTest( const Mat& query, const Mat& train );
530     void knnMatchTest( const Mat& query, const Mat& train );
531     void radiusMatchTest( const Mat& query, const Mat& train );
532
533     string name;
534     Ptr<DescriptorMatcher> dmatcher;
535
536 private:
537     CV_DescriptorMatcherTest& operator=(const CV_DescriptorMatcherTest&) { return *this; }
538 };
539
540 void CV_DescriptorMatcherTest::emptyDataTest()
541 {
542     assert( !dmatcher.empty() );
543     Mat queryDescriptors, trainDescriptors, mask;
544     vector<Mat> trainDescriptorCollection, masks;
545     vector<DMatch> matches;
546     vector<vector<DMatch> > vmatches;
547
548     try
549     {
550         dmatcher->match( queryDescriptors, trainDescriptors, matches, mask );
551     }
552     catch(...)
553     {
554         ts->printf( cvtest::TS::LOG, "match() on empty descriptors must not generate exception (1).\n" );
555         ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
556     }
557
558     try
559     {
560         dmatcher->knnMatch( queryDescriptors, trainDescriptors, vmatches, 2, mask );
561     }
562     catch(...)
563     {
564         ts->printf( cvtest::TS::LOG, "knnMatch() on empty descriptors must not generate exception (1).\n" );
565         ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
566     }
567
568     try
569     {
570         dmatcher->radiusMatch( queryDescriptors, trainDescriptors, vmatches, 10.f, mask );
571     }
572     catch(...)
573     {
574         ts->printf( cvtest::TS::LOG, "radiusMatch() on empty descriptors must not generate exception (1).\n" );
575         ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
576     }
577
578     try
579     {
580         dmatcher->add( trainDescriptorCollection );
581     }
582     catch(...)
583     {
584         ts->printf( cvtest::TS::LOG, "add() on empty descriptors must not generate exception.\n" );
585         ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
586     }
587
588     try
589     {
590         dmatcher->match( queryDescriptors, matches, masks );
591     }
592     catch(...)
593     {
594         ts->printf( cvtest::TS::LOG, "match() on empty descriptors must not generate exception (2).\n" );
595         ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
596     }
597
598     try
599     {
600         dmatcher->knnMatch( queryDescriptors, vmatches, 2, masks );
601     }
602     catch(...)
603     {
604         ts->printf( cvtest::TS::LOG, "knnMatch() on empty descriptors must not generate exception (2).\n" );
605         ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
606     }
607
608     try
609     {
610         dmatcher->radiusMatch( queryDescriptors, vmatches, 10.f, masks );
611     }
612     catch(...)
613     {
614         ts->printf( cvtest::TS::LOG, "radiusMatch() on empty descriptors must not generate exception (2).\n" );
615         ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
616     }
617
618 }
619
620 void CV_DescriptorMatcherTest::generateData( Mat& query, Mat& train )
621 {
622     RNG& rng = theRNG();
623
624     // Generate query descriptors randomly.
625     // Descriptor vector elements are integer values.
626     Mat buf( queryDescCount, dim, CV_32SC1 );
627     rng.fill( buf, RNG::UNIFORM, Scalar::all(0), Scalar(3) );
628     buf.convertTo( query, CV_32FC1 );
629
630     // Generate train decriptors as follows:
631     // copy each query descriptor to train set countFactor times
632     // and perturb some one element of the copied descriptors in
633     // in ascending order. General boundaries of the perturbation
634     // are (0.f, 1.f).
635     train.create( query.rows*countFactor, query.cols, CV_32FC1 );
636     float step = 1.f / countFactor;
637     for( int qIdx = 0; qIdx < query.rows; qIdx++ )
638     {
639         Mat queryDescriptor = query.row(qIdx);
640         for( int c = 0; c < countFactor; c++ )
641         {
642             int tIdx = qIdx * countFactor + c;
643             Mat trainDescriptor = train.row(tIdx);
644             queryDescriptor.copyTo( trainDescriptor );
645             int elem = rng(dim);
646             float diff = rng.uniform( step*c, step*(c+1) );
647             trainDescriptor.at<float>(0, elem) += diff;
648         }
649     }
650 }
651
652 void CV_DescriptorMatcherTest::matchTest( const Mat& query, const Mat& train )
653 {
654     dmatcher->clear();
655
656     // test const version of match()
657     {
658         vector<DMatch> matches;
659         dmatcher->match( query, train, matches );
660
661         if( (int)matches.size() != queryDescCount )
662         {
663             ts->printf(cvtest::TS::LOG, "Incorrect matches count while test match() function (1).\n");
664             ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
665         }
666         else
667         {
668             int badCount = 0;
669             for( size_t i = 0; i < matches.size(); i++ )
670             {
671                 DMatch match = matches[i];
672                 if( (match.queryIdx != (int)i) || (match.trainIdx != (int)i*countFactor) || (match.imgIdx != 0) )
673                     badCount++;
674             }
675             if( (float)badCount > (float)queryDescCount*badPart )
676             {
677                 ts->printf( cvtest::TS::LOG, "%f - too large bad matches part while test match() function (1).\n",
678                             (float)badCount/(float)queryDescCount );
679                 ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
680             }
681         }
682     }
683
684     // test version of match() with add()
685     {
686         vector<DMatch> matches;
687         // make add() twice to test such case
688         dmatcher->add( vector<Mat>(1,train.rowRange(0, train.rows/2)) );
689         dmatcher->add( vector<Mat>(1,train.rowRange(train.rows/2, train.rows)) );
690         // prepare masks (make first nearest match illegal)
691         vector<Mat> masks(2);
692         for(int mi = 0; mi < 2; mi++ )
693         {
694             masks[mi] = Mat(query.rows, train.rows/2, CV_8UC1, Scalar::all(1));
695             for( int di = 0; di < queryDescCount/2; di++ )
696                 masks[mi].col(di*countFactor).setTo(Scalar::all(0));
697         }
698
699         dmatcher->match( query, matches, masks );
700
701         if( (int)matches.size() != queryDescCount )
702         {
703             ts->printf(cvtest::TS::LOG, "Incorrect matches count while test match() function (2).\n");
704             ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
705         }
706         else
707         {
708             int badCount = 0;
709             for( size_t i = 0; i < matches.size(); i++ )
710             {
711                 DMatch match = matches[i];
712                 int shift = dmatcher->isMaskSupported() ? 1 : 0;
713                 {
714                     if( i < queryDescCount/2 )
715                     {
716                         if( (match.queryIdx != (int)i) || (match.trainIdx != (int)i*countFactor + shift) || (match.imgIdx != 0) )
717                             badCount++;
718                     }
719                     else
720                     {
721                         if( (match.queryIdx != (int)i) || (match.trainIdx != ((int)i-queryDescCount/2)*countFactor + shift) || (match.imgIdx != 1) )
722                             badCount++;
723                     }
724                 }
725             }
726             if( (float)badCount > (float)queryDescCount*badPart )
727             {
728                 ts->printf( cvtest::TS::LOG, "%f - too large bad matches part while test match() function (2).\n",
729                             (float)badCount/(float)queryDescCount );
730                 ts->set_failed_test_info( cvtest::TS::FAIL_BAD_ACCURACY );
731             }
732         }
733     }
734 }
735
736 void CV_DescriptorMatcherTest::knnMatchTest( const Mat& query, const Mat& train )
737 {
738     dmatcher->clear();
739
740     // test const version of knnMatch()
741     {
742         const int knn = 3;
743
744         vector<vector<DMatch> > matches;
745         dmatcher->knnMatch( query, train, matches, knn );
746
747         if( (int)matches.size() != queryDescCount )
748         {
749             ts->printf(cvtest::TS::LOG, "Incorrect matches count while test knnMatch() function (1).\n");
750             ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
751         }
752         else
753         {
754             int badCount = 0;
755             for( size_t i = 0; i < matches.size(); i++ )
756             {
757                 if( (int)matches[i].size() != knn )
758                     badCount++;
759                 else
760                 {
761                     int localBadCount = 0;
762                     for( int k = 0; k < knn; k++ )
763                     {
764                         DMatch match = matches[i][k];
765                         if( (match.queryIdx != (int)i) || (match.trainIdx != (int)i*countFactor+k) || (match.imgIdx != 0) )
766                             localBadCount++;
767                     }
768                     badCount += localBadCount > 0 ? 1 : 0;
769                 }
770             }
771             if( (float)badCount > (float)queryDescCount*badPart )
772             {
773                 ts->printf( cvtest::TS::LOG, "%f - too large bad matches part while test knnMatch() function (1).\n",
774                             (float)badCount/(float)queryDescCount );
775                 ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
776             }
777         }
778     }
779
780     // test version of knnMatch() with add()
781     {
782         const int knn = 2;
783         vector<vector<DMatch> > matches;
784         // make add() twice to test such case
785         dmatcher->add( vector<Mat>(1,train.rowRange(0, train.rows/2)) );
786         dmatcher->add( vector<Mat>(1,train.rowRange(train.rows/2, train.rows)) );
787         // prepare masks (make first nearest match illegal)
788         vector<Mat> masks(2);
789         for(int mi = 0; mi < 2; mi++ )
790         {
791             masks[mi] = Mat(query.rows, train.rows/2, CV_8UC1, Scalar::all(1));
792             for( int di = 0; di < queryDescCount/2; di++ )
793                 masks[mi].col(di*countFactor).setTo(Scalar::all(0));
794         }
795
796         dmatcher->knnMatch( query, matches, knn, masks );
797
798         if( (int)matches.size() != queryDescCount )
799         {
800             ts->printf(cvtest::TS::LOG, "Incorrect matches count while test knnMatch() function (2).\n");
801             ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
802         }
803         else
804         {
805             int badCount = 0;
806             int shift = dmatcher->isMaskSupported() ? 1 : 0;
807             for( size_t i = 0; i < matches.size(); i++ )
808             {
809                 if( (int)matches[i].size() != knn )
810                     badCount++;
811                 else
812                 {
813                     int localBadCount = 0;
814                     for( int k = 0; k < knn; k++ )
815                     {
816                         DMatch match = matches[i][k];
817                         {
818                             if( i < queryDescCount/2 )
819                             {
820                                 if( (match.queryIdx != (int)i) || (match.trainIdx != (int)i*countFactor + k + shift) ||
821                                     (match.imgIdx != 0) )
822                                     localBadCount++;
823                             }
824                             else
825                             {
826                                 if( (match.queryIdx != (int)i) || (match.trainIdx != ((int)i-queryDescCount/2)*countFactor + k + shift) ||
827                                     (match.imgIdx != 1) )
828                                     localBadCount++;
829                             }
830                         }
831                     }
832                     badCount += localBadCount > 0 ? 1 : 0;
833                 }
834             }
835             if( (float)badCount > (float)queryDescCount*badPart )
836             {
837                 ts->printf( cvtest::TS::LOG, "%f - too large bad matches part while test knnMatch() function (2).\n",
838                             (float)badCount/(float)queryDescCount );
839                 ts->set_failed_test_info( cvtest::TS::FAIL_BAD_ACCURACY );
840             }
841         }
842     }
843 }
844
845 void CV_DescriptorMatcherTest::radiusMatchTest( const Mat& query, const Mat& train )
846 {
847     dmatcher->clear();
848     // test const version of match()
849     {
850         const float radius = 1.f/countFactor;
851         vector<vector<DMatch> > matches;
852         dmatcher->radiusMatch( query, train, matches, radius );
853
854         if( (int)matches.size() != queryDescCount )
855         {
856             ts->printf(cvtest::TS::LOG, "Incorrect matches count while test radiusMatch() function (1).\n");
857             ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
858         }
859         else
860         {
861             int badCount = 0;
862             for( size_t i = 0; i < matches.size(); i++ )
863             {
864                 if( (int)matches[i].size() != 1 )
865                     badCount++;
866                 else
867                 {
868                     DMatch match = matches[i][0];
869                     if( (match.queryIdx != (int)i) || (match.trainIdx != (int)i*countFactor) || (match.imgIdx != 0) )
870                         badCount++;
871                 }
872             }
873             if( (float)badCount > (float)queryDescCount*badPart )
874             {
875                 ts->printf( cvtest::TS::LOG, "%f - too large bad matches part while test radiusMatch() function (1).\n",
876                             (float)badCount/(float)queryDescCount );
877                 ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
878             }
879         }
880     }
881
882     // test version of match() with add()
883     {
884         int n = 3;
885         const float radius = 1.f/countFactor * n;
886         vector<vector<DMatch> > matches;
887         // make add() twice to test such case
888         dmatcher->add( vector<Mat>(1,train.rowRange(0, train.rows/2)) );
889         dmatcher->add( vector<Mat>(1,train.rowRange(train.rows/2, train.rows)) );
890         // prepare masks (make first nearest match illegal)
891         vector<Mat> masks(2);
892         for(int mi = 0; mi < 2; mi++ )
893         {
894             masks[mi] = Mat(query.rows, train.rows/2, CV_8UC1, Scalar::all(1));
895             for( int di = 0; di < queryDescCount/2; di++ )
896                 masks[mi].col(di*countFactor).setTo(Scalar::all(0));
897         }
898
899         dmatcher->radiusMatch( query, matches, radius, masks );
900
901         //int curRes = cvtest::TS::OK;
902         if( (int)matches.size() != queryDescCount )
903         {
904             ts->printf(cvtest::TS::LOG, "Incorrect matches count while test radiusMatch() function (1).\n");
905             ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
906         }
907
908         int badCount = 0;
909         int shift = dmatcher->isMaskSupported() ? 1 : 0;
910         int needMatchCount = dmatcher->isMaskSupported() ? n-1 : n;
911         for( size_t i = 0; i < matches.size(); i++ )
912         {
913             if( (int)matches[i].size() != needMatchCount )
914                 badCount++;
915             else
916             {
917                 int localBadCount = 0;
918                 for( int k = 0; k < needMatchCount; k++ )
919                 {
920                     DMatch match = matches[i][k];
921                     {
922                         if( i < queryDescCount/2 )
923                         {
924                             if( (match.queryIdx != (int)i) || (match.trainIdx != (int)i*countFactor + k + shift) ||
925                                 (match.imgIdx != 0) )
926                                 localBadCount++;
927                         }
928                         else
929                         {
930                             if( (match.queryIdx != (int)i) || (match.trainIdx != ((int)i-queryDescCount/2)*countFactor + k + shift) ||
931                                 (match.imgIdx != 1) )
932                                 localBadCount++;
933                         }
934                     }
935                 }
936                 badCount += localBadCount > 0 ? 1 : 0;
937             }
938         }
939         if( (float)badCount > (float)queryDescCount*badPart )
940         {
941             ts->printf( cvtest::TS::LOG, "%f - too large bad matches part while test radiusMatch() function (2).\n",
942                         (float)badCount/(float)queryDescCount );
943             ts->set_failed_test_info( cvtest::TS::FAIL_BAD_ACCURACY );
944         }
945     }
946 }
947
948 void CV_DescriptorMatcherTest::run( int )
949 {
950     Mat query, train;
951     generateData( query, train );
952
953     matchTest( query, train );
954
955     knnMatchTest( query, train );
956
957     radiusMatchTest( query, train );
958 }
959
960 /****************************************************************************************\
961 *                                Tests registrations                                     *
962 \****************************************************************************************/
963
964 /*
965  * Detectors
966  */
967
968
969 TEST( Features2d_Detector_SIFT, regression )
970 {
971     CV_FeatureDetectorTest test( "detector-sift", FeatureDetector::create("SIFT") );
972     test.safe_run();
973 }
974
975 TEST( Features2d_Detector_SURF, regression )
976 {
977     CV_FeatureDetectorTest test( "detector-surf", FeatureDetector::create("SURF") );
978     test.safe_run();
979 }
980
981 /*
982  * Descriptors
983  */
984 TEST( Features2d_DescriptorExtractor_SIFT, regression )
985 {
986     CV_DescriptorExtractorTest<L2<float> > test( "descriptor-sift", 0.03f,
987                                                   DescriptorExtractor::create("SIFT"), 8.06652f  );
988     test.safe_run();
989 }
990
991 TEST( Features2d_DescriptorExtractor_SURF, regression )
992 {
993     CV_DescriptorExtractorTest<L2<float> > test( "descriptor-surf",  0.035f,
994                                                  DescriptorExtractor::create("SURF"), 0.147372f );
995     test.safe_run();
996 }
997
998 /*TEST( Features2d_DescriptorExtractor_OpponentSIFT, regression )
999 {
1000     CV_DescriptorExtractorTest<L2<float> > test( "descriptor-opponent-sift", 0.18f,
1001                                                  DescriptorExtractor::create("OpponentSIFT"), 8.06652f  );
1002     test.safe_run();
1003 }*/
1004
1005 TEST( Features2d_DescriptorExtractor_OpponentSURF, regression )
1006 {
1007     CV_DescriptorExtractorTest<L2<float> > test( "descriptor-opponent-surf",  0.18f,
1008                                                  DescriptorExtractor::create("OpponentSURF"), 0.147372f );
1009     test.safe_run();
1010 }
1011
1012 /*#if CV_SSE2
1013 TEST( Features2d_DescriptorExtractor_Calonder_uchar, regression )
1014 {
1015     CV_CalonderDescriptorExtractorTest<uchar, L2<uchar> > test( "descriptor-calonder-uchar",
1016                                                                 std::numeric_limits<float>::epsilon() + 1,
1017                                                                 0.0132175f );
1018     test.safe_run();
1019 }
1020
1021 TEST( Features2d_DescriptorExtractor_Calonder_float, regression )
1022 {
1023     CV_CalonderDescriptorExtractorTest<float, L2<float> > test( "descriptor-calonder-float",
1024                                                                 std::numeric_limits<float>::epsilon(),
1025                                                                 0.0221308f );
1026     test.safe_run();
1027 }
1028 #endif*/ // CV_SSE2