教程 | OpenCV4.1.2中实时高效的二维码识别模块
- 2019 年 11 月 27 日
- 筆記
OpenCV4.0发布了二维码检测与解析模块,但是大家用完以后都吐槽不已,觉得效果太差啦,根本不支持旋转与倾斜角度下的二维码检测与解析,让大家白高兴一场。在OpenCV4.1.2的release发布中有一部分是关于二维码模块精度与速度改善的说明,这么说OpenCV4.1.2中二维码检测与解析效果变好啦,我抱着一丝怀疑的态度,重新测试了一下,先看效果吧:



速度没问题!倾斜与错切视角没有问题,果然是提升了!够强大!
函数调用
OpenCV4中负责二维码检测与解析的类是QRCodeDetector,它有如下几个方法来实现二维码的检测与解析返回。
1.负责从图像中找到二维码区域,返回的是二维码四个顶点的坐标。
detect (InputArray img, OutputArray points) const img参数是输入图像,支持灰度或者彩色 points是vector返回的四个点坐标数组
2.负责解析二维码,返回utf-8字符串作为解析结果,无法解析返回空
decode (InputArray img, InputArray points, OutputArray straight_qrcode=noArray()) img表示输入图像 point表示检测到四个点坐标 straight_qrcode表示解析的二维码ROI
3.一步搞定二维码检测与解析。
detectAndDecode( InputArray img, //输入图像 OutputArray points=noArray(), // 顶点坐标 OutputArray straight_qrcode=noArray() // ROI )
代码演示
最终实现的二维码实时检测程序(比较懒,在sample代码上改改)。主要是分为如下几个部分:
打开摄像头
VideoCapture cap(0); if (!cap.isOpened()) { cout << "Cannot open a camera" << endl; return -1; }
二维码检测与解析
cap >> frame; if (frame.empty()) { cout << "End of video stream" << endl; break; } // flip(frame, frame, 1); cvtColor(frame, gray, COLOR_BGR2GRAY); total.start(); bool result_detection = qrcode.detect(gray, transform); if (result_detection) { printf("detect QR code....n"); decode_info = qrcode.decode(gray, transform, straight_barcode); cout << decode_info.c_str() << endl; putText(frame, decode_info.c_str(), Point(50, 50), FONT_HERSHEY_PLAIN, 1.0, Scalar(255, 0, 0), 2, 8); }
计算FPS与绘制顶点
绘制FPS
ostringstream convert; convert << cvRound(fps) << " FPS (QR detection)"; putText(color_image, convert.str(), Point(25, 25), FONT_HERSHEY_DUPLEX, 1, Scalar(0, 0, 255), 2);
绘制顶点
void drawQRCodeContour(Mat &color_image, vector<Point> transform) { if (!transform.empty()) { double show_radius = (color_image.rows > color_image.cols) ? (2.813 * color_image.rows) / color_image.cols : (2.813 * color_image.cols) / color_image.rows; double contour_radius = show_radius * 0.4; vector< vector<Point> > contours; contours.push_back(transform); drawContours(color_image, contours, 0, Scalar(211, 0, 148), cvRound(contour_radius)); RNG rng(1000); for (size_t i = 0; i < 4; i++) { Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255)); circle(color_image, transform[i], cvRound(show_radius), color, -1); } } }
总结:
OpenCV3是没有自带的二维码检测与解析程序的,OpenCV4.1.2自带的二维码检测程序比之前的要好用多了,直接部署到应用场景下速度与性能都没有问题。只能说OpenCV4 二维码识别靠谱!