detect_diamonds.cpp 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  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 <opencv2/highgui.hpp>
  32. #include <opencv2/aruco/charuco.hpp>
  33. #include <vector>
  34. #include <iostream>
  35. #include "aruco_samples_utility.hpp"
  36. using namespace std;
  37. using namespace cv;
  38. namespace {
  39. const char* about = "Detect ChArUco markers";
  40. const char* keys =
  41. "{sl | | Square side length (in meters) }"
  42. "{ml | | Marker side length (in meters) }"
  43. "{d | | dictionary: DICT_4X4_50=0, DICT_4X4_100=1, DICT_4X4_250=2,"
  44. "DICT_4X4_1000=3, DICT_5X5_50=4, DICT_5X5_100=5, DICT_5X5_250=6, DICT_5X5_1000=7, "
  45. "DICT_6X6_50=8, DICT_6X6_100=9, DICT_6X6_250=10, DICT_6X6_1000=11, DICT_7X7_50=12,"
  46. "DICT_7X7_100=13, DICT_7X7_250=14, DICT_7X7_1000=15, DICT_ARUCO_ORIGINAL = 16}"
  47. "{cd | | Input file with custom dictionary }"
  48. "{c | | Output file with calibrated camera parameters }"
  49. "{as | | Automatic scale. The provided number is multiplied by the last"
  50. "diamond id becoming an indicator of the square length. In this case, the -sl and "
  51. "-ml are only used to know the relative length relation between squares and markers }"
  52. "{v | | Input from video file, if ommited, input comes from camera }"
  53. "{ci | 0 | Camera id if input doesnt come from video (-v) }"
  54. "{dp | | File of marker detector parameters }"
  55. "{rs | | Apply refind strategy }"
  56. "{refine | | Corner refinement: CORNER_REFINE_NONE=0, CORNER_REFINE_SUBPIX=1,"
  57. "CORNER_REFINE_CONTOUR=2, CORNER_REFINE_APRILTAG=3}"
  58. "{r | | show rejected candidates too }";
  59. }
  60. int main(int argc, char *argv[]) {
  61. CommandLineParser parser(argc, argv, keys);
  62. parser.about(about);
  63. if(argc < 4) {
  64. parser.printMessage();
  65. return 0;
  66. }
  67. float squareLength = parser.get<float>("sl");
  68. float markerLength = parser.get<float>("ml");
  69. bool showRejected = parser.has("r");
  70. bool estimatePose = parser.has("c");
  71. bool autoScale = parser.has("as");
  72. float autoScaleFactor = autoScale ? parser.get<float>("as") : 1.f;
  73. Ptr<aruco::DetectorParameters> detectorParams;
  74. if(parser.has("dp")) {
  75. FileStorage fs(parser.get<string>("dp"), FileStorage::READ);
  76. bool readOk = aruco::DetectorParameters::readDetectorParameters(fs.root(), detectorParams);
  77. if(!readOk) {
  78. cerr << "Invalid detector parameters file" << endl;
  79. return 0;
  80. }
  81. }
  82. if (parser.has("refine")) {
  83. //override cornerRefinementMethod read from config file
  84. detectorParams->cornerRefinementMethod = parser.get<int>("refine");
  85. }
  86. std::cout << "Corner refinement method (0: None, 1: Subpixel, 2:contour, 3: AprilTag 2): " << detectorParams->cornerRefinementMethod << std::endl;
  87. int camId = parser.get<int>("ci");
  88. String video;
  89. if(parser.has("v")) {
  90. video = parser.get<String>("v");
  91. }
  92. if(!parser.check()) {
  93. parser.printErrors();
  94. return 0;
  95. }
  96. Ptr<aruco::Dictionary> dictionary;
  97. if (parser.has("d")) {
  98. int dictionaryId = parser.get<int>("d");
  99. dictionary = aruco::getPredefinedDictionary(aruco::PREDEFINED_DICTIONARY_NAME(dictionaryId));
  100. }
  101. else if (parser.has("cd")) {
  102. FileStorage fs(parser.get<std::string>("cd"), FileStorage::READ);
  103. bool readOk = aruco::Dictionary::readDictionary(fs.root(), dictionary);
  104. if(!readOk) {
  105. cerr << "Invalid dictionary file" << endl;
  106. return 0;
  107. }
  108. }
  109. else {
  110. cerr << "Dictionary not specified" << endl;
  111. return 0;
  112. }
  113. Mat camMatrix, distCoeffs;
  114. if(estimatePose) {
  115. bool readOk = readCameraParameters(parser.get<string>("c"), camMatrix, distCoeffs);
  116. if(!readOk) {
  117. cerr << "Invalid camera file" << endl;
  118. return 0;
  119. }
  120. }
  121. VideoCapture inputVideo;
  122. int waitTime;
  123. if(!video.empty()) {
  124. inputVideo.open(video);
  125. waitTime = 0;
  126. } else {
  127. inputVideo.open(camId);
  128. waitTime = 10;
  129. }
  130. double totalTime = 0;
  131. int totalIterations = 0;
  132. while(inputVideo.grab()) {
  133. Mat image, imageCopy;
  134. inputVideo.retrieve(image);
  135. double tick = (double)getTickCount();
  136. vector< int > markerIds;
  137. vector< Vec4i > diamondIds;
  138. vector< vector< Point2f > > markerCorners, rejectedMarkers, diamondCorners;
  139. vector< Vec3d > rvecs, tvecs;
  140. // detect markers
  141. aruco::detectMarkers(image, dictionary, markerCorners, markerIds, detectorParams,
  142. rejectedMarkers);
  143. // detect diamonds
  144. if(markerIds.size() > 0)
  145. aruco::detectCharucoDiamond(image, markerCorners, markerIds,
  146. squareLength / markerLength, diamondCorners, diamondIds,
  147. camMatrix, distCoeffs);
  148. // estimate diamond pose
  149. if(estimatePose && diamondIds.size() > 0) {
  150. if(!autoScale) {
  151. aruco::estimatePoseSingleMarkers(diamondCorners, squareLength, camMatrix,
  152. distCoeffs, rvecs, tvecs);
  153. } else {
  154. // if autoscale, extract square size from last diamond id
  155. for(unsigned int i = 0; i < diamondCorners.size(); i++) {
  156. float autoSquareLength = autoScaleFactor * float(diamondIds[i].val[3]);
  157. vector< vector< Point2f > > currentCorners;
  158. vector< Vec3d > currentRvec, currentTvec;
  159. currentCorners.push_back(diamondCorners[i]);
  160. aruco::estimatePoseSingleMarkers(currentCorners, autoSquareLength, camMatrix,
  161. distCoeffs, currentRvec, currentTvec);
  162. rvecs.push_back(currentRvec[0]);
  163. tvecs.push_back(currentTvec[0]);
  164. }
  165. }
  166. }
  167. double currentTime = ((double)getTickCount() - tick) / getTickFrequency();
  168. totalTime += currentTime;
  169. totalIterations++;
  170. if(totalIterations % 30 == 0) {
  171. cout << "Detection Time = " << currentTime * 1000 << " ms "
  172. << "(Mean = " << 1000 * totalTime / double(totalIterations) << " ms)" << endl;
  173. }
  174. // draw results
  175. image.copyTo(imageCopy);
  176. if(markerIds.size() > 0)
  177. aruco::drawDetectedMarkers(imageCopy, markerCorners);
  178. if(showRejected && rejectedMarkers.size() > 0)
  179. aruco::drawDetectedMarkers(imageCopy, rejectedMarkers, noArray(), Scalar(100, 0, 255));
  180. if(diamondIds.size() > 0) {
  181. aruco::drawDetectedDiamonds(imageCopy, diamondCorners, diamondIds);
  182. if(estimatePose) {
  183. for(unsigned int i = 0; i < diamondIds.size(); i++)
  184. aruco::drawAxis(imageCopy, camMatrix, distCoeffs, rvecs[i], tvecs[i],
  185. squareLength * 0.5f);
  186. }
  187. }
  188. imshow("out", imageCopy);
  189. char key = (char)waitKey(waitTime);
  190. if(key == 27) break;
  191. }
  192. return 0;
  193. }