提前安裝好pyzbar 和 opencv-python庫
//安裝方法:打開cmd, 輸入 pip install ...(pyzbar / opencv-python)
注意!!!
打開攝像頭的瞬間,不要被自己的大臉嚇到哈哈哈哈哈哈哈哈哈
#首先導入本次所需要的庫,最後一個csv是Python自帶的csv表格操作庫,這裏我們需要把我們掃到的二維碼信息都存入csv表格裏。
import cv2
from pyzbar import pyzbar
import csv
#然後我們設置一個變量,來存放我們掃到的二維碼信息,我們每次掃描一遍都會要檢測掃描到的二維碼是不是之前掃描到的,
# 如果沒有就存放到這裏。接着我們調用opencv的方法來實例化一個攝像頭,
# 最後我們設置一些我們存放二維碼信息的表格的路徑。
found = set()
capture = cv2.VideoCapture(0)
#存放數據的表格
PATH = "test.csv"
#然後我們要寫一個死循環,我們要不停的用攝像頭來採集二維碼,
# 所以要在死循環裏來寫二維碼採集的代碼。
while(1):
# 首先我們要用剛纔實例化的攝像頭來採集實時的照片,
ret,frame = capture.read()
# 然後用pyzbar的函數來解析圖片裏面是否有二維碼
#找到圖像中的條形碼並進行解碼
test = pyzbar.decode(frame)
# 循環檢測到的條形碼
for tests in test:
# 先將它轉換成字符串
testdate = tests.data.decode('utf-8')
testtype = tests.type
# 繪出圖像上條形碼的數據和條形碼類型
printout = "{} ({})".format(testdate, testtype)
if testdate not in found:
# 向終端打印條形碼數據和條形碼類型
print("[INFO] Found {} barcode: {}".format(testtype, testdate))
print(printout)
#存放掃描數據
if testdate not in found:
with open(PATH,'a+') as f:
#a+ 以附加方式打開可讀寫的文件。若文件不存在,則會建立該文件,如果文件存在,寫入的數據會被加到文件尾後,即文件原先的內容會被保留。
csv_write = csv.writer(f)
date = [testdate]
csv_write.writerow(date)
found.add(testdate)
cv2.imshow('Test',frame)
if cv2.waitKey(1) == ord('q'):
break