test_nearestneighbors.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  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. // License Agreement
  11. // For Open Source Computer Vision Library
  12. //
  13. // Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
  14. // Copyright (C) 2009, Willow Garage Inc., all rights reserved.
  15. // Copyright (C) 2014, Itseez Inc, all rights reserved.
  16. // Third party copyrights are property of their respective owners.
  17. //
  18. // Redistribution and use in source and binary forms, with or without modification,
  19. // are permitted provided that the following conditions are met:
  20. //
  21. // * Redistribution's of source code must retain the above copyright notice,
  22. // this list of conditions and the following disclaimer.
  23. //
  24. // * Redistribution's in binary form must reproduce the above copyright notice,
  25. // this list of conditions and the following disclaimer in the documentation
  26. // and/or other materials provided with the distribution.
  27. //
  28. // * The name of the copyright holders may not be used to endorse or promote products
  29. // derived from this software without specific prior written permission.
  30. //
  31. // This software is provided by the copyright holders and contributors "as is" and
  32. // any express or implied warranties, including, but not limited to, the implied
  33. // warranties of merchantability and fitness for a particular purpose are disclaimed.
  34. // In no event shall the Intel Corporation or contributors be liable for any direct,
  35. // indirect, incidental, special, exemplary, or consequential damages
  36. // (including, but not limited to, procurement of substitute goods or services;
  37. // loss of use, data, or profits; or business interruption) however caused
  38. // and on any theory of liability, whether in contract, strict liability,
  39. // or tort (including negligence or otherwise) arising in any way out of
  40. // the use of this software, even if advised of the possibility of such damage.
  41. //
  42. //M*/
  43. #include "test_precomp.hpp"
  44. namespace opencv_test { namespace {
  45. #ifdef HAVE_OPENCV_FLANN
  46. using namespace cv::flann;
  47. #endif
  48. //--------------------------------------------------------------------------------
  49. class NearestNeighborTest : public cvtest::BaseTest
  50. {
  51. public:
  52. NearestNeighborTest() {}
  53. protected:
  54. static const int minValue = 0;
  55. static const int maxValue = 1;
  56. static const int dims = 30;
  57. static const int featuresCount = 2000;
  58. static const int K = 1; // * should also test 2nd nn etc.?
  59. virtual void run( int start_from );
  60. virtual void createModel( const Mat& data ) = 0;
  61. virtual int findNeighbors( Mat& points, Mat& neighbors ) = 0;
  62. virtual int checkGetPoints( const Mat& data );
  63. virtual int checkFindBoxed();
  64. virtual int checkFind( const Mat& data );
  65. virtual void releaseModel() = 0;
  66. };
  67. int NearestNeighborTest::checkGetPoints( const Mat& )
  68. {
  69. return cvtest::TS::OK;
  70. }
  71. int NearestNeighborTest::checkFindBoxed()
  72. {
  73. return cvtest::TS::OK;
  74. }
  75. int NearestNeighborTest::checkFind( const Mat& data )
  76. {
  77. int code = cvtest::TS::OK;
  78. int pointsCount = 1000;
  79. float noise = 0.2f;
  80. RNG rng;
  81. Mat points( pointsCount, dims, CV_32FC1 );
  82. Mat results( pointsCount, K, CV_32SC1 );
  83. std::vector<int> fmap( pointsCount );
  84. for( int pi = 0; pi < pointsCount; pi++ )
  85. {
  86. int fi = rng.next() % featuresCount;
  87. fmap[pi] = fi;
  88. for( int d = 0; d < dims; d++ )
  89. points.at<float>(pi, d) = data.at<float>(fi, d) + rng.uniform(0.0f, 1.0f) * noise;
  90. }
  91. code = findNeighbors( points, results );
  92. if( code == cvtest::TS::OK )
  93. {
  94. int correctMatches = 0;
  95. for( int pi = 0; pi < pointsCount; pi++ )
  96. {
  97. if( fmap[pi] == results.at<int>(pi, 0) )
  98. correctMatches++;
  99. }
  100. double correctPerc = correctMatches / (double)pointsCount;
  101. EXPECT_GE(correctPerc, .75) << "correctMatches=" << correctMatches << " pointsCount=" << pointsCount;
  102. }
  103. return code;
  104. }
  105. void NearestNeighborTest::run( int /*start_from*/ ) {
  106. int code = cvtest::TS::OK, tempCode;
  107. Mat desc( featuresCount, dims, CV_32FC1 );
  108. ts->get_rng().fill( desc, RNG::UNIFORM, minValue, maxValue );
  109. createModel( desc.clone() ); // .clone() is used to simulate dangling pointers problem: https://github.com/opencv/opencv/issues/17553
  110. tempCode = checkGetPoints( desc );
  111. if( tempCode != cvtest::TS::OK )
  112. {
  113. ts->printf( cvtest::TS::LOG, "bad accuracy of GetPoints \n" );
  114. code = tempCode;
  115. }
  116. tempCode = checkFindBoxed();
  117. if( tempCode != cvtest::TS::OK )
  118. {
  119. ts->printf( cvtest::TS::LOG, "bad accuracy of FindBoxed \n" );
  120. code = tempCode;
  121. }
  122. tempCode = checkFind( desc );
  123. if( tempCode != cvtest::TS::OK )
  124. {
  125. ts->printf( cvtest::TS::LOG, "bad accuracy of Find \n" );
  126. code = tempCode;
  127. }
  128. releaseModel();
  129. if (::testing::Test::HasFailure()) code = cvtest::TS::FAIL_BAD_ACCURACY;
  130. ts->set_failed_test_info( code );
  131. }
  132. //--------------------------------------------------------------------------------
  133. #ifdef HAVE_OPENCV_FLANN
  134. class CV_FlannTest : public NearestNeighborTest
  135. {
  136. public:
  137. CV_FlannTest() : NearestNeighborTest(), index(NULL) { }
  138. protected:
  139. void createIndex( const Mat& data, const IndexParams& params );
  140. int knnSearch( Mat& points, Mat& neighbors );
  141. int radiusSearch( Mat& points, Mat& neighbors );
  142. virtual void releaseModel();
  143. Index* index;
  144. };
  145. void CV_FlannTest::createIndex( const Mat& data, const IndexParams& params )
  146. {
  147. // release previously allocated index
  148. releaseModel();
  149. index = new Index( data, params );
  150. }
  151. int CV_FlannTest::knnSearch( Mat& points, Mat& neighbors )
  152. {
  153. Mat dist( points.rows, neighbors.cols, CV_32FC1);
  154. int knn = 1, j;
  155. // 1st way
  156. index->knnSearch( points, neighbors, dist, knn, SearchParams() );
  157. // 2nd way
  158. Mat neighbors1( neighbors.size(), CV_32SC1 );
  159. for( int i = 0; i < points.rows; i++ )
  160. {
  161. float* fltPtr = points.ptr<float>(i);
  162. vector<float> query( fltPtr, fltPtr + points.cols );
  163. vector<int> indices( neighbors1.cols, 0 );
  164. vector<float> dists( dist.cols, 0 );
  165. index->knnSearch( query, indices, dists, knn, SearchParams() );
  166. vector<int>::const_iterator it = indices.begin();
  167. for( j = 0; it != indices.end(); ++it, j++ )
  168. neighbors1.at<int>(i,j) = *it;
  169. }
  170. // compare results
  171. EXPECT_LE(cvtest::norm(neighbors, neighbors1, NORM_L1), 0);
  172. return ::testing::Test::HasFailure() ? cvtest::TS::FAIL_BAD_ACCURACY : cvtest::TS::OK;
  173. }
  174. int CV_FlannTest::radiusSearch( Mat& points, Mat& neighbors )
  175. {
  176. Mat dist( 1, neighbors.cols, CV_32FC1);
  177. Mat neighbors1( neighbors.size(), CV_32SC1 );
  178. float radius = 10.0f;
  179. int j;
  180. // radiusSearch can only search one feature at a time for range search
  181. for( int i = 0; i < points.rows; i++ )
  182. {
  183. // 1st way
  184. Mat p( 1, points.cols, CV_32FC1, points.ptr<float>(i) ),
  185. n( 1, neighbors.cols, CV_32SC1, neighbors.ptr<int>(i) );
  186. index->radiusSearch( p, n, dist, radius, neighbors.cols, SearchParams() );
  187. // 2nd way
  188. float* fltPtr = points.ptr<float>(i);
  189. vector<float> query( fltPtr, fltPtr + points.cols );
  190. vector<int> indices( neighbors1.cols, 0 );
  191. vector<float> dists( dist.cols, 0 );
  192. index->radiusSearch( query, indices, dists, radius, neighbors.cols, SearchParams() );
  193. vector<int>::const_iterator it = indices.begin();
  194. for( j = 0; it != indices.end(); ++it, j++ )
  195. neighbors1.at<int>(i,j) = *it;
  196. }
  197. // compare results
  198. EXPECT_LE(cvtest::norm(neighbors, neighbors1, NORM_L1), 0);
  199. return ::testing::Test::HasFailure() ? cvtest::TS::FAIL_BAD_ACCURACY : cvtest::TS::OK;
  200. }
  201. void CV_FlannTest::releaseModel()
  202. {
  203. if (index)
  204. {
  205. delete index;
  206. index = NULL;
  207. }
  208. }
  209. //---------------------------------------
  210. class CV_FlannLinearIndexTest : public CV_FlannTest
  211. {
  212. public:
  213. CV_FlannLinearIndexTest() {}
  214. protected:
  215. virtual void createModel( const Mat& data ) { createIndex( data, LinearIndexParams() ); }
  216. virtual int findNeighbors( Mat& points, Mat& neighbors ) { return knnSearch( points, neighbors ); }
  217. };
  218. //---------------------------------------
  219. class CV_FlannKMeansIndexTest : public CV_FlannTest
  220. {
  221. public:
  222. CV_FlannKMeansIndexTest() {}
  223. protected:
  224. virtual void createModel( const Mat& data ) { createIndex( data, KMeansIndexParams() ); }
  225. virtual int findNeighbors( Mat& points, Mat& neighbors ) { return radiusSearch( points, neighbors ); }
  226. };
  227. //---------------------------------------
  228. class CV_FlannKDTreeIndexTest : public CV_FlannTest
  229. {
  230. public:
  231. CV_FlannKDTreeIndexTest() {}
  232. protected:
  233. virtual void createModel( const Mat& data ) { createIndex( data, KDTreeIndexParams() ); }
  234. virtual int findNeighbors( Mat& points, Mat& neighbors ) { return radiusSearch( points, neighbors ); }
  235. };
  236. //----------------------------------------
  237. class CV_FlannCompositeIndexTest : public CV_FlannTest
  238. {
  239. public:
  240. CV_FlannCompositeIndexTest() {}
  241. protected:
  242. virtual void createModel( const Mat& data ) { createIndex( data, CompositeIndexParams() ); }
  243. virtual int findNeighbors( Mat& points, Mat& neighbors ) { return knnSearch( points, neighbors ); }
  244. };
  245. //----------------------------------------
  246. class CV_FlannAutotunedIndexTest : public CV_FlannTest
  247. {
  248. public:
  249. CV_FlannAutotunedIndexTest() {}
  250. protected:
  251. virtual void createModel( const Mat& data ) { createIndex( data, AutotunedIndexParams() ); }
  252. virtual int findNeighbors( Mat& points, Mat& neighbors ) { return knnSearch( points, neighbors ); }
  253. };
  254. //----------------------------------------
  255. class CV_FlannSavedIndexTest : public CV_FlannTest
  256. {
  257. public:
  258. CV_FlannSavedIndexTest() {}
  259. protected:
  260. virtual void createModel( const Mat& data );
  261. virtual int findNeighbors( Mat& points, Mat& neighbors ) { return knnSearch( points, neighbors ); }
  262. };
  263. void CV_FlannSavedIndexTest::createModel(const cv::Mat &data)
  264. {
  265. switch ( cvtest::randInt(ts->get_rng()) % 2 )
  266. {
  267. //case 0: createIndex( data, LinearIndexParams() ); break; // nothing to save for linear search
  268. case 0: createIndex( data, KMeansIndexParams() ); break;
  269. case 1: createIndex( data, KDTreeIndexParams() ); break;
  270. //case 2: createIndex( data, CompositeIndexParams() ); break; // nothing to save for linear search
  271. //case 2: createIndex( data, AutotunedIndexParams() ); break; // possible linear index !
  272. default: CV_Assert(0);
  273. }
  274. string filename = tempfile();
  275. index->save( filename );
  276. createIndex( data, SavedIndexParams(filename.c_str()));
  277. remove( filename.c_str() );
  278. }
  279. TEST(Features2d_FLANN_Linear, regression) { CV_FlannLinearIndexTest test; test.safe_run(); }
  280. TEST(Features2d_FLANN_KMeans, regression) { CV_FlannKMeansIndexTest test; test.safe_run(); }
  281. TEST(Features2d_FLANN_KDTree, regression) { CV_FlannKDTreeIndexTest test; test.safe_run(); }
  282. TEST(Features2d_FLANN_Composite, regression) { CV_FlannCompositeIndexTest test; test.safe_run(); }
  283. TEST(Features2d_FLANN_Auto, regression) { CV_FlannAutotunedIndexTest test; test.safe_run(); }
  284. TEST(Features2d_FLANN_Saved, regression) { CV_FlannSavedIndexTest test; test.safe_run(); }
  285. #endif
  286. }} // namespace