示例一:使用zbar调用摄像头,对二维码进行解析,并将返回的数据存入txt文件。
# coding:utf-8
import cv2
import zbar
from PIL import Image
def decode_QR(img):
scanner = zbar.ImageScanner() # 获得扫描器对象
pil = Image.fromarray(img).convert('L') # 格式转换
width, height = pil.size # 二维码的宽度和长度
raw = pil.tobytes() # 流转换
image = zbar.Image(width, height, 'Y800', raw)
scanner.scan(image)
data = ''
# 获得二维码里的数据
for symbol in image:
data += symbol.data
# 将二维码的数据存入TXT文件
if data != '':
with open('data.txt', 'w') as file:
file.write(data)
return False
else:
return True
def detect():
camera = cv2.VideoCapture(0) # 打开笔记本的内置摄像头
while True:
ret, frame = camera.read()
flag = decode_QR(frame)
if flag == False:
break
if cv2.waitKey(1) == ord('q'): # 按q键退出
break
cv2.imshow('', frame) # 显示窗口
camera.release()
cv2.destroyAllWindows()
if __name__ == '__main__':
detect()
示例二:导入本地视频,使用zbar对视频中的多个二维码进行解析,同时将解析出来的数据存入txt文件。
# coding:utf-8
import cv2
import zbar
from PIL import Image
# 用来存放视频中识别到的二维码数据
datalist = []
def decode_QR(img):
scanner = zbar.ImageScanner()
pil = Image.fromarray(img).convert('L')
width, height = pil.size
raw = pil.tobytes()
image = zbar.Image(width, height, 'Y800', raw)
scanner.scan(image)
data = ''
for symbol in image:
data += symbol.data
# 先对数据进行处理,防止重复存入相同数据
if data != '' and data not in datalist:
datalist.append(data)
def detect():
camera = cv2.VideoCapture('wx') # 导入视频文件
while True:
ret, frame = camera.read()
if ret == False:
break
decode_QR(frame)
if cv2.waitKey(1) == ord('q'):
break
camera.release()
cv2.destroyAllWindows()
with open('data.txt', 'a+') as file:
file.write('\n'.join(datalist))
if __name__ == '__main__':
detect()
示例三:使用pyzbar对摄像头捕获到的二维码进行解析,并将解析出来的数据存入txt文件。
import cv2
import pyzbar.pyzbar as pyzbar
def detect():
camera = cv2.VideoCapture(0)
while True:
ret, frame = camera.read()
barcodes = pyzbar.decode(frame) # 解析摄像头捕获到的所有二维码
data = ''
# 遍历所有的二维码
for barcode in barcodes:
data = barcode.data.decode('utf-8') # 对数据进行转码
if data != '':
with open('data.txt', 'w') as file:
file.write(data)
break
if cv2.waitKey(1) == ord('q'):
break
cv2.imshow('', frame)
camera.release()
cv2.destroyAllWindows()
if __name__ == '__main__':
detect()
示例四:使用pyzbar对视频中的多个二维码进行解析,同时将数据存放入txt文件。
import cv2
import pyzbar.pyzbar as pyzbar
# 用来存放二维码的数据
datalist = []
def detect():
camera = cv2.VideoCapture('wx') # 本地视频
while True:
ret, frame = camera.read()
if ret == False:
break
barcodes = pyzbar.decode(frame) # 解析摄像头捕获到的所有二维码
data = ''
# 遍历所有的二维码
for barcode in barcodes:
data = barcode.data.decode('utf-8') # 对数据进行转码
if data != '' and data not in datalist:
datalist.append(data)
camera.release()
cv2.destroyAllWindows()
with open('data.txt', 'a+') as file:
file.write('\n'.join(datalist))
if __name__ == '__main__':
detect()