qrcode.cpp 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. #include "opencv2/objdetect.hpp"
  2. #include "opencv2/imgproc.hpp"
  3. #include "opencv2/highgui.hpp"
  4. #include "opencv2/videoio.hpp"
  5. #include "opencv2/imgcodecs.hpp"
  6. #include <string>
  7. #include <iostream>
  8. using namespace std;
  9. using namespace cv;
  10. static int liveQRCodeDetect();
  11. static int imageQRCodeDetect(const string& in_file);
  12. static bool g_modeMultiQR = false;
  13. static bool g_detectOnly = false;
  14. static string g_out_file_name, g_out_file_ext;
  15. static int g_save_idx = 0;
  16. static bool g_saveDetections = false;
  17. static bool g_saveAll = false;
  18. static string getQRModeString()
  19. {
  20. std::ostringstream out;
  21. out << "QR"
  22. << (g_modeMultiQR ? " multi" : "")
  23. << (g_detectOnly ? " detector" : " decoder");
  24. return out.str();
  25. }
  26. int main(int argc, char *argv[])
  27. {
  28. const string keys =
  29. "{h help ? | | print help messages }"
  30. "{i in | | input image path (also switches to image detection mode) }"
  31. "{detect | false | detect QR code only (skip decoding) }"
  32. "{m multi | | use detect for multiple qr-codes }"
  33. "{o out | qr_code.png | path to result file }"
  34. "{save_detections | false | save all QR detections (video mode only) }"
  35. "{save_all | false | save all processed frames (video mode only) }"
  36. ;
  37. CommandLineParser cmd_parser(argc, argv, keys);
  38. cmd_parser.about("This program detects the QR-codes from camera or images using the OpenCV library.");
  39. if (cmd_parser.has("help"))
  40. {
  41. cmd_parser.printMessage();
  42. return 0;
  43. }
  44. string in_file_name = cmd_parser.get<string>("in"); // path to input image
  45. if (cmd_parser.has("out"))
  46. {
  47. std::string fpath = cmd_parser.get<string>("out"); // path to output image
  48. std::string::size_type idx = fpath.rfind('.');
  49. if (idx != std::string::npos)
  50. {
  51. g_out_file_name = fpath.substr(0, idx);
  52. g_out_file_ext = fpath.substr(idx);
  53. }
  54. else
  55. {
  56. g_out_file_name = fpath;
  57. g_out_file_ext = ".png";
  58. }
  59. }
  60. if (!cmd_parser.check())
  61. {
  62. cmd_parser.printErrors();
  63. return -1;
  64. }
  65. g_modeMultiQR = cmd_parser.has("multi") && cmd_parser.get<bool>("multi");
  66. g_detectOnly = cmd_parser.has("detect") && cmd_parser.get<bool>("detect");
  67. g_saveDetections = cmd_parser.has("save_detections") && cmd_parser.get<bool>("save_detections");
  68. g_saveAll = cmd_parser.has("save_all") && cmd_parser.get<bool>("save_all");
  69. int return_code = 0;
  70. if (in_file_name.empty())
  71. {
  72. return_code = liveQRCodeDetect();
  73. }
  74. else
  75. {
  76. return_code = imageQRCodeDetect(samples::findFile(in_file_name));
  77. }
  78. return return_code;
  79. }
  80. static
  81. void drawQRCodeContour(Mat &color_image, const vector<Point>& corners)
  82. {
  83. if (!corners.empty())
  84. {
  85. double show_radius = (color_image.rows > color_image.cols)
  86. ? (2.813 * color_image.rows) / color_image.cols
  87. : (2.813 * color_image.cols) / color_image.rows;
  88. double contour_radius = show_radius * 0.4;
  89. vector< vector<Point> > contours;
  90. contours.push_back(corners);
  91. drawContours(color_image, contours, 0, Scalar(211, 0, 148), cvRound(contour_radius));
  92. RNG rng(1000);
  93. for (size_t i = 0; i < 4; i++)
  94. {
  95. Scalar color = Scalar(rng.uniform(0,255), rng.uniform(0, 255), rng.uniform(0, 255));
  96. circle(color_image, corners[i], cvRound(show_radius), color, -1);
  97. }
  98. }
  99. }
  100. static
  101. void drawFPS(Mat &color_image, double fps)
  102. {
  103. ostringstream convert;
  104. convert << cv::format("%.2f", fps) << " FPS (" << getQRModeString() << ")";
  105. putText(color_image, convert.str(), Point(25, 25), FONT_HERSHEY_DUPLEX, 1, Scalar(0, 0, 255), 2);
  106. }
  107. static
  108. void drawQRCodeResults(Mat& frame, const vector<Point>& corners, const vector<cv::String>& decode_info, double fps)
  109. {
  110. if (!corners.empty())
  111. {
  112. for (size_t i = 0; i < corners.size(); i += 4)
  113. {
  114. size_t qr_idx = i / 4;
  115. vector<Point> qrcode_contour(corners.begin() + i, corners.begin() + i + 4);
  116. drawQRCodeContour(frame, qrcode_contour);
  117. cout << "QR[" << qr_idx << "] @ " << Mat(qrcode_contour).reshape(2, 1) << ": ";
  118. if (decode_info.size() > qr_idx)
  119. {
  120. if (!decode_info[qr_idx].empty())
  121. cout << "'" << decode_info[qr_idx] << "'" << endl;
  122. else
  123. cout << "can't decode QR code" << endl;
  124. }
  125. else
  126. {
  127. cout << "decode information is not available (disabled)" << endl;
  128. }
  129. }
  130. }
  131. else
  132. {
  133. cout << "QR code is not detected" << endl;
  134. }
  135. drawFPS(frame, fps);
  136. }
  137. static
  138. void runQR(
  139. QRCodeDetector& qrcode, const Mat& input,
  140. vector<Point>& corners, vector<cv::String>& decode_info
  141. // +global: bool g_modeMultiQR, bool g_detectOnly
  142. )
  143. {
  144. if (!g_modeMultiQR)
  145. {
  146. if (!g_detectOnly)
  147. {
  148. String decode_info1 = qrcode.detectAndDecode(input, corners);
  149. decode_info.push_back(decode_info1);
  150. }
  151. else
  152. {
  153. bool detection_result = qrcode.detect(input, corners);
  154. CV_UNUSED(detection_result);
  155. }
  156. }
  157. else
  158. {
  159. if (!g_detectOnly)
  160. {
  161. bool result_detection = qrcode.detectAndDecodeMulti(input, decode_info, corners);
  162. CV_UNUSED(result_detection);
  163. }
  164. else
  165. {
  166. bool result_detection = qrcode.detectMulti(input, corners);
  167. CV_UNUSED(result_detection);
  168. }
  169. }
  170. }
  171. static
  172. double processQRCodeDetection(QRCodeDetector& qrcode, const Mat& input, Mat& result, vector<Point>& corners)
  173. {
  174. if (input.channels() == 1)
  175. cvtColor(input, result, COLOR_GRAY2BGR);
  176. else
  177. input.copyTo(result);
  178. cout << "Run " << getQRModeString()
  179. << " on image: " << input.size() << " (" << typeToString(input.type()) << ")"
  180. << endl;
  181. TickMeter timer;
  182. vector<cv::String> decode_info;
  183. timer.start();
  184. runQR(qrcode, input, corners, decode_info);
  185. timer.stop();
  186. double fps = 1 / timer.getTimeSec();
  187. drawQRCodeResults(result, corners, decode_info, fps);
  188. return fps;
  189. }
  190. int liveQRCodeDetect()
  191. {
  192. VideoCapture cap(0);
  193. if (!cap.isOpened())
  194. {
  195. cout << "Cannot open a camera" << endl;
  196. return 2;
  197. }
  198. cout << "Press 'm' to switch between detectAndDecode and detectAndDecodeMulti" << endl;
  199. cout << "Press 'd' to switch between decoder and detector" << endl;
  200. cout << "Press ' ' (space) to save result into images" << endl;
  201. cout << "Press 'ESC' to exit" << endl;
  202. QRCodeDetector qrcode;
  203. for (;;)
  204. {
  205. Mat frame;
  206. cap >> frame;
  207. if (frame.empty())
  208. {
  209. cout << "End of video stream" << endl;
  210. break;
  211. }
  212. bool forceSave = g_saveAll;
  213. Mat result;
  214. try
  215. {
  216. vector<Point> corners;
  217. double fps = processQRCodeDetection(qrcode, frame, result, corners);
  218. cout << "FPS: " << fps << endl;
  219. forceSave |= (g_saveDetections && !corners.empty());
  220. //forceSave |= fps < 1.0;
  221. }
  222. catch (const cv::Exception& e)
  223. {
  224. cerr << "ERROR exception: " << e.what() << endl;
  225. forceSave = true;
  226. }
  227. if (!result.empty())
  228. imshow("QR code", result);
  229. int code = waitKey(1);
  230. if (code < 0 && !forceSave)
  231. continue; // timeout
  232. char c = (char)code;
  233. if (c == ' ' || forceSave)
  234. {
  235. string fsuffix = cv::format("-%05d", g_save_idx++);
  236. string fname_input = g_out_file_name + fsuffix + "_input.png";
  237. cout << "Saving QR code detection input: '" << fname_input << "' ..." << endl;
  238. imwrite(fname_input, frame);
  239. string fname = g_out_file_name + fsuffix + g_out_file_ext;
  240. cout << "Saving QR code detection result: '" << fname << "' ..." << endl;
  241. imwrite(fname, result);
  242. cout << "Saved" << endl;
  243. }
  244. if (c == 'm')
  245. {
  246. g_modeMultiQR = !g_modeMultiQR;
  247. cout << "Switching QR code mode ==> " << (g_modeMultiQR ? "detectAndDecodeMulti" : "detectAndDecode") << endl;
  248. }
  249. if (c == 'd')
  250. {
  251. g_detectOnly = !g_detectOnly;
  252. cout << "Switching QR decoder mode ==> " << (g_detectOnly ? "detect" : "decode") << endl;
  253. }
  254. if (c == 27)
  255. {
  256. cout << "'ESC' is pressed. Exiting..." << endl;
  257. break;
  258. }
  259. }
  260. cout << "Exit." << endl;
  261. return 0;
  262. }
  263. int imageQRCodeDetect(const string& in_file)
  264. {
  265. const int count_experiments = 10;
  266. Mat input = imread(in_file, IMREAD_COLOR);
  267. cout << "Run " << getQRModeString()
  268. << " on image: " << input.size() << " (" << typeToString(input.type()) << ")"
  269. << endl;
  270. QRCodeDetector qrcode;
  271. vector<Point> corners;
  272. vector<cv::String> decode_info;
  273. TickMeter timer;
  274. for (size_t i = 0; i < count_experiments; i++)
  275. {
  276. corners.clear();
  277. decode_info.clear();
  278. timer.start();
  279. runQR(qrcode, input, corners, decode_info);
  280. timer.stop();
  281. }
  282. double fps = count_experiments / timer.getTimeSec();
  283. cout << "FPS: " << fps << endl;
  284. Mat result; input.copyTo(result);
  285. drawQRCodeResults(result, corners, decode_info, fps);
  286. imshow("QR", result); waitKey(1);
  287. if (!g_out_file_name.empty())
  288. {
  289. string out_file = g_out_file_name + g_out_file_ext;
  290. cout << "Saving result: " << out_file << endl;
  291. imwrite(out_file, result);
  292. }
  293. cout << "Press any key to exit ..." << endl;
  294. waitKey(0);
  295. cout << "Exit." << endl;
  296. return 0;
  297. }