通過python掃描二維碼/條形碼並列印資料
阿新 • • 發佈:2020-01-09
需提前安裝好pyzbar和opencv-python庫(博主的電腦安裝opencv-python庫比較麻煩,但大部分都不會出現該問題)
安裝方法:開啟命令框輸入 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() #找到影象中的條形碼並進行解碼 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,'x+') as f: #x+ 以附加方式開啟可讀寫的檔案。若檔案不存在,則會建立該檔案,如果檔案存在,寫入的資料會被加到檔案尾後,即檔案原先的內容會被保留。 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
如果遇到在命令符中無法安裝opencv-python庫的話,手動在該網址https://www.lfd.uci.edu/~gohlke/pythonlibs/下載對應的whl包,手動安裝。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。