目录
1 二维码(QRCode)扫描
2 结果
3 参考
在这篇文章中,我们将看到如何使用OpenCV扫描二维码。您将需要OpenCV3.4.4或4.0.0及更高版本来运行代码。
在OpenCV中扫描二维码很简单。我们首先读取图像。然后,我们实例化QRCodeDetector对象并使用detectAndDecode方法来查找QR码的数据和位置。最后,我们进行结果显示。
具体代码如下:
C++:
// QRCode_scanner.cpp
#include "pch.h"
#include
#include
#include
using namespace cv;
using namespace std;
/**
* @brief 用于显示检测到的QR码周围的框
*
* @param im
* @param bbox
*/
void display(Mat &im, Mat &bbox)
{
int n = bbox.rows;
for (int i = 0; i < n; i++)
{
line(im, Point2i(bbox.at(i, 0), bbox.at(i, 1)),
Point2i(bbox.at((i + 1) % n, 0), bbox.at((i + 1) % n, 1)), Scalar(255, 0, 0), 3);
}
imshow("Result", im);
}
int main()
{
// Read image
Mat inputImage = imread("./image/demo.jpg");
//QR检测器
QRCodeDetector qrDecoder = QRCodeDetector::QRCodeDetector();
//二维码边框坐标,提取出来的二维码
Mat bbox, rectifiedImage;
//检测二维码
std::string data = qrDecoder.detectAndDecode(inputImage, bbox, rectifiedImage);
//获取二维码中的数据链接
if (data.length() > 0)
{
cout << "Decoded Data : " << data << endl;
display(inputImage, bbox);
rectifiedImage.convertTo(rectifiedImage, CV_8UC3);
//展示二维码
imshow("Rectified QRCode", rectifiedImage);
waitKey(0);
}
else
{
cout << "QR Code not detected" << endl;
}
return 0;
}
Python:
import cv2
import numpy as np
import time
inputImage = cv2.imread("./image/demo.jpg")
# Display barcode and QR code location
def display(im, bbox):
n = len(bbox)
for j in range(n):
cv2.line(im, tuple(bbox[j][0]), tuple(bbox[ (j+1) % n][0]), (255,0,0), 3)
# Display results
cv2.imshow("Results", im)
# Create a qrCodeDetector Object
qrDecoder = cv2.QRCodeDetector()
# Detect and decode the qrcode
t = time.time()
data,bbox,rectifiedImage = qrDecoder.detectAndDecode(inputImage)
print("Time Taken for Detect and Decode : {:.3f} seconds".format(time.time() - t))
if len(data)>0:
print("Decoded Data : {}".format(data))
display(inputImage, bbox)
rectifiedImage = np.uint8(rectifiedImage);
cv2.imshow("Rectified QRCode", rectifiedImage);
else:
print("QR Code not detected")
cv2.imshow("Results", inputImage)
cv2.imwrite("output.jpg",inputImage)
cv2.waitKey(0)
cv2.destroyAllWindows()
二维码定位画框:
命令行输出,也就是提取的二维码链接:
Decoded Data : http://LearnOpenCV.com
所获取的二维码点图:
总体来说OpenCV检测的效果只能作为研究用。所有的代码见:
https://github.com/luohenyueji/OpenCV-Practical-Exercise
实际用还是用ZBar比较好,ZBar还支持条形码的识别,OpenCV只有二维码的识别。
ZBar具体应用见:
http://zbar.sourceforge.net/
https://blog.csdn.net/qq_38712026/article/details/78674665
https://blog.csdn.net/dcrmg/article/details/52132313
OpenCV自带二维码识别:
https://www.learnopencv.com/opencv-qr-code-scanner-c-and-python/
OpenCV上使用ZBar进行二维码和条形码识别:
https://www.learnopencv.com/barcode-and-qr-code-scanner-using-zbar-and-opencv/