calibrate_camera_charuco.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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/calib3d.hpp>
  33. #include <opencv2/aruco/charuco.hpp>
  34. #include <opencv2/imgproc.hpp>
  35. #include <vector>
  36. #include <iostream>
  37. #include "aruco_samples_utility.hpp"
  38. using namespace std;
  39. using namespace cv;
  40. namespace {
  41. const char* about =
  42. "Calibration using a ChArUco board\n"
  43. " To capture a frame for calibration, press 'c',\n"
  44. " If input comes from video, press any key for next frame\n"
  45. " To finish capturing, press 'ESC' key and calibration starts.\n";
  46. const char* keys =
  47. "{w | | Number of squares in X direction }"
  48. "{h | | Number of squares in Y direction }"
  49. "{sl | | Square side length (in meters) }"
  50. "{ml | | Marker side length (in meters) }"
  51. "{d | | dictionary: DICT_4X4_50=0, DICT_4X4_100=1, DICT_4X4_250=2,"
  52. "DICT_4X4_1000=3, DICT_5X5_50=4, DICT_5X5_100=5, DICT_5X5_250=6, DICT_5X5_1000=7, "
  53. "DICT_6X6_50=8, DICT_6X6_100=9, DICT_6X6_250=10, DICT_6X6_1000=11, DICT_7X7_50=12,"
  54. "DICT_7X7_100=13, DICT_7X7_250=14, DICT_7X7_1000=15, DICT_ARUCO_ORIGINAL = 16}"
  55. "{cd | | Input file with custom dictionary }"
  56. "{@outfile |<none> | Output file with calibrated camera parameters }"
  57. "{v | | Input from video file, if ommited, input comes from camera }"
  58. "{ci | 0 | Camera id if input doesnt come from video (-v) }"
  59. "{dp | | File of marker detector parameters }"
  60. "{rs | false | Apply refind strategy }"
  61. "{zt | false | Assume zero tangential distortion }"
  62. "{a | | Fix aspect ratio (fx/fy) to this value }"
  63. "{pc | false | Fix the principal point at the center }"
  64. "{sc | false | Show detected chessboard corners after calibration }";
  65. }
  66. int main(int argc, char *argv[]) {
  67. CommandLineParser parser(argc, argv, keys);
  68. parser.about(about);
  69. if(argc < 7) {
  70. parser.printMessage();
  71. return 0;
  72. }
  73. int squaresX = parser.get<int>("w");
  74. int squaresY = parser.get<int>("h");
  75. float squareLength = parser.get<float>("sl");
  76. float markerLength = parser.get<float>("ml");
  77. string outputFile = parser.get<string>(0);
  78. bool showChessboardCorners = parser.get<bool>("sc");
  79. int calibrationFlags = 0;
  80. float aspectRatio = 1;
  81. if(parser.has("a")) {
  82. calibrationFlags |= CALIB_FIX_ASPECT_RATIO;
  83. aspectRatio = parser.get<float>("a");
  84. }
  85. if(parser.get<bool>("zt")) calibrationFlags |= CALIB_ZERO_TANGENT_DIST;
  86. if(parser.get<bool>("pc")) calibrationFlags |= CALIB_FIX_PRINCIPAL_POINT;
  87. Ptr<aruco::DetectorParameters> detectorParams;
  88. if(parser.has("dp")) {
  89. FileStorage fs(parser.get<string>("dp"), FileStorage::READ);
  90. bool readOk = aruco::DetectorParameters::readDetectorParameters(fs.root(), detectorParams);
  91. if(!readOk) {
  92. cerr << "Invalid detector parameters file" << endl;
  93. return 0;
  94. }
  95. }
  96. bool refindStrategy = parser.get<bool>("rs");
  97. int camId = parser.get<int>("ci");
  98. String video;
  99. if(parser.has("v")) {
  100. video = parser.get<String>("v");
  101. }
  102. if(!parser.check()) {
  103. parser.printErrors();
  104. return 0;
  105. }
  106. VideoCapture inputVideo;
  107. int waitTime;
  108. if(!video.empty()) {
  109. inputVideo.open(video);
  110. waitTime = 0;
  111. } else {
  112. inputVideo.open(camId);
  113. waitTime = 10;
  114. }
  115. Ptr<aruco::Dictionary> dictionary;
  116. if (parser.has("d")) {
  117. int dictionaryId = parser.get<int>("d");
  118. dictionary = aruco::getPredefinedDictionary(aruco::PREDEFINED_DICTIONARY_NAME(dictionaryId));
  119. }
  120. else if (parser.has("cd")) {
  121. FileStorage fs(parser.get<std::string>("cd"), FileStorage::READ);
  122. bool readOk = aruco::Dictionary::readDictionary(fs.root(), dictionary);
  123. if(!readOk) {
  124. cerr << "Invalid dictionary file" << endl;
  125. return 0;
  126. }
  127. }
  128. else {
  129. cerr << "Dictionary not specified" << endl;
  130. return 0;
  131. }
  132. // create charuco board object
  133. Ptr<aruco::CharucoBoard> charucoboard =
  134. aruco::CharucoBoard::create(squaresX, squaresY, squareLength, markerLength, dictionary);
  135. Ptr<aruco::Board> board = charucoboard.staticCast<aruco::Board>();
  136. // collect data from each frame
  137. vector< vector< vector< Point2f > > > allCorners;
  138. vector< vector< int > > allIds;
  139. vector< Mat > allImgs;
  140. Size imgSize;
  141. while(inputVideo.grab()) {
  142. Mat image, imageCopy;
  143. inputVideo.retrieve(image);
  144. vector< int > ids;
  145. vector< vector< Point2f > > corners, rejected;
  146. // detect markers
  147. aruco::detectMarkers(image, dictionary, corners, ids, detectorParams, rejected);
  148. // refind strategy to detect more markers
  149. if(refindStrategy) aruco::refineDetectedMarkers(image, board, corners, ids, rejected);
  150. // interpolate charuco corners
  151. Mat currentCharucoCorners, currentCharucoIds;
  152. if(ids.size() > 0)
  153. aruco::interpolateCornersCharuco(corners, ids, image, charucoboard, currentCharucoCorners,
  154. currentCharucoIds);
  155. // draw results
  156. image.copyTo(imageCopy);
  157. if(ids.size() > 0) aruco::drawDetectedMarkers(imageCopy, corners);
  158. if(currentCharucoCorners.total() > 0)
  159. aruco::drawDetectedCornersCharuco(imageCopy, currentCharucoCorners, currentCharucoIds);
  160. putText(imageCopy, "Press 'c' to add current frame. 'ESC' to finish and calibrate",
  161. Point(10, 20), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(255, 0, 0), 2);
  162. imshow("out", imageCopy);
  163. char key = (char)waitKey(waitTime);
  164. if(key == 27) break;
  165. if(key == 'c' && ids.size() > 0) {
  166. cout << "Frame captured" << endl;
  167. allCorners.push_back(corners);
  168. allIds.push_back(ids);
  169. allImgs.push_back(image);
  170. imgSize = image.size();
  171. }
  172. }
  173. if(allIds.size() < 1) {
  174. cerr << "Not enough captures for calibration" << endl;
  175. return 0;
  176. }
  177. Mat cameraMatrix, distCoeffs;
  178. vector< Mat > rvecs, tvecs;
  179. double repError;
  180. if(calibrationFlags & CALIB_FIX_ASPECT_RATIO) {
  181. cameraMatrix = Mat::eye(3, 3, CV_64F);
  182. cameraMatrix.at< double >(0, 0) = aspectRatio;
  183. }
  184. // prepare data for calibration
  185. vector< vector< Point2f > > allCornersConcatenated;
  186. vector< int > allIdsConcatenated;
  187. vector< int > markerCounterPerFrame;
  188. markerCounterPerFrame.reserve(allCorners.size());
  189. for(unsigned int i = 0; i < allCorners.size(); i++) {
  190. markerCounterPerFrame.push_back((int)allCorners[i].size());
  191. for(unsigned int j = 0; j < allCorners[i].size(); j++) {
  192. allCornersConcatenated.push_back(allCorners[i][j]);
  193. allIdsConcatenated.push_back(allIds[i][j]);
  194. }
  195. }
  196. // calibrate camera using aruco markers
  197. double arucoRepErr;
  198. arucoRepErr = aruco::calibrateCameraAruco(allCornersConcatenated, allIdsConcatenated,
  199. markerCounterPerFrame, board, imgSize, cameraMatrix,
  200. distCoeffs, noArray(), noArray(), calibrationFlags);
  201. // prepare data for charuco calibration
  202. int nFrames = (int)allCorners.size();
  203. vector< Mat > allCharucoCorners;
  204. vector< Mat > allCharucoIds;
  205. vector< Mat > filteredImages;
  206. allCharucoCorners.reserve(nFrames);
  207. allCharucoIds.reserve(nFrames);
  208. for(int i = 0; i < nFrames; i++) {
  209. // interpolate using camera parameters
  210. Mat currentCharucoCorners, currentCharucoIds;
  211. aruco::interpolateCornersCharuco(allCorners[i], allIds[i], allImgs[i], charucoboard,
  212. currentCharucoCorners, currentCharucoIds, cameraMatrix,
  213. distCoeffs);
  214. allCharucoCorners.push_back(currentCharucoCorners);
  215. allCharucoIds.push_back(currentCharucoIds);
  216. filteredImages.push_back(allImgs[i]);
  217. }
  218. if(allCharucoCorners.size() < 4) {
  219. cerr << "Not enough corners for calibration" << endl;
  220. return 0;
  221. }
  222. // calibrate camera using charuco
  223. repError =
  224. aruco::calibrateCameraCharuco(allCharucoCorners, allCharucoIds, charucoboard, imgSize,
  225. cameraMatrix, distCoeffs, rvecs, tvecs, calibrationFlags);
  226. bool saveOk = saveCameraParams(outputFile, imgSize, aspectRatio, calibrationFlags,
  227. cameraMatrix, distCoeffs, repError);
  228. if(!saveOk) {
  229. cerr << "Cannot save output file" << endl;
  230. return 0;
  231. }
  232. cout << "Rep Error: " << repError << endl;
  233. cout << "Rep Error Aruco: " << arucoRepErr << endl;
  234. cout << "Calibration saved to " << outputFile << endl;
  235. // show interpolated charuco corners for debugging
  236. if(showChessboardCorners) {
  237. for(unsigned int frame = 0; frame < filteredImages.size(); frame++) {
  238. Mat imageCopy = filteredImages[frame].clone();
  239. if(allIds[frame].size() > 0) {
  240. if(allCharucoCorners[frame].total() > 0) {
  241. aruco::drawDetectedCornersCharuco( imageCopy, allCharucoCorners[frame],
  242. allCharucoIds[frame]);
  243. }
  244. }
  245. imshow("out", imageCopy);
  246. char key = (char)waitKey(0);
  247. if(key == 27) break;
  248. }
  249. }
  250. return 0;
  251. }