我们将学习如何使用opencv检测图像中的QR码和条形码,我们首先了解一下基础知识,然后我们将继续创建一个身份验证项目,在该项目中,根据上的QR码检查人是否被授权或未经授权。
在python中,我打开一个新项目,第一件事是要导入我们所需要的库
?代码如下:
import cv2
import numpy as np
from pyzbar.pyzbar import decode # 从pyzbar中导入解码器
# img = cv2.imread('3.webp')
cap = cv2.VideoCapture(0) # 调用摄像头
cap.set(3, 640) # 设置宽度ID等于3,宽640
cap.set(4, 480) # 设置高度ID等于4,宽480
while True:
success, img = cap.read() # 成功读取相机中的图像
for barcode in decode(img):
print(barcode.data) # 打印解码数据
myData = barcode.data.decode('utf-8')
print(myData) # 打印我的解码数据
pts = np.array([barcode.polygon], np.int32)
pts = pts.reshape((-1,1,2))
cv2.polylines(img,[pts],True,(255,0,255),5)
pts2 = barcode.rect
cv2.putText(img,myData,(pts2[0],pts2[1]),cv2.FONT_HERSHEY_SIMPLEX,0.9,(255,0,255),2)
cv2.imshow('Result', img)
cv2.waitKey(1)
检查二维码是否在授权范围之内:
import cv2
import numpy as np
from pyzbar.pyzbar import decode
# img = cv2.imread('3.webp')
cap = cv2.VideoCapture(0)
cap.set(3, 640)
cap.set(4, 480)
with open('myDataFile') as f:
myDataList = f.read().splitlines()
while True:
success, img = cap.read()
for barcode in decode(img):
print(barcode.data)
myData = barcode.data.decode('utf-8')
print(myData)
if myData in myDataList:
myOutput = 'Authorized'
myColor = (0, 255, 0)
else:
myOutput = 'Un-Authorized'
myColor = (0, 0, 255)
pts = np.array([barcode.polygon], np.int32)
pts = pts.reshape((-1,1,2))
cv2.polylines(img,[pts],True,myColor,5)
pts2 = barcode.rect
cv2.putText(img,myOutput,(pts2[0],pts2[1]),cv2.FONT_HERSHEY_SIMPLEX,0.9,myColor,2)
cv2.imshow('Result', img)
cv2.waitKey(1)
|