test_chesscorners.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866
  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. #include "test_chessboardgenerator.hpp"
  43. #include <functional>
  44. namespace opencv_test { namespace {
  45. #define _L2_ERR
  46. //#define DEBUG_CHESSBOARD
  47. #ifdef DEBUG_CHESSBOARD
  48. void show_points( const Mat& gray, const Mat& expected, const vector<Point2f>& actual, bool was_found )
  49. {
  50. Mat rgb( gray.size(), CV_8U);
  51. merge(vector<Mat>(3, gray), rgb);
  52. for(size_t i = 0; i < actual.size(); i++ )
  53. circle( rgb, actual[i], 5, Scalar(0, 0, 200), 1, LINE_AA);
  54. if( !expected.empty() )
  55. {
  56. const Point2f* u_data = expected.ptr<Point2f>();
  57. size_t count = expected.cols * expected.rows;
  58. for(size_t i = 0; i < count; i++ )
  59. circle(rgb, u_data[i], 4, Scalar(0, 240, 0), 1, LINE_AA);
  60. }
  61. putText(rgb, was_found ? "FOUND !!!" : "NOT FOUND", Point(5, 20), FONT_HERSHEY_PLAIN, 1, Scalar(0, 240, 0));
  62. imshow( "test", rgb ); while ((uchar)waitKey(0) != 'q') {};
  63. }
  64. #else
  65. #define show_points(...)
  66. #endif
  67. enum Pattern { CHESSBOARD, CHESSBOARD_SB, CHESSBOARD_PLAIN, CIRCLES_GRID, ASYMMETRIC_CIRCLES_GRID};
  68. class CV_ChessboardDetectorTest : public cvtest::BaseTest
  69. {
  70. public:
  71. CV_ChessboardDetectorTest( Pattern pattern, int algorithmFlags = 0 );
  72. protected:
  73. void run(int);
  74. void run_batch(const string& filename);
  75. bool checkByGenerator();
  76. bool checkByGeneratorHighAccuracy();
  77. // wraps calls based on the given pattern
  78. bool findChessboardCornersWrapper(InputArray image, Size patternSize, OutputArray corners,int flags);
  79. Pattern pattern;
  80. int algorithmFlags;
  81. };
  82. CV_ChessboardDetectorTest::CV_ChessboardDetectorTest( Pattern _pattern, int _algorithmFlags )
  83. {
  84. pattern = _pattern;
  85. algorithmFlags = _algorithmFlags;
  86. }
  87. double calcError(const vector<Point2f>& v, const Mat& u)
  88. {
  89. int count_exp = u.cols * u.rows;
  90. const Point2f* u_data = u.ptr<Point2f>();
  91. double err = std::numeric_limits<double>::max();
  92. for( int k = 0; k < 2; ++k )
  93. {
  94. double err1 = 0;
  95. for( int j = 0; j < count_exp; ++j )
  96. {
  97. int j1 = k == 0 ? j : count_exp - j - 1;
  98. double dx = fabs( v[j].x - u_data[j1].x );
  99. double dy = fabs( v[j].y - u_data[j1].y );
  100. #if defined(_L2_ERR)
  101. err1 += dx*dx + dy*dy;
  102. #else
  103. dx = MAX( dx, dy );
  104. if( dx > err1 )
  105. err1 = dx;
  106. #endif //_L2_ERR
  107. //printf("dx = %f\n", dx);
  108. }
  109. //printf("\n");
  110. err = min(err, err1);
  111. }
  112. #if defined(_L2_ERR)
  113. err = sqrt(err/count_exp);
  114. #endif //_L2_ERR
  115. return err;
  116. }
  117. const double rough_success_error_level = 2.5;
  118. const double precise_success_error_level = 2;
  119. /* ///////////////////// chess_corner_test ///////////////////////// */
  120. void CV_ChessboardDetectorTest::run( int /*start_from */)
  121. {
  122. ts->set_failed_test_info( cvtest::TS::OK );
  123. /*if (!checkByGenerator())
  124. return;*/
  125. switch( pattern )
  126. {
  127. case CHESSBOARD_SB:
  128. checkByGeneratorHighAccuracy(); // not supported by CHESSBOARD
  129. /* fallthrough */
  130. case CHESSBOARD_PLAIN:
  131. checkByGenerator();
  132. if (ts->get_err_code() != cvtest::TS::OK)
  133. {
  134. break;
  135. }
  136. run_batch("negative_list.dat");
  137. if (ts->get_err_code() != cvtest::TS::OK)
  138. {
  139. break;
  140. }
  141. run_batch("chessboard_list.dat");
  142. if (ts->get_err_code() != cvtest::TS::OK)
  143. {
  144. break;
  145. }
  146. break;
  147. case CHESSBOARD:
  148. checkByGenerator();
  149. if (ts->get_err_code() != cvtest::TS::OK)
  150. {
  151. break;
  152. }
  153. run_batch("negative_list.dat");
  154. if (ts->get_err_code() != cvtest::TS::OK)
  155. {
  156. break;
  157. }
  158. run_batch("chessboard_list.dat");
  159. if (ts->get_err_code() != cvtest::TS::OK)
  160. {
  161. break;
  162. }
  163. run_batch("chessboard_list_subpixel.dat");
  164. break;
  165. case CIRCLES_GRID:
  166. run_batch("circles_list.dat");
  167. break;
  168. case ASYMMETRIC_CIRCLES_GRID:
  169. run_batch("acircles_list.dat");
  170. break;
  171. }
  172. }
  173. void CV_ChessboardDetectorTest::run_batch( const string& filename )
  174. {
  175. ts->printf(cvtest::TS::LOG, "\nRunning batch %s\n", filename.c_str());
  176. //#define WRITE_POINTS 1
  177. #ifndef WRITE_POINTS
  178. double max_rough_error = 0, max_precise_error = 0;
  179. #endif
  180. string folder;
  181. switch( pattern )
  182. {
  183. case CHESSBOARD:
  184. case CHESSBOARD_SB:
  185. case CHESSBOARD_PLAIN:
  186. folder = string(ts->get_data_path()) + "cv/cameracalibration/";
  187. break;
  188. case CIRCLES_GRID:
  189. folder = string(ts->get_data_path()) + "cv/cameracalibration/circles/";
  190. break;
  191. case ASYMMETRIC_CIRCLES_GRID:
  192. folder = string(ts->get_data_path()) + "cv/cameracalibration/asymmetric_circles/";
  193. break;
  194. }
  195. FileStorage fs( folder + filename, FileStorage::READ );
  196. FileNode board_list = fs["boards"];
  197. if( !fs.isOpened() || board_list.empty() || !board_list.isSeq() || board_list.size() % 2 != 0 )
  198. {
  199. ts->printf( cvtest::TS::LOG, "%s can not be read or is not valid\n", (folder + filename).c_str() );
  200. ts->printf( cvtest::TS::LOG, "fs.isOpened=%d, board_list.empty=%d, board_list.isSeq=%d,board_list.size()%2=%d\n",
  201. fs.isOpened(), (int)board_list.empty(), board_list.isSeq(), board_list.size()%2);
  202. ts->set_failed_test_info( cvtest::TS::FAIL_MISSING_TEST_DATA );
  203. return;
  204. }
  205. int progress = 0;
  206. int max_idx = (int)board_list.size()/2;
  207. if(filename.compare("chessboard_list.dat") == 0 && pattern == CHESSBOARD_PLAIN)
  208. max_idx = 7;
  209. double sum_error = 0.0;
  210. int count = 0;
  211. for(int idx = 0; idx < max_idx; ++idx )
  212. {
  213. ts->update_context( this, idx, true );
  214. /* read the image */
  215. String img_file = board_list[idx * 2];
  216. Mat gray = imread( folder + img_file, IMREAD_GRAYSCALE);
  217. if( gray.empty() )
  218. {
  219. ts->printf( cvtest::TS::LOG, "one of chessboard images can't be read: %s\n", img_file.c_str() );
  220. ts->set_failed_test_info( cvtest::TS::FAIL_MISSING_TEST_DATA );
  221. return;
  222. }
  223. String _filename = folder + (String)board_list[idx * 2 + 1];
  224. bool doesContatinChessboard;
  225. float sharpness;
  226. Mat expected;
  227. {
  228. FileStorage fs1(_filename, FileStorage::READ);
  229. fs1["corners"] >> expected;
  230. fs1["isFound"] >> doesContatinChessboard;
  231. fs1["sharpness"] >> sharpness ;
  232. fs1.release();
  233. }
  234. size_t count_exp = static_cast<size_t>(expected.cols * expected.rows);
  235. Size pattern_size = expected.size();
  236. Mat ori;
  237. vector<Point2f> v;
  238. int flags = 0;
  239. switch( pattern )
  240. {
  241. case CHESSBOARD:
  242. flags = CALIB_CB_ADAPTIVE_THRESH | CALIB_CB_NORMALIZE_IMAGE;
  243. break;
  244. case CHESSBOARD_PLAIN: {
  245. flags = CALIB_CB_PLAIN;
  246. ori = gray.clone();
  247. int min_size = cvRound((gray.cols * gray.rows * 0.05) / ((pattern_size.width+1) * (pattern_size.height+1)));
  248. if(min_size%2==0) min_size += 1;
  249. adaptiveThreshold(gray, gray, 255, ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY, min_size, 0);
  250. dilate(gray, gray, Mat(), Point(-1, -1), 1);
  251. break;
  252. }
  253. case CIRCLES_GRID:
  254. case CHESSBOARD_SB:
  255. case ASYMMETRIC_CIRCLES_GRID:
  256. default:
  257. flags = 0;
  258. }
  259. bool result = findChessboardCornersWrapper(gray, pattern_size,v,flags);
  260. if(result && pattern == CHESSBOARD_PLAIN) {
  261. gray = ori;
  262. cornerSubPix(gray, v, Size(6,6), Size(-1,-1), TermCriteria(TermCriteria::EPS + TermCriteria::COUNT, 30, 0.1));
  263. }
  264. if(result && sharpness && (pattern == CHESSBOARD_SB || pattern == CHESSBOARD || pattern == CHESSBOARD_PLAIN))
  265. {
  266. Scalar s= estimateChessboardSharpness(gray,pattern_size,v);
  267. if(fabs(s[0] - sharpness) > 0.1)
  268. {
  269. ts->printf(cvtest::TS::LOG, "chessboard image has a wrong sharpness in %s. Expected %f but measured %f\n", img_file.c_str(),sharpness,s[0]);
  270. ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
  271. show_points( gray, expected, v, result );
  272. return;
  273. }
  274. }
  275. if(result ^ doesContatinChessboard || (doesContatinChessboard && v.size() != count_exp))
  276. {
  277. ts->printf( cvtest::TS::LOG, "chessboard is detected incorrectly in %s\n", img_file.c_str() );
  278. ts->set_failed_test_info( cvtest::TS::FAIL_INVALID_OUTPUT );
  279. show_points( gray, expected, v, result );
  280. return;
  281. }
  282. if( result )
  283. {
  284. #ifndef WRITE_POINTS
  285. double err = calcError(v, expected);
  286. max_rough_error = MAX( max_rough_error, err );
  287. #endif
  288. if( pattern == CHESSBOARD || pattern == CHESSBOARD_PLAIN )
  289. cornerSubPix( gray, v, Size(5, 5), Size(-1,-1), TermCriteria(TermCriteria::EPS|TermCriteria::MAX_ITER, 30, 0.1));
  290. //find4QuadCornerSubpix(gray, v, Size(5, 5));
  291. show_points( gray, expected, v, result );
  292. #ifndef WRITE_POINTS
  293. // printf("called find4QuadCornerSubpix\n");
  294. err = calcError(v, expected);
  295. sum_error += err;
  296. count++;
  297. if( err > precise_success_error_level )
  298. {
  299. ts->printf( cvtest::TS::LOG, "Image %s: bad accuracy of adjusted corners %f\n", img_file.c_str(), err );
  300. ts->set_failed_test_info( cvtest::TS::FAIL_BAD_ACCURACY );
  301. return;
  302. }
  303. ts->printf(cvtest::TS::LOG, "Error on %s is %f\n", img_file.c_str(), err);
  304. max_precise_error = MAX( max_precise_error, err );
  305. #endif
  306. }
  307. else
  308. {
  309. show_points( gray, Mat(), v, result );
  310. }
  311. #ifdef WRITE_POINTS
  312. Mat mat_v(pattern_size, CV_32FC2, (void*)&v[0]);
  313. FileStorage fs(_filename, FileStorage::WRITE);
  314. fs << "isFound" << result;
  315. fs << "corners" << mat_v;
  316. fs.release();
  317. #endif
  318. progress = update_progress( progress, idx, max_idx, 0 );
  319. }
  320. if (count != 0)
  321. sum_error /= count;
  322. ts->printf(cvtest::TS::LOG, "Average error is %f (%d patterns have been found)\n", sum_error, count);
  323. }
  324. double calcErrorMinError(const Size& cornSz, const vector<Point2f>& corners_found, const vector<Point2f>& corners_generated)
  325. {
  326. Mat m1(cornSz, CV_32FC2, (Point2f*)&corners_generated[0]);
  327. Mat m2; flip(m1, m2, 0);
  328. Mat m3; flip(m1, m3, 1); m3 = m3.t(); flip(m3, m3, 1);
  329. Mat m4 = m1.t(); flip(m4, m4, 1);
  330. double min1 = min(calcError(corners_found, m1), calcError(corners_found, m2));
  331. double min2 = min(calcError(corners_found, m3), calcError(corners_found, m4));
  332. return min(min1, min2);
  333. }
  334. bool validateData(const ChessBoardGenerator& cbg, const Size& imgSz,
  335. const vector<Point2f>& corners_generated)
  336. {
  337. Size cornersSize = cbg.cornersSize();
  338. Mat_<Point2f> mat(cornersSize.height, cornersSize.width, (Point2f*)&corners_generated[0]);
  339. double minNeibDist = std::numeric_limits<double>::max();
  340. double tmp = 0;
  341. for(int i = 1; i < mat.rows - 2; ++i)
  342. for(int j = 1; j < mat.cols - 2; ++j)
  343. {
  344. const Point2f& cur = mat(i, j);
  345. tmp = cv::norm(cur - mat(i + 1, j + 1)); // TODO cvtest
  346. if (tmp < minNeibDist)
  347. minNeibDist = tmp;
  348. tmp = cv::norm(cur - mat(i - 1, j + 1)); // TODO cvtest
  349. if (tmp < minNeibDist)
  350. minNeibDist = tmp;
  351. tmp = cv::norm(cur - mat(i + 1, j - 1)); // TODO cvtest
  352. if (tmp < minNeibDist)
  353. minNeibDist = tmp;
  354. tmp = cv::norm(cur - mat(i - 1, j - 1)); // TODO cvtest
  355. if (tmp < minNeibDist)
  356. minNeibDist = tmp;
  357. }
  358. const double threshold = 0.25;
  359. double cbsize = (max(cornersSize.width, cornersSize.height) + 1) * minNeibDist;
  360. int imgsize = min(imgSz.height, imgSz.width);
  361. return imgsize * threshold < cbsize;
  362. }
  363. bool CV_ChessboardDetectorTest::findChessboardCornersWrapper(InputArray image, Size patternSize, OutputArray corners,int flags)
  364. {
  365. switch(pattern)
  366. {
  367. case CHESSBOARD:
  368. case CHESSBOARD_PLAIN:
  369. return findChessboardCorners(image,patternSize,corners,flags);
  370. case CHESSBOARD_SB:
  371. // check default settings until flags have been specified
  372. return findChessboardCornersSB(image,patternSize,corners,0);
  373. case ASYMMETRIC_CIRCLES_GRID:
  374. flags |= CALIB_CB_ASYMMETRIC_GRID | algorithmFlags;
  375. return findCirclesGrid(image, patternSize,corners,flags);
  376. case CIRCLES_GRID:
  377. flags |= CALIB_CB_SYMMETRIC_GRID;
  378. return findCirclesGrid(image, patternSize,corners,flags);
  379. default:
  380. ts->printf( cvtest::TS::LOG, "Internal Error: unsupported chessboard pattern" );
  381. ts->set_failed_test_info( cvtest::TS::FAIL_GENERIC);
  382. }
  383. return false;
  384. }
  385. bool CV_ChessboardDetectorTest::checkByGenerator()
  386. {
  387. bool res = true;
  388. //theRNG() = 0x58e6e895b9913160;
  389. //cv::DefaultRngAuto dra;
  390. //theRNG() = *ts->get_rng();
  391. Mat bg(Size(800, 600), CV_8UC3, Scalar::all(255));
  392. randu(bg, Scalar::all(0), Scalar::all(255));
  393. GaussianBlur(bg, bg, Size(5, 5), 0.0);
  394. Mat_<float> camMat(3, 3);
  395. camMat << 300.f, 0.f, bg.cols/2.f, 0, 300.f, bg.rows/2.f, 0.f, 0.f, 1.f;
  396. Mat_<float> distCoeffs(1, 5);
  397. distCoeffs << 1.2f, 0.2f, 0.f, 0.f, 0.f;
  398. const Size sizes[] = { Size(6, 6), Size(8, 6), Size(11, 12), Size(5, 4) };
  399. const size_t sizes_num = sizeof(sizes)/sizeof(sizes[0]);
  400. const int test_num = 16;
  401. int progress = 0;
  402. for(int i = 0; i < test_num; ++i)
  403. {
  404. SCOPED_TRACE(cv::format("test_num=%d", test_num));
  405. progress = update_progress( progress, i, test_num, 0 );
  406. ChessBoardGenerator cbg(sizes[i % sizes_num]);
  407. vector<Point2f> corners_generated;
  408. Mat cb = cbg(bg, camMat, distCoeffs, corners_generated);
  409. if(!validateData(cbg, cb.size(), corners_generated))
  410. {
  411. ts->printf( cvtest::TS::LOG, "Chess board skipped - too small" );
  412. continue;
  413. }
  414. /*cb = cb * 0.8 + Scalar::all(30);
  415. GaussianBlur(cb, cb, Size(3, 3), 0.8); */
  416. //cv::addWeighted(cb, 0.8, bg, 0.2, 20, cb);
  417. //cv::namedWindow("CB"); cv::imshow("CB", cb); cv::waitKey();
  418. vector<Point2f> corners_found;
  419. int flags = i % 8; // need to check branches for all flags
  420. bool found = findChessboardCornersWrapper(cb, cbg.cornersSize(), corners_found, flags);
  421. if (!found)
  422. {
  423. ts->printf( cvtest::TS::LOG, "Chess board corners not found\n" );
  424. ts->set_failed_test_info( cvtest::TS::FAIL_BAD_ACCURACY );
  425. res = false;
  426. return res;
  427. }
  428. double err = calcErrorMinError(cbg.cornersSize(), corners_found, corners_generated);
  429. EXPECT_LE(err, rough_success_error_level) << "bad accuracy of corner guesses";
  430. #if 0
  431. if (err >= rough_success_error_level)
  432. {
  433. imshow("cb", cb);
  434. Mat cb_corners = cb.clone();
  435. cv::drawChessboardCorners(cb_corners, cbg.cornersSize(), Mat(corners_found), found);
  436. imshow("corners", cb_corners);
  437. waitKey(0);
  438. }
  439. #endif
  440. }
  441. /* ***** negative ***** */
  442. {
  443. vector<Point2f> corners_found;
  444. bool found = findChessboardCornersWrapper(bg, Size(8, 7), corners_found,0);
  445. if (found)
  446. res = false;
  447. ChessBoardGenerator cbg(Size(8, 7));
  448. vector<Point2f> cg;
  449. Mat cb = cbg(bg, camMat, distCoeffs, cg);
  450. found = findChessboardCornersWrapper(cb, Size(3, 4), corners_found,0);
  451. if (found)
  452. res = false;
  453. Point2f c = std::accumulate(cg.begin(), cg.end(), Point2f(), std::plus<Point2f>()) * (1.f/cg.size());
  454. Mat_<double> aff(2, 3);
  455. aff << 1.0, 0.0, -(double)c.x, 0.0, 1.0, 0.0;
  456. Mat sh;
  457. warpAffine(cb, sh, aff, cb.size());
  458. found = findChessboardCornersWrapper(sh, cbg.cornersSize(), corners_found,0);
  459. if (found)
  460. res = false;
  461. vector< vector<Point> > cnts(1);
  462. vector<Point>& cnt = cnts[0];
  463. cnt.push_back(cg[ 0]); cnt.push_back(cg[0+2]);
  464. cnt.push_back(cg[7+0]); cnt.push_back(cg[7+2]);
  465. cv::drawContours(cb, cnts, -1, Scalar::all(128), FILLED);
  466. found = findChessboardCornersWrapper(cb, cbg.cornersSize(), corners_found,0);
  467. if (found)
  468. res = false;
  469. cv::drawChessboardCorners(cb, cbg.cornersSize(), Mat(corners_found), found);
  470. }
  471. return res;
  472. }
  473. // generates artificial checkerboards using warpPerspective which supports
  474. // subpixel rendering. The transformation is found by transferring corners to
  475. // the camera image using a virtual plane.
  476. bool CV_ChessboardDetectorTest::checkByGeneratorHighAccuracy()
  477. {
  478. // draw 2D pattern
  479. cv::Size pattern_size(6,5);
  480. int cell_size = 80;
  481. bool bwhite = true;
  482. cv::Mat image = cv::Mat::ones((pattern_size.height+3)*cell_size,(pattern_size.width+3)*cell_size,CV_8UC1)*255;
  483. cv::Mat pimage = image(Rect(cell_size,cell_size,(pattern_size.width+1)*cell_size,(pattern_size.height+1)*cell_size));
  484. pimage = 0;
  485. for(int row=0;row<=pattern_size.height;++row)
  486. {
  487. int y = int(cell_size*row+0.5F);
  488. bool bwhite2 = bwhite;
  489. for(int col=0;col<=pattern_size.width;++col)
  490. {
  491. if(bwhite2)
  492. {
  493. int x = int(cell_size*col+0.5F);
  494. pimage(cv::Rect(x,y,cell_size,cell_size)) = 255;
  495. }
  496. bwhite2 = !bwhite2;
  497. }
  498. bwhite = !bwhite;
  499. }
  500. // generate 2d points
  501. std::vector<Point2f> pts1,pts2,pts1_all,pts2_all;
  502. std::vector<Point3f> pts3d;
  503. for(int row=0;row<pattern_size.height;++row)
  504. {
  505. int y = int(cell_size*(row+2));
  506. for(int col=0;col<pattern_size.width;++col)
  507. {
  508. int x = int(cell_size*(col+2));
  509. pts1_all.push_back(cv::Point2f(x-0.5F,y-0.5F));
  510. }
  511. }
  512. // back project chessboard corners to a virtual plane
  513. double fx = 500;
  514. double fy = 500;
  515. cv::Point2f center(250,250);
  516. double fxi = 1.0/fx;
  517. double fyi = 1.0/fy;
  518. for(auto &&pt : pts1_all)
  519. {
  520. // calc camera ray
  521. cv::Vec3f ray(float((pt.x-center.x)*fxi),float((pt.y-center.y)*fyi),1.0F);
  522. ray /= cv::norm(ray);
  523. // intersect ray with virtual plane
  524. cv::Scalar plane(0,0,1,-1);
  525. cv::Vec3f n(float(plane(0)),float(plane(1)),float(plane(2)));
  526. cv::Point3f p0(0,0,0);
  527. cv::Point3f l0(0,0,0); // camera center in world coordinates
  528. p0.z = float(-plane(3)/plane(2));
  529. double val1 = ray.dot(n);
  530. if(val1 == 0)
  531. {
  532. ts->printf( cvtest::TS::LOG, "Internal Error: ray and plane are parallel" );
  533. ts->set_failed_test_info( cvtest::TS::FAIL_GENERIC);
  534. return false;
  535. }
  536. pts3d.push_back(Point3f(ray/val1*cv::Vec3f((p0-l0)).dot(n))+l0);
  537. }
  538. // generate multiple rotations
  539. for(int i=15;i<90;i=i+15)
  540. {
  541. // project 3d points to new camera
  542. Vec3f rvec(0.0F,0.05F,float(float(i)/180.0*CV_PI));
  543. Vec3f tvec(0,0,0);
  544. cv::Mat k = (cv::Mat_<double>(3,3) << fx/2,0,center.x*2, 0,fy/2,center.y, 0,0,1);
  545. cv::projectPoints(pts3d,rvec,tvec,k,cv::Mat(),pts2_all);
  546. // get perspective transform using four correspondences and wrap original image
  547. pts1.clear();
  548. pts2.clear();
  549. pts1.push_back(pts1_all[0]);
  550. pts1.push_back(pts1_all[pattern_size.width-1]);
  551. pts1.push_back(pts1_all[pattern_size.width*pattern_size.height-1]);
  552. pts1.push_back(pts1_all[pattern_size.width*(pattern_size.height-1)]);
  553. pts2.push_back(pts2_all[0]);
  554. pts2.push_back(pts2_all[pattern_size.width-1]);
  555. pts2.push_back(pts2_all[pattern_size.width*pattern_size.height-1]);
  556. pts2.push_back(pts2_all[pattern_size.width*(pattern_size.height-1)]);
  557. Mat m2 = getPerspectiveTransform(pts1,pts2);
  558. Mat out(image.size(),image.type());
  559. warpPerspective(image,out,m2,out.size());
  560. // find checkerboard
  561. vector<Point2f> corners_found;
  562. bool found = findChessboardCornersWrapper(out,pattern_size,corners_found,0);
  563. if (!found)
  564. {
  565. ts->printf( cvtest::TS::LOG, "Chess board corners not found\n" );
  566. ts->set_failed_test_info( cvtest::TS::FAIL_BAD_ACCURACY );
  567. return false;
  568. }
  569. double err = calcErrorMinError(pattern_size,corners_found,pts2_all);
  570. if(err > 0.08)
  571. {
  572. ts->printf( cvtest::TS::LOG, "bad accuracy of corner guesses" );
  573. ts->set_failed_test_info( cvtest::TS::FAIL_BAD_ACCURACY );
  574. return false;
  575. }
  576. //cv::cvtColor(out,out,cv::COLOR_GRAY2BGR);
  577. //cv::drawChessboardCorners(out,pattern_size,corners_found,true);
  578. //cv::imshow("img",out);
  579. //cv::waitKey(-1);
  580. }
  581. return true;
  582. }
  583. TEST(Calib3d_ChessboardDetector, accuracy) { CV_ChessboardDetectorTest test( CHESSBOARD ); test.safe_run(); }
  584. TEST(Calib3d_ChessboardDetector2, accuracy) { CV_ChessboardDetectorTest test( CHESSBOARD_SB ); test.safe_run(); }
  585. TEST(Calib3d_ChessboardDetector3, accuracy) { CV_ChessboardDetectorTest test( CHESSBOARD_PLAIN ); test.safe_run(); }
  586. TEST(Calib3d_CirclesPatternDetector, accuracy) { CV_ChessboardDetectorTest test( CIRCLES_GRID ); test.safe_run(); }
  587. TEST(Calib3d_AsymmetricCirclesPatternDetector, accuracy) { CV_ChessboardDetectorTest test( ASYMMETRIC_CIRCLES_GRID ); test.safe_run(); }
  588. #ifdef HAVE_OPENCV_FLANN
  589. TEST(Calib3d_AsymmetricCirclesPatternDetectorWithClustering, accuracy) { CV_ChessboardDetectorTest test( ASYMMETRIC_CIRCLES_GRID, CALIB_CB_CLUSTERING ); test.safe_run(); }
  590. #endif
  591. TEST(Calib3d_ChessboardWithMarkers, regression_25806_white)
  592. {
  593. const cv::String dataDir = string(TS::ptr()->get_data_path()) + "cv/cameracalibration/";
  594. const cv::Mat image = cv::imread(dataDir + "checkerboard_marker_white.png");
  595. std::vector<Point2f> corners;
  596. const bool success = cv::findChessboardCornersSB(image, Size(9, 14), corners, CALIB_CB_MARKER);
  597. ASSERT_TRUE(success);
  598. }
  599. TEST(Calib3d_ChessboardWithMarkers, regression_25806_black)
  600. {
  601. const cv::String dataDir = string(TS::ptr()->get_data_path()) + "cv/cameracalibration/";
  602. const cv::Mat image = cv::imread(dataDir + "checkerboard_marker_black.png");
  603. std::vector<Point2f> corners;
  604. const bool success = cv::findChessboardCornersSB(image, Size(9, 14), corners, CALIB_CB_MARKER);
  605. ASSERT_TRUE(success);
  606. }
  607. TEST(Calib3d_CirclesPatternDetectorWithClustering, accuracy)
  608. {
  609. cv::String dataDir = string(TS::ptr()->get_data_path()) + "cv/cameracalibration/circles/";
  610. cv::Mat expected;
  611. FileStorage fs(dataDir + "circles_corners15.dat", FileStorage::READ);
  612. fs["corners"] >> expected;
  613. fs.release();
  614. cv::Mat image = cv::imread(dataDir + "circles15.png");
  615. std::vector<Point2f> centers;
  616. cv::findCirclesGrid(image, Size(10, 8), centers, CALIB_CB_SYMMETRIC_GRID | CALIB_CB_CLUSTERING);
  617. ASSERT_EQ(expected.total(), centers.size());
  618. double error = calcError(centers, expected);
  619. ASSERT_LE(error, precise_success_error_level);
  620. }
  621. TEST(Calib3d_AsymmetricCirclesPatternDetector, regression_18713)
  622. {
  623. float pts_[][2] = {
  624. { 166.5, 107 }, { 146, 236 }, { 147, 92 }, { 184, 162 }, { 150, 185.5 },
  625. { 215, 105 }, { 270.5, 186 }, { 159, 142 }, { 6, 205.5 }, { 32, 148.5 },
  626. { 126, 163.5 }, { 181, 208.5 }, { 240.5, 62 }, { 84.5, 76.5 }, { 190, 120.5 },
  627. { 10, 189 }, { 266, 104 }, { 307.5, 207.5 }, { 97, 184 }, { 116.5, 210 },
  628. { 114, 139 }, { 84.5, 233 }, { 269.5, 139 }, { 136, 126.5 }, { 120, 107.5 },
  629. { 129.5, 65.5 }, { 212.5, 140.5 }, { 204.5, 60.5 }, { 207.5, 241 }, { 61.5, 94.5 },
  630. { 186.5, 61.5 }, { 220, 63 }, { 239, 120.5 }, { 212, 186 }, { 284, 87.5 },
  631. { 62, 114.5 }, { 283, 61.5 }, { 238.5, 88.5 }, { 243, 159 }, { 245, 208 },
  632. { 298.5, 158.5 }, { 57, 129 }, { 156.5, 63.5 }, { 192, 90.5 }, { 281, 235.5 },
  633. { 172, 62.5 }, { 291.5, 119.5 }, { 90, 127 }, { 68.5, 166.5 }, { 108.5, 83.5 },
  634. { 22, 176 }
  635. };
  636. Mat candidates(51, 1, CV_32FC2, (void*)pts_);
  637. Size patternSize(4, 9);
  638. std::vector< Point2f > result;
  639. bool res = false;
  640. // issue reports about hangs
  641. EXPECT_NO_THROW(res = findCirclesGrid(candidates, patternSize, result, CALIB_CB_ASYMMETRIC_GRID, Ptr<FeatureDetector>()/*blobDetector=NULL*/));
  642. EXPECT_FALSE(res);
  643. if (cvtest::debugLevel > 0)
  644. {
  645. std::cout << Mat(candidates) << std::endl;
  646. std::cout << Mat(result) << std::endl;
  647. Mat img(Size(400, 300), CV_8UC3, Scalar::all(0));
  648. std::vector< Point2f > centers;
  649. candidates.copyTo(centers);
  650. for (size_t i = 0; i < centers.size(); i++)
  651. {
  652. const Point2f& pt = centers[i];
  653. //printf("{ %g, %g }, \n", pt.x, pt.y);
  654. circle(img, pt, 5, Scalar(0, 255, 0));
  655. }
  656. for (size_t i = 0; i < result.size(); i++)
  657. {
  658. const Point2f& pt = result[i];
  659. circle(img, pt, 10, Scalar(0, 0, 255));
  660. }
  661. imwrite("test_18713.png", img);
  662. if (cvtest::debugLevel >= 10)
  663. {
  664. imshow("result", img);
  665. waitKey();
  666. }
  667. }
  668. }
  669. TEST(Calib3d_AsymmetricCirclesPatternDetector, regression_19498)
  670. {
  671. float pts_[121][2] = {
  672. { 84.7462f, 404.504f }, { 49.1586f, 404.092f }, { 12.3362f, 403.434f }, { 102.542f, 386.214f }, { 67.6042f, 385.475f },
  673. { 31.4982f, 384.569f }, { 141.231f, 377.856f }, { 332.834f, 370.745f }, { 85.7663f, 367.261f }, { 50.346f, 366.051f },
  674. { 13.7726f, 364.663f }, { 371.746f, 362.011f }, { 68.8543f, 347.883f }, { 32.9334f, 346.263f }, { 331.926f, 343.291f },
  675. { 351.535f, 338.112f }, { 51.7951f, 328.247f }, { 15.4613f, 326.095f }, { 311.719f, 319.578f }, { 330.947f, 313.708f },
  676. { 256.706f, 307.584f }, { 34.6834f, 308.167f }, { 291.085f, 295.429f }, { 17.4316f, 287.824f }, { 252.928f, 277.92f },
  677. { 270.19f, 270.93f }, { 288.473f, 263.484f }, { 216.401f, 260.94f }, { 232.195f, 253.656f }, { 266.757f, 237.708f },
  678. { 211.323f, 229.005f }, { 227.592f, 220.498f }, { 154.749f, 188.52f }, { 222.52f, 184.906f }, { 133.85f, 163.968f },
  679. { 200.024f, 158.05f }, { 147.485f, 153.643f }, { 161.967f, 142.633f }, { 177.396f, 131.059f }, { 125.909f, 128.116f },
  680. { 139.817f, 116.333f }, { 91.8639f, 114.454f }, { 104.343f, 102.542f }, { 117.635f, 89.9116f }, { 70.9465f, 89.4619f },
  681. { 82.8524f, 76.7862f }, { 131.738f, 76.4741f }, { 95.5012f, 63.3351f }, { 109.034f, 49.0424f }, { 314.886f, 374.711f },
  682. { 351.735f, 366.489f }, { 279.113f, 357.05f }, { 313.371f, 348.131f }, { 260.123f, 335.271f }, { 276.346f, 330.325f },
  683. { 293.588f, 325.133f }, { 240.86f, 313.143f }, { 273.436f, 301.667f }, { 206.762f, 296.574f }, { 309.877f, 288.796f },
  684. { 187.46f, 274.319f }, { 201.521f, 267.804f }, { 248.973f, 245.918f }, { 181.644f, 244.655f }, { 196.025f, 237.045f },
  685. { 148.41f, 229.131f }, { 161.604f, 221.215f }, { 175.455f, 212.873f }, { 244.748f, 211.459f }, { 128.661f, 206.109f },
  686. { 190.217f, 204.108f }, { 141.346f, 197.568f }, { 205.876f, 194.781f }, { 168.937f, 178.948f }, { 121.006f, 173.714f },
  687. { 183.998f, 168.806f }, { 88.9095f, 159.731f }, { 100.559f, 149.867f }, { 58.553f, 146.47f }, { 112.849f, 139.302f },
  688. { 80.0968f, 125.74f }, { 39.24f, 123.671f }, { 154.582f, 103.85f }, { 59.7699f, 101.49f }, { 266.334f, 385.387f },
  689. { 234.053f, 368.718f }, { 263.347f, 361.184f }, { 244.763f, 339.958f }, { 198.16f, 328.214f }, { 211.675f, 323.407f },
  690. { 225.905f, 318.426f }, { 192.98f, 302.119f }, { 221.267f, 290.693f }, { 161.437f, 286.46f }, { 236.656f, 284.476f },
  691. { 168.023f, 251.799f }, { 105.385f, 221.988f }, { 116.724f, 214.25f }, { 97.2959f, 191.81f }, { 108.89f, 183.05f },
  692. { 77.9896f, 169.242f }, { 48.6763f, 156.088f }, { 68.9635f, 136.415f }, { 29.8484f, 133.886f }, { 49.1966f, 112.826f },
  693. { 113.059f, 29.003f }, { 251.698f, 388.562f }, { 281.689f, 381.929f }, { 297.875f, 378.518f }, { 248.376f, 365.025f },
  694. { 295.791f, 352.763f }, { 216.176f, 348.586f }, { 230.143f, 344.443f }, { 179.89f, 307.457f }, { 174.083f, 280.51f },
  695. { 142.867f, 265.085f }, { 155.127f, 258.692f }, { 124.187f, 243.661f }, { 136.01f, 236.553f }, { 86.4651f, 200.13f },
  696. { 67.5711f, 178.221f }
  697. };
  698. Mat candidates(121, 1, CV_32FC2, (void*)pts_);
  699. Size patternSize(13, 8);
  700. std::vector< Point2f > result;
  701. bool res = false;
  702. EXPECT_NO_THROW(res = findCirclesGrid(candidates, patternSize, result, CALIB_CB_SYMMETRIC_GRID, Ptr<FeatureDetector>()/*blobDetector=NULL*/));
  703. EXPECT_FALSE(res);
  704. }
  705. TEST(Calib3d_RotatedCirclesPatternDetector, issue_24964)
  706. {
  707. string path = cvtest::findDataFile("cv/cameracalibration/circles/circles_24964.png");
  708. Mat image = cv::imread(path);
  709. ASSERT_FALSE(image.empty()) << "Can't read image: " << path;
  710. vector<Point2f> centers;
  711. Size parrernSize(7, 6);
  712. Mat goldCenters(parrernSize.height, parrernSize.width, CV_32FC2);
  713. Point2f firstGoldCenter(380.f, 430.f);
  714. for (int i = 0; i < parrernSize.height; i++)
  715. {
  716. for (int j = 0; j < parrernSize.width; j++)
  717. {
  718. goldCenters.at<Point2f>(i, j) = Point2f(firstGoldCenter.x + j * 100.f, firstGoldCenter.y + i * 100.f);
  719. }
  720. }
  721. bool found = false;
  722. found = findCirclesGrid(image, parrernSize, centers, CALIB_CB_SYMMETRIC_GRID);
  723. EXPECT_TRUE(found);
  724. ASSERT_EQ(centers.size(), (size_t)parrernSize.area());
  725. double error = calcError(centers, goldCenters);
  726. EXPECT_LE(error, precise_success_error_level);
  727. // "rotate" the circle grid by 90 degrees
  728. swap(parrernSize.height, parrernSize.width);
  729. found = findCirclesGrid(image, parrernSize, centers, CALIB_CB_SYMMETRIC_GRID);
  730. error = calcError(centers, goldCenters.t());
  731. EXPECT_TRUE(found);
  732. ASSERT_EQ(centers.size(), (size_t)parrernSize.area());
  733. EXPECT_LE(error, precise_success_error_level);
  734. }
  735. TEST(Calib3d_CornerOrdering, issue_26830) {
  736. const cv::String dataDir = string(TS::ptr()->get_data_path()) + "cv/cameracalibration/";
  737. const cv::Mat image = cv::imread(dataDir + "checkerboard_marker_white.png");
  738. std::vector<Point2f> cornersMinimumSizeMatchesPatternSize;
  739. ASSERT_TRUE(cv::findChessboardCornersSB(image, Size(14, 9), cornersMinimumSizeMatchesPatternSize, CALIB_CB_MARKER | CALIB_CB_LARGER));
  740. std::vector<Point2f> cornersMinimumSizeSmallerThanPatternSize;
  741. ASSERT_TRUE(cv::findChessboardCornersSB(image, Size(4, 4), cornersMinimumSizeSmallerThanPatternSize, CALIB_CB_MARKER | CALIB_CB_LARGER));
  742. ASSERT_EQ(cornersMinimumSizeMatchesPatternSize, cornersMinimumSizeSmallerThanPatternSize);
  743. }
  744. }} // namespace
  745. /* End of file. */