detect_diamonds.cpp 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. #include <opencv2/highgui.hpp>
  2. #include <vector>
  3. #include <iostream>
  4. #include <opencv2/objdetect/charuco_detector.hpp>
  5. #include "aruco_samples_utility.hpp"
  6. using namespace std;
  7. using namespace cv;
  8. namespace {
  9. const char* about = "Detect ChArUco markers";
  10. const char* keys =
  11. "{sl | 100 | Square side length (in meters) }"
  12. "{ml | 60 | Marker side length (in meters) }"
  13. "{d | 10 | dictionary: DICT_4X4_50=0, DICT_4X4_100=1, DICT_4X4_250=2,"
  14. "DICT_4X4_1000=3, DICT_5X5_50=4, DICT_5X5_100=5, DICT_5X5_250=6, DICT_5X5_1000=7, "
  15. "DICT_6X6_50=8, DICT_6X6_100=9, DICT_6X6_250=10, DICT_6X6_1000=11, DICT_7X7_50=12,"
  16. "DICT_7X7_100=13, DICT_7X7_250=14, DICT_7X7_1000=15, DICT_ARUCO_ORIGINAL = 16}"
  17. "{cd | | Input file with custom dictionary }"
  18. "{c | | Output file with calibrated camera parameters }"
  19. "{as | | Automatic scale. The provided number is multiplied by the last"
  20. "diamond id becoming an indicator of the square length. In this case, the -sl and "
  21. "-ml are only used to know the relative length relation between squares and markers }"
  22. "{v | | Input from video file, if ommited, input comes from camera }"
  23. "{ci | 0 | Camera id if input doesnt come from video (-v) }"
  24. "{dp | | File of marker detector parameters }"
  25. "{refine | | Corner refinement: CORNER_REFINE_NONE=0, CORNER_REFINE_SUBPIX=1,"
  26. "CORNER_REFINE_CONTOUR=2, CORNER_REFINE_APRILTAG=3}";
  27. const string refineMethods[4] = {
  28. "None",
  29. "Subpixel",
  30. "Contour",
  31. "AprilTag"
  32. };
  33. }
  34. int main(int argc, char *argv[]) {
  35. CommandLineParser parser(argc, argv, keys);
  36. parser.about(about);
  37. float squareLength = parser.get<float>("sl");
  38. float markerLength = parser.get<float>("ml");
  39. bool estimatePose = parser.has("c");
  40. bool autoScale = parser.has("as");
  41. float autoScaleFactor = autoScale ? parser.get<float>("as") : 1.f;
  42. aruco::Dictionary dictionary = readDictionatyFromCommandLine(parser);
  43. Mat camMatrix, distCoeffs;
  44. readCameraParamsFromCommandLine(parser, camMatrix, distCoeffs);
  45. aruco::DetectorParameters detectorParams = readDetectorParamsFromCommandLine(parser);
  46. if (parser.has("refine")) {
  47. // override cornerRefinementMethod read from config file
  48. int user_method = parser.get<aruco::CornerRefineMethod>("refine");
  49. if (user_method < 0 || user_method >= 4)
  50. {
  51. std::cout << "Corner refinement method should be in range 0..3" << std::endl;
  52. return 0;
  53. }
  54. detectorParams.cornerRefinementMethod = user_method;
  55. }
  56. std::cout << "Corner refinement method: " << refineMethods[detectorParams.cornerRefinementMethod] << std::endl;
  57. int camId = parser.get<int>("ci");
  58. String video;
  59. if(parser.has("v")) {
  60. video = parser.get<String>("v");
  61. }
  62. if(!parser.check()) {
  63. parser.printErrors();
  64. return 0;
  65. }
  66. VideoCapture inputVideo;
  67. int waitTime;
  68. if(!video.empty()) {
  69. inputVideo.open(video);
  70. waitTime = 0;
  71. } else {
  72. inputVideo.open(camId);
  73. waitTime = 10;
  74. }
  75. double totalTime = 0;
  76. int totalIterations = 0;
  77. aruco::CharucoBoard charucoBoard(Size(3, 3), squareLength, markerLength, dictionary);
  78. aruco::CharucoDetector detector(charucoBoard, aruco::CharucoParameters(), detectorParams);
  79. while(inputVideo.grab()) {
  80. Mat image, imageCopy;
  81. inputVideo.retrieve(image);
  82. double tick = (double)getTickCount();
  83. //! [detect_diamonds]
  84. vector<int> markerIds;
  85. vector<Vec4i> diamondIds;
  86. vector<vector<Point2f> > markerCorners, diamondCorners;
  87. vector<Vec3d> rvecs, tvecs;
  88. detector.detectDiamonds(image, diamondCorners, diamondIds, markerCorners, markerIds);
  89. //! [detect_diamonds]
  90. //! [diamond_pose_estimation]
  91. // estimate diamond pose
  92. size_t N = diamondIds.size();
  93. if(estimatePose && N > 0) {
  94. cv::Mat objPoints(4, 1, CV_32FC3);
  95. rvecs.resize(N);
  96. tvecs.resize(N);
  97. if(!autoScale) {
  98. // set coordinate system
  99. objPoints.ptr<Vec3f>(0)[0] = Vec3f(-squareLength/2.f, squareLength/2.f, 0);
  100. objPoints.ptr<Vec3f>(0)[1] = Vec3f(squareLength/2.f, squareLength/2.f, 0);
  101. objPoints.ptr<Vec3f>(0)[2] = Vec3f(squareLength/2.f, -squareLength/2.f, 0);
  102. objPoints.ptr<Vec3f>(0)[3] = Vec3f(-squareLength/2.f, -squareLength/2.f, 0);
  103. // Calculate pose for each marker
  104. for (size_t i = 0ull; i < N; i++)
  105. solvePnP(objPoints, diamondCorners.at(i), camMatrix, distCoeffs, rvecs.at(i), tvecs.at(i));
  106. //! [diamond_pose_estimation]
  107. /* //! [diamond_pose_estimation_as_charuco]
  108. for (size_t i = 0ull; i < N; i++) { // estimate diamond pose as Charuco board
  109. Mat objPoints_b, imgPoints;
  110. // The coordinate system of the diamond is placed in the board plane centered in the bottom left corner
  111. vector<int> charucoIds = {0, 1, 3, 2}; // if CCW order, Z axis pointing in the plane
  112. // vector<int> charucoIds = {0, 2, 3, 1}; // if CW order, Z axis pointing out the plane
  113. charucoBoard.matchImagePoints(diamondCorners[i], charucoIds, objPoints_b, imgPoints);
  114. solvePnP(objPoints_b, imgPoints, camMatrix, distCoeffs, rvecs[i], tvecs[i]);
  115. }
  116. //! [diamond_pose_estimation_as_charuco] */
  117. }
  118. else {
  119. // if autoscale, extract square size from last diamond id
  120. for(size_t i = 0; i < N; i++) {
  121. float sqLenScale = autoScaleFactor * float(diamondIds[i].val[3]);
  122. vector<vector<Point2f> > currentCorners;
  123. vector<Vec3d> currentRvec, currentTvec;
  124. currentCorners.push_back(diamondCorners[i]);
  125. // set coordinate system
  126. objPoints.ptr<Vec3f>(0)[0] = Vec3f(-sqLenScale/2.f, sqLenScale/2.f, 0);
  127. objPoints.ptr<Vec3f>(0)[1] = Vec3f(sqLenScale/2.f, sqLenScale/2.f, 0);
  128. objPoints.ptr<Vec3f>(0)[2] = Vec3f(sqLenScale/2.f, -sqLenScale/2.f, 0);
  129. objPoints.ptr<Vec3f>(0)[3] = Vec3f(-sqLenScale/2.f, -sqLenScale/2.f, 0);
  130. solvePnP(objPoints, diamondCorners.at(i), camMatrix, distCoeffs, rvecs.at(i), tvecs.at(i));
  131. }
  132. }
  133. }
  134. double currentTime = ((double)getTickCount() - tick) / getTickFrequency();
  135. totalTime += currentTime;
  136. totalIterations++;
  137. if(totalIterations % 30 == 0) {
  138. cout << "Detection Time = " << currentTime * 1000 << " ms "
  139. << "(Mean = " << 1000 * totalTime / double(totalIterations) << " ms)" << endl;
  140. }
  141. // draw results
  142. image.copyTo(imageCopy);
  143. if(markerIds.size() > 0)
  144. aruco::drawDetectedMarkers(imageCopy, markerCorners);
  145. //! [draw_diamonds]
  146. if(diamondIds.size() > 0) {
  147. aruco::drawDetectedDiamonds(imageCopy, diamondCorners, diamondIds);
  148. //! [draw_diamonds]
  149. //! [draw_diamond_pose_estimation]
  150. if(estimatePose) {
  151. for(size_t i = 0u; i < diamondIds.size(); i++)
  152. cv::drawFrameAxes(imageCopy, camMatrix, distCoeffs, rvecs[i], tvecs[i], squareLength*1.1f);
  153. }
  154. //! [draw_diamond_pose_estimation]
  155. }
  156. imshow("out", imageCopy);
  157. char key = (char)waitKey(waitTime);
  158. if(key == 27) break;
  159. }
  160. return 0;
  161. }