代碼直接復制運行即可,需要先安裝opencv和pyzbar的包
# coding:utf8 import cv2 import pyzbar.pyzbar as pyzbar def decodeDisplay(image): barcodes = pyzbar.decode(image) for barcode in barcodes: # 提取條形碼的邊界框的位置 # 畫出圖像中條形碼的邊界框 (x, y, w, h) = barcode.rect cv2.rectangle(image, (x, y), (x + w, y + h), (0, 0, 255), 2) # 條形碼數據為字節對象,所以如果我們想在輸出圖像上 # 畫出來,就需要先將它轉換成字符串 barcodeData = barcode.data.decode("utf-8") barcodeType = barcode.type # 繪出圖像上條形碼的數據和條形碼類型 text = "{} ({})".format(barcodeData, barcodeType) cv2.putText(image, text, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, .5, (0, 0, 125), 2) # 向終端打印條形碼數據和條形碼類型 print("[INFO] Found {} barcode: {}".format(barcodeType, barcodeData)) return image def detect(): camera = cv2.VideoCapture(0) while True: # 讀取當前幀 ret, frame = camera.read() # 轉為灰度圖像 gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) im=decodeDisplay(gray) cv2.waitKey(5) cv2.imshow("camera", im) camera.release() cv2.destroyAllWindows() if __name__ == '__main__': detect()