test_goodfeaturetotrack.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  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. #include "test_precomp.hpp"
  42. namespace opencv_test { namespace {
  43. enum { MINEIGENVAL=0, HARRIS=1, EIGENVALSVECS=2 };
  44. #if 0 //set 1 to switch ON debug message
  45. #define TEST_MESSAGE( message ) std::cout << message;
  46. #define TEST_MESSAGEL( message, val) std::cout << message << val << std::endl;
  47. #else
  48. #define TEST_MESSAGE( message )
  49. #define TEST_MESSAGEL( message, val)
  50. #endif
  51. /////////////////////ref//////////////////////
  52. struct greaterThanPtr
  53. {
  54. bool operator () (const float * a, const float * b) const
  55. { return *a > *b; }
  56. };
  57. static void
  58. test_cornerEigenValsVecs( const Mat& src, Mat& eigenv, int block_size,
  59. int _aperture_size, double k, int mode, int borderType, const Scalar& _borderValue )
  60. {
  61. int i, j;
  62. Scalar borderValue = _borderValue;
  63. int aperture_size = _aperture_size < 0 ? 3 : _aperture_size;
  64. Point anchor( aperture_size/2, aperture_size/2 );
  65. CV_Assert( src.type() == CV_8UC1 || src.type() == CV_32FC1 );
  66. CV_Assert( eigenv.type() == CV_32FC1 );
  67. CV_Assert( ( src.rows == eigenv.rows ) &&
  68. (((mode == MINEIGENVAL)||(mode == HARRIS)) && (src.cols == eigenv.cols)) );
  69. int type = src.type();
  70. int ftype = CV_32FC1;
  71. double kernel_scale = 1;
  72. Mat dx2, dy2, dxdy(src.size(), CV_32F), kernel;
  73. kernel = cvtest::calcSobelKernel2D( 1, 0, _aperture_size );
  74. cvtest::filter2D( src, dx2, ftype, kernel*kernel_scale, anchor, 0, borderType, borderValue );
  75. kernel = cvtest::calcSobelKernel2D( 0, 1, _aperture_size );
  76. cvtest::filter2D( src, dy2, ftype, kernel*kernel_scale, anchor, 0, borderType,borderValue );
  77. double denom = (1 << (aperture_size-1))*block_size;
  78. if( _aperture_size < 0 )
  79. denom *= 2.;
  80. if(type != ftype )
  81. denom *= 255.;
  82. denom = 1. / (denom * denom);
  83. for( i = 0; i < src.rows; i++ )
  84. {
  85. float* dxdyp = dxdy.ptr<float>(i);
  86. float* dx2p = dx2.ptr<float>(i);
  87. float* dy2p = dy2.ptr<float>(i);
  88. for( j = 0; j < src.cols; j++ )
  89. {
  90. double xval = dx2p[j], yval = dy2p[j];
  91. dxdyp[j] = (float)(xval*yval*denom);
  92. dx2p[j] = (float)(xval*xval*denom);
  93. dy2p[j] = (float)(yval*yval*denom);
  94. }
  95. }
  96. kernel = Mat::ones(block_size, block_size, CV_32F);
  97. anchor = Point(block_size/2, block_size/2);
  98. cvtest::filter2D( dx2, dx2, ftype, kernel, anchor, 0, borderType, borderValue );
  99. cvtest::filter2D( dy2, dy2, ftype, kernel, anchor, 0, borderType, borderValue );
  100. cvtest::filter2D( dxdy, dxdy, ftype, kernel, anchor, 0, borderType, borderValue );
  101. if( mode == MINEIGENVAL )
  102. {
  103. for( i = 0; i < src.rows; i++ )
  104. {
  105. float* eigenvp = eigenv.ptr<float>(i);
  106. const float* dxdyp = dxdy.ptr<float>(i);
  107. const float* dx2p = dx2.ptr<float>(i);
  108. const float* dy2p = dy2.ptr<float>(i);
  109. for( j = 0; j < src.cols; j++ )
  110. {
  111. double a = dx2p[j], b = dxdyp[j], c = dy2p[j];
  112. double d = sqrt( ( a - c )*( a - c ) + 4*b*b );
  113. eigenvp[j] = (float)( 0.5*(a + c - d));
  114. }
  115. }
  116. }
  117. else if( mode == HARRIS )
  118. {
  119. for( i = 0; i < src.rows; i++ )
  120. {
  121. float* eigenvp = eigenv.ptr<float>(i);
  122. const float* dxdyp = dxdy.ptr<float>(i);
  123. const float* dx2p = dx2.ptr<float>(i);
  124. const float* dy2p = dy2.ptr<float>(i);
  125. for( j = 0; j < src.cols; j++ )
  126. {
  127. double a = dx2p[j], b = dxdyp[j], c = dy2p[j];
  128. eigenvp[j] = (float)(a*c - b*b - k*(a + c)*(a + c));
  129. }
  130. }
  131. }
  132. }
  133. static void
  134. test_goodFeaturesToTrack( InputArray _image, OutputArray _corners,
  135. int maxCorners, double qualityLevel, double minDistance,
  136. InputArray _mask, OutputArray _cornersQuality,
  137. int blockSize, int gradientSize, bool useHarrisDetector, double harrisK)
  138. {
  139. CV_Assert( qualityLevel > 0 && minDistance >= 0 && maxCorners >= 0 );
  140. CV_Assert( _mask.empty() || (_mask.type() == CV_8UC1 && _mask.sameSize(_image)) );
  141. Mat image = _image.getMat(), mask = _mask.getMat();
  142. int aperture_size = gradientSize;
  143. int borderType = BORDER_DEFAULT;
  144. Mat eig, tmp, tt;
  145. eig.create( image.size(), CV_32F );
  146. if( useHarrisDetector )
  147. test_cornerEigenValsVecs( image, eig, blockSize, aperture_size, harrisK, HARRIS, borderType, 0 );
  148. else
  149. test_cornerEigenValsVecs( image, eig, blockSize, aperture_size, 0, MINEIGENVAL, borderType, 0 );
  150. double maxVal = 0;
  151. cvtest::minMaxIdx( eig, 0, &maxVal, 0, 0, mask );
  152. cvtest::threshold( eig, eig, (float)(maxVal*qualityLevel), 0.f,THRESH_TOZERO );
  153. cvtest::dilate( eig, tmp, Mat(),Point(-1,-1),borderType,0);
  154. Size imgsize = image.size();
  155. vector<const float*> tmpCorners;
  156. // collect list of pointers to features - put them into temporary image
  157. for( int y = 1; y < imgsize.height - 1; y++ )
  158. {
  159. const float* eig_data = (const float*)eig.ptr(y);
  160. const float* tmp_data = (const float*)tmp.ptr(y);
  161. const uchar* mask_data = mask.data ? mask.ptr(y) : 0;
  162. for( int x = 1; x < imgsize.width - 1; x++ )
  163. {
  164. float val = eig_data[x];
  165. if( val != 0 && val == tmp_data[x] && (!mask_data || mask_data[x]) )
  166. {
  167. tmpCorners.push_back(eig_data + x);
  168. }
  169. }
  170. }
  171. vector<Point2f> corners;
  172. vector<float> cornersQuality;
  173. size_t i, j, total = tmpCorners.size(), ncorners = 0;
  174. std::sort( tmpCorners.begin(), tmpCorners.end(), greaterThanPtr() );
  175. if(minDistance >= 1)
  176. {
  177. // Partition the image into larger grids
  178. int w = image.cols;
  179. int h = image.rows;
  180. const int cell_size = cvRound(minDistance);
  181. const int grid_width = (w + cell_size - 1) / cell_size;
  182. const int grid_height = (h + cell_size - 1) / cell_size;
  183. std::vector<std::vector<Point2f> > grid(grid_width*grid_height);
  184. minDistance *= minDistance;
  185. for( i = 0; i < total; i++ )
  186. {
  187. int ofs = (int)((const uchar*)tmpCorners[i] - eig.data);
  188. int y = (int)(ofs / eig.step);
  189. int x = (int)((ofs - y*eig.step)/sizeof(float));
  190. bool good = true;
  191. int x_cell = x / cell_size;
  192. int y_cell = y / cell_size;
  193. int x1 = x_cell - 1;
  194. int y1 = y_cell - 1;
  195. int x2 = x_cell + 1;
  196. int y2 = y_cell + 1;
  197. // boundary check
  198. x1 = std::max(0, x1);
  199. y1 = std::max(0, y1);
  200. x2 = std::min(grid_width-1, x2);
  201. y2 = std::min(grid_height-1, y2);
  202. for( int yy = y1; yy <= y2; yy++ )
  203. {
  204. for( int xx = x1; xx <= x2; xx++ )
  205. {
  206. vector <Point2f> &m = grid[yy*grid_width + xx];
  207. if( m.size() )
  208. {
  209. for(j = 0; j < m.size(); j++)
  210. {
  211. float dx = x - m[j].x;
  212. float dy = y - m[j].y;
  213. if( dx*dx + dy*dy < minDistance )
  214. {
  215. good = false;
  216. goto break_out;
  217. }
  218. }
  219. }
  220. }
  221. }
  222. break_out:
  223. if(good)
  224. {
  225. grid[y_cell*grid_width + x_cell].push_back(Point2f((float)x, (float)y));
  226. cornersQuality.push_back(*tmpCorners[i]);
  227. corners.push_back(Point2f((float)x, (float)y));
  228. ++ncorners;
  229. if( maxCorners > 0 && (int)ncorners == maxCorners )
  230. break;
  231. }
  232. }
  233. }
  234. else
  235. {
  236. for( i = 0; i < total; i++ )
  237. {
  238. cornersQuality.push_back(*tmpCorners[i]);
  239. int ofs = (int)((const uchar*)tmpCorners[i] - eig.data);
  240. int y = (int)(ofs / eig.step);
  241. int x = (int)((ofs - y*eig.step)/sizeof(float));
  242. corners.push_back(Point2f((float)x, (float)y));
  243. ++ncorners;
  244. if( maxCorners > 0 && (int)ncorners == maxCorners )
  245. break;
  246. }
  247. }
  248. Mat(corners).convertTo(_corners, _corners.fixedType() ? _corners.type() : CV_32F);
  249. if (_cornersQuality.needed()) {
  250. Mat(cornersQuality).convertTo(_cornersQuality, _cornersQuality.fixedType() ? _cornersQuality.type() : CV_32F);
  251. }
  252. }
  253. /////////////////end of ref code//////////////////////////
  254. class CV_GoodFeatureToTTest : public cvtest::ArrayTest
  255. {
  256. public:
  257. CV_GoodFeatureToTTest();
  258. protected:
  259. int prepare_test_case( int test_case_idx );
  260. void run_func();
  261. int validate_test_results( int test_case_idx );
  262. Mat src, src_gray;
  263. Mat src_gray32f, src_gray8U;
  264. Mat mask;
  265. int maxCorners;
  266. vector<Point2f> corners;
  267. vector<Point2f> Refcorners;
  268. vector<float> cornersQuality;
  269. vector<float> RefcornersQuality;
  270. double qualityLevel;
  271. double minDistance;
  272. int blockSize;
  273. int gradientSize;
  274. bool useHarrisDetector;
  275. double k;
  276. int SrcType;
  277. };
  278. CV_GoodFeatureToTTest::CV_GoodFeatureToTTest()
  279. {
  280. RNG& rng = ts->get_rng();
  281. maxCorners = rng.uniform( 50, 100 );
  282. qualityLevel = 0.01;
  283. minDistance = 10;
  284. blockSize = 3;
  285. gradientSize = 3;
  286. useHarrisDetector = false;
  287. k = 0.04;
  288. mask = Mat();
  289. test_case_count = 4;
  290. SrcType = 0;
  291. }
  292. int CV_GoodFeatureToTTest::prepare_test_case( int test_case_idx )
  293. {
  294. const static int types[] = { CV_32FC1, CV_8UC1 };
  295. cvtest::TS& tst = *cvtest::TS::ptr();
  296. src = imread(string(tst.get_data_path()) + "shared/fruits.png", IMREAD_COLOR);
  297. CV_Assert(src.data != NULL);
  298. cvtColor( src, src_gray, COLOR_BGR2GRAY );
  299. SrcType = types[test_case_idx & 0x1];
  300. useHarrisDetector = test_case_idx & 2 ? true : false;
  301. return 1;
  302. }
  303. void CV_GoodFeatureToTTest::run_func()
  304. {
  305. int cn = src_gray.channels();
  306. CV_Assert( cn == 1 );
  307. CV_Assert( ( CV_MAT_DEPTH(SrcType) == CV_32FC1 ) || ( CV_MAT_DEPTH(SrcType) == CV_8UC1 ));
  308. TEST_MESSAGEL (" maxCorners = ", maxCorners)
  309. if (useHarrisDetector)
  310. {
  311. TEST_MESSAGE (" useHarrisDetector = true\n");
  312. }
  313. else
  314. {
  315. TEST_MESSAGE (" useHarrisDetector = false\n");
  316. }
  317. if( CV_MAT_DEPTH(SrcType) == CV_32FC1)
  318. {
  319. if (src_gray.depth() != CV_32FC1 ) src_gray.convertTo(src_gray32f, CV_32FC1);
  320. else src_gray32f = src_gray.clone();
  321. TEST_MESSAGE ("goodFeaturesToTrack 32f\n")
  322. goodFeaturesToTrack( src_gray32f,
  323. corners,
  324. maxCorners,
  325. qualityLevel,
  326. minDistance,
  327. Mat(),
  328. cornersQuality,
  329. blockSize,
  330. gradientSize,
  331. useHarrisDetector,
  332. k );
  333. }
  334. else
  335. {
  336. if (src_gray.depth() != CV_8UC1 ) src_gray.convertTo(src_gray8U, CV_8UC1);
  337. else src_gray8U = src_gray.clone();
  338. TEST_MESSAGE ("goodFeaturesToTrack 8U\n")
  339. goodFeaturesToTrack( src_gray8U,
  340. corners,
  341. maxCorners,
  342. qualityLevel,
  343. minDistance,
  344. Mat(),
  345. cornersQuality,
  346. blockSize,
  347. gradientSize,
  348. useHarrisDetector,
  349. k );
  350. }
  351. }
  352. int CV_GoodFeatureToTTest::validate_test_results( int test_case_idx )
  353. {
  354. static const double eps = 2e-6;
  355. if( CV_MAT_DEPTH(SrcType) == CV_32FC1 )
  356. {
  357. if (src_gray.depth() != CV_32FC1 ) src_gray.convertTo(src_gray32f, CV_32FC1);
  358. else src_gray32f = src_gray.clone();
  359. TEST_MESSAGE ("test_goodFeaturesToTrack 32f\n")
  360. test_goodFeaturesToTrack( src_gray32f,
  361. Refcorners,
  362. maxCorners,
  363. qualityLevel,
  364. minDistance,
  365. Mat(),
  366. RefcornersQuality,
  367. blockSize,
  368. gradientSize,
  369. useHarrisDetector,
  370. k );
  371. }
  372. else
  373. {
  374. if (src_gray.depth() != CV_8UC1 ) src_gray.convertTo(src_gray8U, CV_8UC1);
  375. else src_gray8U = src_gray.clone();
  376. TEST_MESSAGE ("test_goodFeaturesToTrack 8U\n")
  377. test_goodFeaturesToTrack( src_gray8U,
  378. Refcorners,
  379. maxCorners,
  380. qualityLevel,
  381. minDistance,
  382. Mat(),
  383. RefcornersQuality,
  384. blockSize,
  385. gradientSize,
  386. useHarrisDetector,
  387. k );
  388. }
  389. double e = cv::norm(corners, Refcorners); // TODO cvtest
  390. if (e > eps)
  391. {
  392. TEST_MESSAGEL ("Number of features: Refcorners = ", Refcorners.size())
  393. TEST_MESSAGEL (" TestCorners = ", corners.size())
  394. TEST_MESSAGE ("\n")
  395. EXPECT_LE(e, eps); // never true
  396. ts->set_failed_test_info(cvtest::TS::FAIL_BAD_ACCURACY);
  397. for(int i = 0; i < (int)std::min((unsigned int)(corners.size()), (unsigned int)(Refcorners.size())); i++){
  398. if ( (corners[i].x != Refcorners[i].x) || (corners[i].y != Refcorners[i].y))
  399. printf("i = %i X %2.2f Xref %2.2f Y %2.2f Yref %2.2f\n",i,corners[i].x,Refcorners[i].x,corners[i].y,Refcorners[i].y);
  400. }
  401. }
  402. else
  403. {
  404. TEST_MESSAGEL (" Refcorners = ", Refcorners.size())
  405. TEST_MESSAGEL (" TestCorners = ", corners.size())
  406. TEST_MESSAGE ("\n")
  407. ts->set_failed_test_info(cvtest::TS::OK);
  408. }
  409. e = cv::norm(cornersQuality, RefcornersQuality, NORM_RELATIVE | NORM_INF);
  410. if (e > eps)
  411. {
  412. EXPECT_LE(e, eps); // never true
  413. ts->set_failed_test_info(cvtest::TS::FAIL_BAD_ACCURACY);
  414. for(int i = 0; i < (int)std::min((unsigned int)(cornersQuality.size()), (unsigned int)(cornersQuality.size())); i++) {
  415. if (std::abs(cornersQuality[i] - RefcornersQuality[i]) > eps * std::max(cornersQuality[i], RefcornersQuality[i]))
  416. printf("i = %i Quality %2.6f Quality ref %2.6f\n", i, cornersQuality[i], RefcornersQuality[i]);
  417. }
  418. }
  419. return BaseTest::validate_test_results(test_case_idx);
  420. }
  421. TEST(Imgproc_GoodFeatureToT, accuracy) { CV_GoodFeatureToTTest test; test.safe_run(); }
  422. }} // namespace
  423. /* End of file. */