制作一个二维码验证的工具,调用摄像头
假设文件myDataFile.txt的记事本存放了会议人员的名字,并且每人安排了一个二维码,通过相机安检进入,编写程序,
在摄像头捕获的图像中,程序会尝试识别二维码并读取二维码的内容并与从文件中读取内容进行比对,然后在图像上标记出是否授权
Python代码
#使用pyzbar库扫描摄像头捕获的图像中的二维码。
#使用 OpenCV 实现了从摄像头读取图像、显示图像、绘制多边形和文字等功能。
#使用 NumPy 用于处理图像数据和多边形的坐标。
import cv2
import numpy as np
from pyzbar.pyzbar import decode
cap = cv2.VideoCapture(0)#打开摄像头(打开默认摄像头(通常是内置摄像头)。)
cap.set(3,640)#摄像头设置:打开默认摄像头(通常是内置摄像头)。设置摄像头的宽度和高度为640x480。
cap.set(4,480)#
print("打开调用摄像头")
with open('myDataFile.txt', encoding='utf-8') as f:#mydatafile.txt修改为本机路径并且输入类容
#获取每一行成一个列表,相当于myDataList = [line.strip() for line in f.readlines()]
myDataList = f.read().splitlines()
#myDataList = [line.strip() for line in f]
print(myDataList)
while True:
success, img = cap.read()
for barcode in decode(img):
myData = barcode.data.decode('utf-8')
print("二维码识别成功")
print("识别出二维码的myData:", repr(myData)) # 打印解码后的二维码数据
print("读取的列表中的myDataList:", myDataList)#txt文档中的信息
if myData in myDataList:#如果myData在myDataList中,则执行以下代码块
myOutput = 'Authorized'#将 myOutput 设置为 'Authorized' 表示授权,同时将颜色设置为绿色
#print("在列表中")
myColor = (0,255,0)
else:# 如果myData不在myDataList中,则执行以下代码块
myOutput = 'Un-Authorized'#将 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)
print("正在运行识别")
cv2.imshow('Result',img)
cv2.waitKey(1)
二维码制作网站
https://zh.qr-code-generator.com/
text的文档内容
运行代码识别摄像头的内容
二维码内容是列表中内容
二维码不是列表中的内容
会一直运行