以下是使用Python和OpenCV實現攝像頭掃描二維碼的最簡單示例:
import cv2
from pyzbar import pyzbar# 打開攝像頭
cap = cv2.VideoCapture(0)print("正在掃描二維碼... (按 'q' 鍵退出)")while True:# 讀取攝像頭幀ret, frame = cap.read()if not ret:print("無法獲取攝像頭畫面")break# 查找并解碼二維碼barcodes = pyzbar.decode(frame)# 處理檢測到的二維碼for barcode in barcodes:# 提取二維碼數據barcode_data = barcode.data.decode("utf-8")barcode_type = barcode.type# 在圖像上繪制二維碼邊框和內容(x, y, w, h) = barcode.rectcv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)# 顯示二維碼內容text = f"{barcode_type}: {barcode_data}"cv2.putText(frame, text, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)# 打印到控制臺print(f"檢測到二維碼: {text}")# 顯示畫面cv2.imshow("二維碼掃描器", frame)# 按'q'鍵退出if cv2.waitKey(1) & 0xFF == ord('q'):break# 釋放資源
cap.release()
cv2.destroyAllWindows()
代碼說明:
-
??依賴庫??:
opencv-python
:用于攝像頭捕獲和圖像顯示pyzbar
:用于二維碼/條形碼識別
-
??安裝依賴??:
pip install opencv-python pyzbar
-
??主要功能??:
- 打開默認攝像頭
- 實時檢測畫面中的二維碼
- 在畫面中標記二維碼位置
- 顯示二維碼內容和類型
- 在控制臺輸出檢測結果
-
??支持的二維碼類型??:
- QR Code
- Code 128
- EAN-13
- UPC-A
- 等多種常見條碼/二維碼格式