test_charucodetection.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883
  1. /*
  2. By downloading, copying, installing or using the software you agree to this
  3. license. If you do not agree to this license, do not download, install,
  4. copy or use the software.
  5. License Agreement
  6. For Open Source Computer Vision Library
  7. (3-clause BSD License)
  8. Copyright (C) 2013, OpenCV Foundation, all rights reserved.
  9. Third party copyrights are property of their respective owners.
  10. Redistribution and use in source and binary forms, with or without modification,
  11. are permitted provided that the following conditions are met:
  12. * Redistributions of source code must retain the above copyright notice,
  13. this list of conditions and the following disclaimer.
  14. * Redistributions in binary form must reproduce the above copyright notice,
  15. this list of conditions and the following disclaimer in the documentation
  16. and/or other materials provided with the distribution.
  17. * Neither the names of the copyright holders nor the names of the contributors
  18. may be used to endorse or promote products derived from this software
  19. without specific prior written permission.
  20. This software is provided by the copyright holders and contributors "as is" and
  21. any express or implied warranties, including, but not limited to, the implied
  22. warranties of merchantability and fitness for a particular purpose are
  23. disclaimed. In no event shall copyright holders or contributors be liable for
  24. any direct, indirect, incidental, special, exemplary, or consequential damages
  25. (including, but not limited to, procurement of substitute goods or services;
  26. loss of use, data, or profits; or business interruption) however caused
  27. and on any theory of liability, whether in contract, strict liability,
  28. or tort (including negligence or otherwise) arising in any way out of
  29. the use of this software, even if advised of the possibility of such damage.
  30. */
  31. #include "test_precomp.hpp"
  32. namespace opencv_test { namespace {
  33. static double deg2rad(double deg) { return deg * CV_PI / 180.; }
  34. /**
  35. * @brief Get rvec and tvec from yaw, pitch and distance
  36. */
  37. static void getSyntheticRT(double yaw, double pitch, double distance, Mat &rvec, Mat &tvec) {
  38. rvec = Mat(3, 1, CV_64FC1);
  39. tvec = Mat(3, 1, CV_64FC1);
  40. // Rvec
  41. // first put the Z axis aiming to -X (like the camera axis system)
  42. Mat rotZ(3, 1, CV_64FC1);
  43. rotZ.ptr< double >(0)[0] = 0;
  44. rotZ.ptr< double >(0)[1] = 0;
  45. rotZ.ptr< double >(0)[2] = -0.5 * CV_PI;
  46. Mat rotX(3, 1, CV_64FC1);
  47. rotX.ptr< double >(0)[0] = 0.5 * CV_PI;
  48. rotX.ptr< double >(0)[1] = 0;
  49. rotX.ptr< double >(0)[2] = 0;
  50. Mat camRvec, camTvec;
  51. composeRT(rotZ, Mat(3, 1, CV_64FC1, Scalar::all(0)), rotX, Mat(3, 1, CV_64FC1, Scalar::all(0)),
  52. camRvec, camTvec);
  53. // now pitch and yaw angles
  54. Mat rotPitch(3, 1, CV_64FC1);
  55. rotPitch.ptr< double >(0)[0] = 0;
  56. rotPitch.ptr< double >(0)[1] = pitch;
  57. rotPitch.ptr< double >(0)[2] = 0;
  58. Mat rotYaw(3, 1, CV_64FC1);
  59. rotYaw.ptr< double >(0)[0] = yaw;
  60. rotYaw.ptr< double >(0)[1] = 0;
  61. rotYaw.ptr< double >(0)[2] = 0;
  62. composeRT(rotPitch, Mat(3, 1, CV_64FC1, Scalar::all(0)), rotYaw,
  63. Mat(3, 1, CV_64FC1, Scalar::all(0)), rvec, tvec);
  64. // compose both rotations
  65. composeRT(camRvec, Mat(3, 1, CV_64FC1, Scalar::all(0)), rvec,
  66. Mat(3, 1, CV_64FC1, Scalar::all(0)), rvec, tvec);
  67. // Tvec, just move in z (camera) direction the specific distance
  68. tvec.ptr< double >(0)[0] = 0.;
  69. tvec.ptr< double >(0)[1] = 0.;
  70. tvec.ptr< double >(0)[2] = distance;
  71. }
  72. /**
  73. * @brief Project a synthetic marker
  74. */
  75. static void projectMarker(Mat &img, Ptr<aruco::Dictionary> dictionary, int id,
  76. vector< Point3f > markerObjPoints, Mat cameraMatrix, Mat rvec, Mat tvec,
  77. int markerBorder) {
  78. Mat markerImg;
  79. const int markerSizePixels = 100;
  80. aruco::drawMarker(dictionary, id, markerSizePixels, markerImg, markerBorder);
  81. Mat distCoeffs(5, 1, CV_64FC1, Scalar::all(0));
  82. vector< Point2f > corners;
  83. projectPoints(markerObjPoints, rvec, tvec, cameraMatrix, distCoeffs, corners);
  84. vector< Point2f > originalCorners;
  85. originalCorners.push_back(Point2f(0, 0));
  86. originalCorners.push_back(Point2f((float)markerSizePixels, 0));
  87. originalCorners.push_back(Point2f((float)markerSizePixels, (float)markerSizePixels));
  88. originalCorners.push_back(Point2f(0, (float)markerSizePixels));
  89. Mat transformation = getPerspectiveTransform(originalCorners, corners);
  90. Mat aux;
  91. const char borderValue = 127;
  92. warpPerspective(markerImg, aux, transformation, img.size(), INTER_NEAREST, BORDER_CONSTANT,
  93. Scalar::all(borderValue));
  94. // copy only not-border pixels
  95. for(int y = 0; y < aux.rows; y++) {
  96. for(int x = 0; x < aux.cols; x++) {
  97. if(aux.at< unsigned char >(y, x) == borderValue) continue;
  98. img.at< unsigned char >(y, x) = aux.at< unsigned char >(y, x);
  99. }
  100. }
  101. }
  102. /**
  103. * @brief Get a synthetic image of Chessboard in perspective
  104. */
  105. static Mat projectChessboard(int squaresX, int squaresY, float squareSize, Size imageSize,
  106. Mat cameraMatrix, Mat rvec, Mat tvec) {
  107. Mat img(imageSize, CV_8UC1, Scalar::all(255));
  108. Mat distCoeffs(5, 1, CV_64FC1, Scalar::all(0));
  109. for(int y = 0; y < squaresY; y++) {
  110. float startY = float(y) * squareSize;
  111. for(int x = 0; x < squaresX; x++) {
  112. if(y % 2 != x % 2) continue;
  113. float startX = float(x) * squareSize;
  114. vector< Point3f > squareCorners;
  115. squareCorners.push_back(Point3f(startX, startY, 0));
  116. squareCorners.push_back(squareCorners[0] + Point3f(squareSize, 0, 0));
  117. squareCorners.push_back(squareCorners[0] + Point3f(squareSize, squareSize, 0));
  118. squareCorners.push_back(squareCorners[0] + Point3f(0, squareSize, 0));
  119. vector< vector< Point2f > > projectedCorners;
  120. projectedCorners.push_back(vector< Point2f >());
  121. projectPoints(squareCorners, rvec, tvec, cameraMatrix, distCoeffs, projectedCorners[0]);
  122. vector< vector< Point > > projectedCornersInt;
  123. projectedCornersInt.push_back(vector< Point >());
  124. for(int k = 0; k < 4; k++)
  125. projectedCornersInt[0]
  126. .push_back(Point((int)projectedCorners[0][k].x, (int)projectedCorners[0][k].y));
  127. fillPoly(img, projectedCornersInt, Scalar::all(0));
  128. }
  129. }
  130. return img;
  131. }
  132. /**
  133. * @brief Check pose estimation of charuco board
  134. */
  135. static Mat projectCharucoBoard(Ptr<aruco::CharucoBoard> &board, Mat cameraMatrix, double yaw,
  136. double pitch, double distance, Size imageSize, int markerBorder,
  137. Mat &rvec, Mat &tvec) {
  138. getSyntheticRT(yaw, pitch, distance, rvec, tvec);
  139. // project markers
  140. Mat img = Mat(imageSize, CV_8UC1, Scalar::all(255));
  141. for(unsigned int m = 0; m < board->ids.size(); m++) {
  142. projectMarker(img, board->dictionary, board->ids[m], board->objPoints[m], cameraMatrix, rvec,
  143. tvec, markerBorder);
  144. }
  145. // project chessboard
  146. Mat chessboard =
  147. projectChessboard(board->getChessboardSize().width, board->getChessboardSize().height,
  148. board->getSquareLength(), imageSize, cameraMatrix, rvec, tvec);
  149. for(unsigned int i = 0; i < chessboard.total(); i++) {
  150. if(chessboard.ptr< unsigned char >()[i] == 0) {
  151. img.ptr< unsigned char >()[i] = 0;
  152. }
  153. }
  154. return img;
  155. }
  156. /**
  157. * @brief Check Charuco detection
  158. */
  159. class CV_CharucoDetection : public cvtest::BaseTest {
  160. public:
  161. CV_CharucoDetection();
  162. protected:
  163. void run(int);
  164. };
  165. CV_CharucoDetection::CV_CharucoDetection() {}
  166. void CV_CharucoDetection::run(int) {
  167. int iter = 0;
  168. Mat cameraMatrix = Mat::eye(3, 3, CV_64FC1);
  169. Size imgSize(500, 500);
  170. Ptr<aruco::Dictionary> dictionary = aruco::getPredefinedDictionary(aruco::DICT_6X6_250);
  171. Ptr<aruco::CharucoBoard> board = aruco::CharucoBoard::create(4, 4, 0.03f, 0.015f, dictionary);
  172. cameraMatrix.at< double >(0, 0) = cameraMatrix.at< double >(1, 1) = 650;
  173. cameraMatrix.at< double >(0, 2) = imgSize.width / 2;
  174. cameraMatrix.at< double >(1, 2) = imgSize.height / 2;
  175. Mat distCoeffs(5, 1, CV_64FC1, Scalar::all(0));
  176. // for different perspectives
  177. for(double distance = 0.2; distance <= 0.4; distance += 0.2) {
  178. for(int yaw = 0; yaw < 360; yaw += 100) {
  179. for(int pitch = 30; pitch <= 90; pitch += 50) {
  180. int markerBorder = iter % 2 + 1;
  181. iter++;
  182. // create synthetic image
  183. Mat rvec, tvec;
  184. Mat img = projectCharucoBoard(board, cameraMatrix, deg2rad(pitch), deg2rad(yaw),
  185. distance, imgSize, markerBorder, rvec, tvec);
  186. // detect markers
  187. vector< vector< Point2f > > corners;
  188. vector< int > ids;
  189. Ptr<aruco::DetectorParameters> params = aruco::DetectorParameters::create();
  190. params->minDistanceToBorder = 3;
  191. params->markerBorderBits = markerBorder;
  192. aruco::detectMarkers(img, dictionary, corners, ids, params);
  193. if(ids.size() == 0) {
  194. ts->printf(cvtest::TS::LOG, "Marker detection failed");
  195. ts->set_failed_test_info(cvtest::TS::FAIL_MISMATCH);
  196. return;
  197. }
  198. // interpolate charuco corners
  199. vector< Point2f > charucoCorners;
  200. vector< int > charucoIds;
  201. if(iter % 2 == 0) {
  202. aruco::interpolateCornersCharuco(corners, ids, img, board, charucoCorners,
  203. charucoIds);
  204. } else {
  205. aruco::interpolateCornersCharuco(corners, ids, img, board, charucoCorners,
  206. charucoIds, cameraMatrix, distCoeffs);
  207. }
  208. // check results
  209. vector< Point2f > projectedCharucoCorners;
  210. projectPoints(board->chessboardCorners, rvec, tvec, cameraMatrix, distCoeffs,
  211. projectedCharucoCorners);
  212. for(unsigned int i = 0; i < charucoIds.size(); i++) {
  213. int currentId = charucoIds[i];
  214. if(currentId >= (int)board->chessboardCorners.size()) {
  215. ts->printf(cvtest::TS::LOG, "Invalid Charuco corner id");
  216. ts->set_failed_test_info(cvtest::TS::FAIL_MISMATCH);
  217. return;
  218. }
  219. double repError = cv::norm(charucoCorners[i] - projectedCharucoCorners[currentId]); // TODO cvtest
  220. if(repError > 5.) {
  221. ts->printf(cvtest::TS::LOG, "Charuco corner reprojection error too high");
  222. ts->set_failed_test_info(cvtest::TS::FAIL_MISMATCH);
  223. return;
  224. }
  225. }
  226. }
  227. }
  228. }
  229. }
  230. /**
  231. * @brief Check charuco pose estimation
  232. */
  233. class CV_CharucoPoseEstimation : public cvtest::BaseTest {
  234. public:
  235. CV_CharucoPoseEstimation();
  236. protected:
  237. void run(int);
  238. };
  239. CV_CharucoPoseEstimation::CV_CharucoPoseEstimation() {}
  240. void CV_CharucoPoseEstimation::run(int) {
  241. int iter = 0;
  242. Mat cameraMatrix = Mat::eye(3, 3, CV_64FC1);
  243. Size imgSize(500, 500);
  244. Ptr<aruco::Dictionary> dictionary = aruco::getPredefinedDictionary(aruco::DICT_6X6_250);
  245. Ptr<aruco::CharucoBoard> board = aruco::CharucoBoard::create(4, 4, 0.03f, 0.015f, dictionary);
  246. cameraMatrix.at< double >(0, 0) = cameraMatrix.at< double >(1, 1) = 650;
  247. cameraMatrix.at< double >(0, 2) = imgSize.width / 2;
  248. cameraMatrix.at< double >(1, 2) = imgSize.height / 2;
  249. Mat distCoeffs(5, 1, CV_64FC1, Scalar::all(0));
  250. // for different perspectives
  251. for(double distance = 0.2; distance <= 0.4; distance += 0.2) {
  252. for(int yaw = 0; yaw < 360; yaw += 100) {
  253. for(int pitch = 30; pitch <= 90; pitch += 50) {
  254. int markerBorder = iter % 2 + 1;
  255. iter++;
  256. // get synthetic image
  257. Mat rvec, tvec;
  258. Mat img = projectCharucoBoard(board, cameraMatrix, deg2rad(pitch), deg2rad(yaw),
  259. distance, imgSize, markerBorder, rvec, tvec);
  260. // detect markers
  261. vector< vector< Point2f > > corners;
  262. vector< int > ids;
  263. Ptr<aruco::DetectorParameters> params = aruco::DetectorParameters::create();
  264. params->minDistanceToBorder = 3;
  265. params->markerBorderBits = markerBorder;
  266. aruco::detectMarkers(img, dictionary, corners, ids, params);
  267. if(ids.size() == 0) {
  268. ts->printf(cvtest::TS::LOG, "Marker detection failed");
  269. ts->set_failed_test_info(cvtest::TS::FAIL_MISMATCH);
  270. return;
  271. }
  272. // interpolate charuco corners
  273. vector< Point2f > charucoCorners;
  274. vector< int > charucoIds;
  275. if(iter % 2 == 0) {
  276. aruco::interpolateCornersCharuco(corners, ids, img, board, charucoCorners,
  277. charucoIds);
  278. } else {
  279. aruco::interpolateCornersCharuco(corners, ids, img, board, charucoCorners,
  280. charucoIds, cameraMatrix, distCoeffs);
  281. }
  282. if(charucoIds.size() == 0) continue;
  283. // estimate charuco pose
  284. aruco::estimatePoseCharucoBoard(charucoCorners, charucoIds, board, cameraMatrix,
  285. distCoeffs, rvec, tvec);
  286. // check result
  287. vector< Point2f > projectedCharucoCorners;
  288. projectPoints(board->chessboardCorners, rvec, tvec, cameraMatrix, distCoeffs,
  289. projectedCharucoCorners);
  290. for(unsigned int i = 0; i < charucoIds.size(); i++) {
  291. int currentId = charucoIds[i];
  292. if(currentId >= (int)board->chessboardCorners.size()) {
  293. ts->printf(cvtest::TS::LOG, "Invalid Charuco corner id");
  294. ts->set_failed_test_info(cvtest::TS::FAIL_MISMATCH);
  295. return;
  296. }
  297. double repError = cv::norm(charucoCorners[i] - projectedCharucoCorners[currentId]); // TODO cvtest
  298. if(repError > 5.) {
  299. ts->printf(cvtest::TS::LOG, "Charuco corner reprojection error too high");
  300. ts->set_failed_test_info(cvtest::TS::FAIL_MISMATCH);
  301. return;
  302. }
  303. }
  304. }
  305. }
  306. }
  307. }
  308. /**
  309. * @brief Check diamond detection
  310. */
  311. class CV_CharucoDiamondDetection : public cvtest::BaseTest {
  312. public:
  313. CV_CharucoDiamondDetection();
  314. protected:
  315. void run(int);
  316. };
  317. CV_CharucoDiamondDetection::CV_CharucoDiamondDetection() {}
  318. void CV_CharucoDiamondDetection::run(int) {
  319. int iter = 0;
  320. Mat cameraMatrix = Mat::eye(3, 3, CV_64FC1);
  321. Size imgSize(500, 500);
  322. Ptr<aruco::Dictionary> dictionary = aruco::getPredefinedDictionary(aruco::DICT_6X6_250);
  323. float squareLength = 0.03f;
  324. float markerLength = 0.015f;
  325. Ptr<aruco::CharucoBoard> board =
  326. aruco::CharucoBoard::create(3, 3, squareLength, markerLength, dictionary);
  327. cameraMatrix.at< double >(0, 0) = cameraMatrix.at< double >(1, 1) = 650;
  328. cameraMatrix.at< double >(0, 2) = imgSize.width / 2;
  329. cameraMatrix.at< double >(1, 2) = imgSize.height / 2;
  330. Mat distCoeffs(5, 1, CV_64FC1, Scalar::all(0));
  331. // for different perspectives
  332. for(double distance = 0.3; distance <= 0.3; distance += 0.2) {
  333. for(int yaw = 0; yaw < 360; yaw += 100) {
  334. for(int pitch = 30; pitch <= 90; pitch += 30) {
  335. int markerBorder = iter % 2 + 1;
  336. for(int i = 0; i < 4; i++)
  337. board->ids[i] = 4 * iter + i;
  338. iter++;
  339. // get synthetic image
  340. Mat rvec, tvec;
  341. Mat img = projectCharucoBoard(board, cameraMatrix, deg2rad(pitch), deg2rad(yaw),
  342. distance, imgSize, markerBorder, rvec, tvec);
  343. // detect markers
  344. vector< vector< Point2f > > corners;
  345. vector< int > ids;
  346. Ptr<aruco::DetectorParameters> params = aruco::DetectorParameters::create();
  347. params->minDistanceToBorder = 0;
  348. params->markerBorderBits = markerBorder;
  349. aruco::detectMarkers(img, dictionary, corners, ids, params);
  350. if(ids.size() != 4) {
  351. ts->printf(cvtest::TS::LOG, "Not enough markers for diamond detection");
  352. ts->set_failed_test_info(cvtest::TS::FAIL_MISMATCH);
  353. return;
  354. }
  355. // detect diamonds
  356. vector< vector< Point2f > > diamondCorners;
  357. vector< Vec4i > diamondIds;
  358. aruco::detectCharucoDiamond(img, corners, ids, squareLength / markerLength,
  359. diamondCorners, diamondIds, cameraMatrix, distCoeffs);
  360. // check results
  361. if(diamondIds.size() != 1) {
  362. ts->printf(cvtest::TS::LOG, "Diamond not detected correctly");
  363. ts->set_failed_test_info(cvtest::TS::FAIL_MISMATCH);
  364. return;
  365. }
  366. for(int i = 0; i < 4; i++) {
  367. if(diamondIds[0][i] != board->ids[i]) {
  368. ts->printf(cvtest::TS::LOG, "Incorrect diamond ids");
  369. ts->set_failed_test_info(cvtest::TS::FAIL_MISMATCH);
  370. return;
  371. }
  372. }
  373. vector< Point2f > projectedDiamondCorners;
  374. projectPoints(board->chessboardCorners, rvec, tvec, cameraMatrix, distCoeffs,
  375. projectedDiamondCorners);
  376. vector< Point2f > projectedDiamondCornersReorder(4);
  377. projectedDiamondCornersReorder[0] = projectedDiamondCorners[2];
  378. projectedDiamondCornersReorder[1] = projectedDiamondCorners[3];
  379. projectedDiamondCornersReorder[2] = projectedDiamondCorners[1];
  380. projectedDiamondCornersReorder[3] = projectedDiamondCorners[0];
  381. for(unsigned int i = 0; i < 4; i++) {
  382. double repError = cv::norm(diamondCorners[0][i] - projectedDiamondCornersReorder[i]); // TODO cvtest
  383. if(repError > 5.) {
  384. ts->printf(cvtest::TS::LOG, "Diamond corner reprojection error too high");
  385. ts->set_failed_test_info(cvtest::TS::FAIL_MISMATCH);
  386. return;
  387. }
  388. }
  389. // estimate diamond pose
  390. vector< Vec3d > estimatedRvec, estimatedTvec;
  391. aruco::estimatePoseSingleMarkers(diamondCorners, squareLength, cameraMatrix,
  392. distCoeffs, estimatedRvec, estimatedTvec);
  393. // check result
  394. vector< Point2f > projectedDiamondCornersPose;
  395. vector< Vec3f > diamondObjPoints(4);
  396. diamondObjPoints[0] = Vec3f(-squareLength / 2.f, squareLength / 2.f, 0);
  397. diamondObjPoints[1] = Vec3f(squareLength / 2.f, squareLength / 2.f, 0);
  398. diamondObjPoints[2] = Vec3f(squareLength / 2.f, -squareLength / 2.f, 0);
  399. diamondObjPoints[3] = Vec3f(-squareLength / 2.f, -squareLength / 2.f, 0);
  400. projectPoints(diamondObjPoints, estimatedRvec[0], estimatedTvec[0], cameraMatrix,
  401. distCoeffs, projectedDiamondCornersPose);
  402. for(unsigned int i = 0; i < 4; i++) {
  403. double repError = cv::norm(projectedDiamondCornersReorder[i] - projectedDiamondCornersPose[i]); // TODO cvtest
  404. if(repError > 5.) {
  405. ts->printf(cvtest::TS::LOG, "Charuco pose error too high");
  406. ts->set_failed_test_info(cvtest::TS::FAIL_MISMATCH);
  407. return;
  408. }
  409. }
  410. }
  411. }
  412. }
  413. }
  414. /**
  415. * @brief Check charuco board creation
  416. */
  417. class CV_CharucoBoardCreation : public cvtest::BaseTest {
  418. public:
  419. CV_CharucoBoardCreation();
  420. protected:
  421. void run(int);
  422. };
  423. CV_CharucoBoardCreation::CV_CharucoBoardCreation() {}
  424. void CV_CharucoBoardCreation::run(int)
  425. {
  426. Ptr<aruco::Dictionary> dictionary = aruco::getPredefinedDictionary(aruco::DICT_5X5_250);
  427. int n = 6;
  428. float markerSizeFactor = 0.5f;
  429. for (float squareSize_mm = 5.0f; squareSize_mm < 35.0f; squareSize_mm += 0.1f)
  430. {
  431. Ptr<aruco::CharucoBoard> board_meters = aruco::CharucoBoard::create(
  432. n, n, squareSize_mm*1e-3f, squareSize_mm * markerSizeFactor * 1e-3f, dictionary);
  433. Ptr<aruco::CharucoBoard> board_millimeters = aruco::CharucoBoard::create(
  434. n, n, squareSize_mm, squareSize_mm * markerSizeFactor, dictionary);
  435. for (size_t i = 0; i < board_meters->nearestMarkerIdx.size(); i++)
  436. {
  437. if (board_meters->nearestMarkerIdx[i].size() != board_millimeters->nearestMarkerIdx[i].size() ||
  438. board_meters->nearestMarkerIdx[i][0] != board_millimeters->nearestMarkerIdx[i][0])
  439. {
  440. ts->printf(cvtest::TS::LOG,
  441. cv::format("Charuco board topology is sensitive to scale with squareSize=%.1f\n",
  442. squareSize_mm).c_str());
  443. ts->set_failed_test_info(cvtest::TS::FAIL_INVALID_OUTPUT);
  444. break;
  445. }
  446. }
  447. }
  448. }
  449. TEST(CV_CharucoDetection, accuracy) {
  450. CV_CharucoDetection test;
  451. test.safe_run();
  452. }
  453. TEST(CV_CharucoPoseEstimation, accuracy) {
  454. CV_CharucoPoseEstimation test;
  455. test.safe_run();
  456. }
  457. TEST(CV_CharucoDiamondDetection, accuracy) {
  458. CV_CharucoDiamondDetection test;
  459. test.safe_run();
  460. }
  461. TEST(CV_CharucoBoardCreation, accuracy) {
  462. CV_CharucoBoardCreation test;
  463. test.safe_run();
  464. }
  465. TEST(Charuco, testCharucoCornersCollinear_true)
  466. {
  467. int squaresX = 13;
  468. int squaresY = 28;
  469. float squareLength = 300;
  470. float markerLength = 150;
  471. int dictionaryId = 11;
  472. Ptr<aruco::DetectorParameters> detectorParams = aruco::DetectorParameters::create();
  473. Ptr<aruco::Dictionary> dictionary =
  474. aruco::getPredefinedDictionary(aruco::PREDEFINED_DICTIONARY_NAME(dictionaryId));
  475. Ptr<aruco::CharucoBoard> charucoBoard =
  476. aruco::CharucoBoard::create(squaresX, squaresY, squareLength, markerLength, dictionary);
  477. // consistency with C++98
  478. const int arrLine[9] = {192, 204, 216, 228, 240, 252, 264, 276, 288};
  479. vector<int> charucoIdsAxisLine(9, 0);
  480. for (int i = 0; i < 9; i++){
  481. charucoIdsAxisLine[i] = arrLine[i];
  482. }
  483. const int arrDiag[7] = {198, 209, 220, 231, 242, 253, 264};
  484. vector<int> charucoIdsDiagonalLine(7, 0);
  485. for (int i = 0; i < 7; i++){
  486. charucoIdsDiagonalLine[i] = arrDiag[i];
  487. }
  488. bool resultAxisLine = cv::aruco::testCharucoCornersCollinear(charucoBoard, charucoIdsAxisLine);
  489. bool resultDiagonalLine = cv::aruco::testCharucoCornersCollinear(charucoBoard, charucoIdsDiagonalLine);
  490. EXPECT_TRUE(resultAxisLine);
  491. EXPECT_TRUE(resultDiagonalLine);
  492. }
  493. TEST(Charuco, testCharucoCornersCollinear_false)
  494. {
  495. int squaresX = 13;
  496. int squaresY = 28;
  497. float squareLength = 300;
  498. float markerLength = 150;
  499. int dictionaryId = 11;
  500. Ptr<aruco::DetectorParameters> detectorParams = aruco::DetectorParameters::create();
  501. Ptr<aruco::Dictionary> dictionary =
  502. aruco::getPredefinedDictionary(aruco::PREDEFINED_DICTIONARY_NAME(dictionaryId));
  503. Ptr<aruco::CharucoBoard> charucoBoard =
  504. aruco::CharucoBoard::create(squaresX, squaresY, squareLength, markerLength, dictionary);
  505. // consistency with C++98
  506. const int arr[63] = {192, 193, 194, 195, 196, 197, 198, 204, 205, 206, 207, 208,
  507. 209, 210, 216, 217, 218, 219, 220, 221, 222, 228, 229, 230,
  508. 231, 232, 233, 234, 240, 241, 242, 243, 244, 245, 246, 252,
  509. 253, 254, 255, 256, 257, 258, 264, 265, 266, 267, 268, 269,
  510. 270, 276, 277, 278, 279, 280, 281, 282, 288, 289, 290, 291,
  511. 292, 293, 294};
  512. vector<int> charucoIds(63, 0);
  513. for (int i = 0; i < 63; i++){
  514. charucoIds[i] = arr[i];
  515. }
  516. bool result = cv::aruco::testCharucoCornersCollinear(charucoBoard, charucoIds);
  517. EXPECT_FALSE(result);
  518. }
  519. // test that ChArUco board detection is subpixel accurate
  520. TEST(Charuco, testBoardSubpixelCoords)
  521. {
  522. cv::Size res{500, 500};
  523. cv::Mat K = (cv::Mat_<double>(3,3) <<
  524. 0.5*res.width, 0, 0.5*res.width,
  525. 0, 0.5*res.height, 0.5*res.height,
  526. 0, 0, 1);
  527. // load board image with corners at round values
  528. cv::String testImagePath = cvtest::TS::ptr()->get_data_path() + "aruco/" + "trivial_board_detection.png";
  529. Mat img = imread(testImagePath);
  530. cv::Mat expected_corners = (cv::Mat_<float>(9,2) <<
  531. 200, 300,
  532. 250, 300,
  533. 300, 300,
  534. 200, 250,
  535. 250, 250,
  536. 300, 250,
  537. 200, 200,
  538. 250, 200,
  539. 300, 200
  540. );
  541. cv::Mat gray;
  542. cv::cvtColor(img, gray, cv::COLOR_BGR2GRAY);
  543. auto dict = cv::aruco::getPredefinedDictionary(cv::aruco::DICT_APRILTAG_36h11);
  544. auto board = cv::aruco::CharucoBoard::create(4, 4, 1.f, .8f, dict);
  545. auto params = cv::aruco::DetectorParameters::create();
  546. params->cornerRefinementMethod = cv::aruco::CORNER_REFINE_APRILTAG;
  547. std::vector<int> ids;
  548. std::vector<std::vector<cv::Point2f>> corners, rejected;
  549. cv::aruco::detectMarkers(gray, dict, corners, ids, params, rejected, K);
  550. ASSERT_EQ(ids.size(), size_t(8));
  551. cv::Mat c_ids, c_corners;
  552. cv::aruco::interpolateCornersCharuco(corners, ids, gray, board, c_corners, c_ids, K);
  553. cv::Mat corners_reshaped = c_corners.reshape(1);
  554. ASSERT_EQ(c_corners.rows, expected_corners.rows);
  555. EXPECT_NEAR(0, cvtest::norm(expected_corners, c_corners.reshape(1), NORM_INF), 1e-3);
  556. c_ids = cv::Mat();
  557. c_corners = cv::Mat();
  558. cv::aruco::interpolateCornersCharuco(corners, ids, gray, board, c_corners, c_ids);
  559. corners_reshaped = c_corners.reshape(1);
  560. ASSERT_EQ(c_corners.rows, expected_corners.rows);
  561. EXPECT_NEAR(0, cvtest::norm(expected_corners, c_corners.reshape(1), NORM_INF), 1e-3);
  562. }
  563. TEST(CV_ArucoTutorial, can_find_choriginal)
  564. {
  565. string imgPath = cvtest::findDataFile("choriginal.jpg", false);
  566. Mat image = imread(imgPath);
  567. cv::Ptr<cv::aruco::Dictionary> dictionary = aruco::getPredefinedDictionary(aruco::DICT_6X6_250);
  568. Ptr<aruco::DetectorParameters> detectorParams = aruco::DetectorParameters::create();
  569. vector< int > ids;
  570. vector< vector< Point2f > > corners, rejected;
  571. const size_t N = 17ull;
  572. // corners of aruco markers with indices goldCornersIds
  573. const int goldCorners[N][8] = { {268,77, 290,80, 286,97, 263,94}, {360,90, 382,93, 379,111, 357,108},
  574. {211,106, 233,109, 228,127, 205,123}, {306,120, 328,124, 325,142, 302,138},
  575. {402,135, 425,139, 423,157, 400,154}, {247,152, 271,155, 267,174, 242,171},
  576. {347,167, 371,171, 369,191, 344,187}, {185,185, 209,189, 203,210, 178,206},
  577. {288,201, 313,206, 309,227, 284,223}, {393,218, 418,222, 416,245, 391,241},
  578. {223,240, 250,244, 244,268, 217,263}, {333,258, 359,262, 356,286, 329,282},
  579. {152,281, 179,285, 171,312, 143,307}, {267,300, 294,305, 289,331, 261,327},
  580. {383,319, 410,324, 408,351, 380,347}, {194,347, 223,352, 216,382, 186,377},
  581. {315,368, 345,373, 341,403, 310,398} };
  582. map<int, const int*> mapGoldCorners;
  583. for (int i = 0; i < static_cast<int>(N); i++)
  584. mapGoldCorners[i] = goldCorners[i];
  585. aruco::detectMarkers(image, dictionary, corners, ids, detectorParams, rejected);
  586. ASSERT_EQ(N, ids.size());
  587. for (size_t i = 0; i < N; i++)
  588. {
  589. int arucoId = ids[i];
  590. ASSERT_EQ(4ull, corners[i].size());
  591. ASSERT_TRUE(mapGoldCorners.find(arucoId) != mapGoldCorners.end());
  592. for (int j = 0; j < 4; j++)
  593. {
  594. EXPECT_NEAR(static_cast<float>(mapGoldCorners[arucoId][j * 2]), corners[i][j].x, 1.f);
  595. EXPECT_NEAR(static_cast<float>(mapGoldCorners[arucoId][j * 2 + 1]), corners[i][j].y, 1.f);
  596. }
  597. }
  598. }
  599. TEST(CV_ArucoTutorial, can_find_chocclusion)
  600. {
  601. string imgPath = cvtest::findDataFile("chocclusion_original.jpg", false);
  602. Mat image = imread(imgPath);
  603. cv::Ptr<cv::aruco::Dictionary> dictionary = aruco::getPredefinedDictionary(aruco::DICT_6X6_250);
  604. Ptr<aruco::DetectorParameters> detectorParams = aruco::DetectorParameters::create();
  605. vector< int > ids;
  606. vector< vector< Point2f > > corners, rejected;
  607. const size_t N = 13ull;
  608. // corners of aruco markers with indices goldCornersIds
  609. const int goldCorners[N][8] = { {301,57, 322,62, 317,79, 295,73}, {391,80, 413,85, 408,103, 386,97},
  610. {242,79, 264,85, 256,102, 234,96}, {334,103, 357,109, 352,126, 329,121},
  611. {428,129, 451,134, 448,152, 425,146}, {274,128, 296,134, 290,153, 266,147},
  612. {371,154, 394,160, 390,180, 366,174}, {208,155, 232,161, 223,181, 199,175},
  613. {309,182, 333,188, 327,209, 302,203}, {411,210, 436,216, 432,238, 407,231},
  614. {241,212, 267,219, 258,242, 232,235}, {167,244, 194,252, 183,277, 156,269},
  615. {202,314, 230,322, 220,349, 191,341} };
  616. map<int, const int*> mapGoldCorners;
  617. const int goldCornersIds[N] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 15};
  618. for (int i = 0; i < static_cast<int>(N); i++)
  619. mapGoldCorners[goldCornersIds[i]] = goldCorners[i];
  620. aruco::detectMarkers(image, dictionary, corners, ids, detectorParams, rejected);
  621. ASSERT_EQ(N, ids.size());
  622. for (size_t i = 0; i < N; i++)
  623. {
  624. int arucoId = ids[i];
  625. ASSERT_EQ(4ull, corners[i].size());
  626. ASSERT_TRUE(mapGoldCorners.find(arucoId) != mapGoldCorners.end());
  627. for (int j = 0; j < 4; j++)
  628. {
  629. EXPECT_NEAR(static_cast<float>(mapGoldCorners[arucoId][j * 2]), corners[i][j].x, 1.f);
  630. EXPECT_NEAR(static_cast<float>(mapGoldCorners[arucoId][j * 2 + 1]), corners[i][j].y, 1.f);
  631. }
  632. }
  633. }
  634. TEST(CV_ArucoTutorial, can_find_diamondmarkers)
  635. {
  636. string imgPath = cvtest::findDataFile("diamondmarkers.png", false);
  637. Mat image = imread(imgPath);
  638. string dictPath = cvtest::findDataFile("tutorial_dict.yml", false);
  639. cv::Ptr<cv::aruco::Dictionary> dictionary;
  640. FileStorage fs(dictPath, FileStorage::READ);
  641. aruco::Dictionary::readDictionary(fs.root(), dictionary); // set marker from tutorial_dict.yml
  642. string detectorPath = cvtest::findDataFile("detector_params.yml", false);
  643. fs = FileStorage(detectorPath, FileStorage::READ);
  644. Ptr<aruco::DetectorParameters> detectorParams;
  645. aruco::DetectorParameters::readDetectorParameters(fs.root(), detectorParams);
  646. detectorParams->cornerRefinementMethod = 3;
  647. vector< int > ids;
  648. vector< vector< Point2f > > corners, rejected;
  649. const size_t N = 12ull;
  650. // corner indices of ArUco markers
  651. const int goldCornersIds[N] = { 4, 12, 11, 3, 12, 10, 12, 10, 10, 11, 2, 11 };
  652. map<int, int> counterGoldCornersIds;
  653. for (int i = 0; i < static_cast<int>(N); i++)
  654. counterGoldCornersIds[goldCornersIds[i]]++;
  655. aruco::detectMarkers(image, dictionary, corners, ids, detectorParams, rejected);
  656. map<int, int> counterRes;
  657. for (size_t i = 0; i < N; i++)
  658. {
  659. int arucoId = ids[i];
  660. counterRes[arucoId]++;
  661. }
  662. ASSERT_EQ(N, ids.size());
  663. EXPECT_EQ(counterGoldCornersIds, counterRes); // check the number of ArUco markers
  664. }
  665. TEST(Charuco, issue_14014)
  666. {
  667. string imgPath = cvtest::findDataFile("aruco/recover.png");
  668. Mat img = imread(imgPath);
  669. Ptr<aruco::Dictionary> dict = aruco::getPredefinedDictionary(aruco::PREDEFINED_DICTIONARY_NAME(cv::aruco::DICT_7X7_250));
  670. Ptr<aruco::CharucoBoard> board = aruco::CharucoBoard::create(8, 5, 0.03455f, 0.02164f, dict);
  671. Ptr<aruco::DetectorParameters> detectorParams = aruco::DetectorParameters::create();
  672. detectorParams->cornerRefinementMethod = aruco::CORNER_REFINE_SUBPIX;
  673. detectorParams->cornerRefinementMinAccuracy = 0.01;
  674. vector<Mat> corners, rejectedPoints;
  675. vector<int> ids;
  676. aruco::detectMarkers(img, dict, corners, ids, detectorParams, rejectedPoints);
  677. ASSERT_EQ(corners.size(), 19ull);
  678. EXPECT_EQ(Size(4, 1), corners[0].size()); // check dimension of detected corners
  679. ASSERT_EQ(rejectedPoints.size(), 21ull);
  680. EXPECT_EQ(Size(4, 1), rejectedPoints[0].size()); // check dimension of detected corners
  681. aruco::refineDetectedMarkers(img, board, corners, ids, rejectedPoints);
  682. ASSERT_EQ(corners.size(), 20ull);
  683. EXPECT_EQ(Size(4, 1), corners[0].size()); // check dimension of rejected corners after successfully refine
  684. ASSERT_EQ(rejectedPoints.size(), 20ull);
  685. EXPECT_EQ(Size(4, 1), rejectedPoints[0].size()); // check dimension of rejected corners after successfully refine
  686. }
  687. }} // namespace