test_chesscorners.cpp 29 KB

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