使用pyzbar模块来识别二维码和条形码。ZBar是一个开源软件,用来从图像中读取条形码,支持多种编码,比如EAN-13/UPC-A、UPC-E、EAN-8、代码128、代码39、交错2/5以及二维码。
pyzbar是python封装ZBar的模块,我们用它来做条形码和二维码的识别。
安装方法:
平台 | 安装方法 |
Windows | 使用pip安装即可 pip install pyzbar |
Ubuntu | sudo apt-get install libzbar-dev pip install zbar 参考: ubuntu中安装zbar_ubuntu 安装libzbar依赖-CSDN博客 |
python识别二维码并绘制边框和文字的代码:
import matplotlib.pyplot as plt
import numpy as np
import cv2 as cv
from pyzbar.pyzbar import decode
#读取二维码图像
img = cv.imread('../../SampleImages/QRCodes.jpg')
QRCodes = decode(img)
for QRCode in QRCodes:
print(QRCode)
stringData = QRCode.data.decode('utf-8')
print("二维码字符串是:\"" + stringData + "\"")
#绘制出二维码边框
points = np.array([QRCode.polygon], np.int32)
#numpy reshape: https://blog.csdn.net/DocStorm/article/details/58593682
points = points.reshape((-1,1,2))
cv.polylines(img, [points], True, (0,255,0), 5)
rectPoints = QRCode.rect
cv.putText(img, stringData, (rectPoints[0], rectPoints[1]), cv.FONT_HERSHEY_SIMPLEX, 0.5, (0,0,255), 2)
plt.imshow(img[:,:,::-1])
运行结果(最后的二维码是残缺的,因此未识别):
识别条形码的代码和识别二维码的代码是一样的:
#读取条形码图像
img = cv.imread('../../SampleImages/BARCodes.png')
BARCodes = decode(img)
for BARCode in BARCodes:
print(QRCode)
stringData = BARCode.data.decode('utf-8')
print("条形码字符串是:\"" + stringData + "\"")
#绘制出二维码边框
points = np.array([BARCode.polygon], np.int32)
#numpy reshape: https://blog.csdn.net/DocStorm/article/details/58593682
points = points.reshape((-1,1,2))
cv.polylines(img, [points], True, (0,255,0), 5)
rectPoints = BARCode.rect
cv.putText(img, stringData, (rectPoints[0] - 20, rectPoints[1] - 5), cv.FONT_HERSHEY_SIMPLEX, 1, (0,0,255), 2)
plt.imshow(img[:,:,::-1])
识别结果: