在生活中我们有时候会遇到用电脑扫描更方便的情形,但是奈何现在的电脑程序都没有提供扫描二维码的功能,所以我花了半天的时间专门做了一个电脑扫描二维码程序。
实现目标:利用电脑摄像头识别二维码中的内容并自动打开浏览器进行浏览,同时发出扫描成功的音效。
废话不多说,上代码!
"""
准备工作:
二维码图片
导入pyzbar库:pip install pyzbar
实现目标:
利用摄像头识别二维码中的内容并打印出来
"""
import cv2
import pyzbar.pyzbar as pyzbar
import webbrowser
import os
from pygame import mixer
import time
def decodeDisplay(video,flag):
gray = cv2.cvtColor(video, cv2.COLOR_BGR2GRAY)
barcodes = pyzbar.decode(gray)
for barcode in barcodes:
(x, y, w, h) = barcode.rect
cv2.rectangle(video, (x, y), (x + w, y + h), (0, 255, 0), 2)
barcodeData = barcode.data.decode("utf-8")
barcodeType = barcode.type
text = "{}".format(barcodeData)
cv2.putText(video, text, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX,1, (0, 255, 0), 2)
print("[扫描结果]: {0}".format(barcodeData))
for i in range(0,1):
result = barcodeData
webbrowser.open(result)
flag=27
mixer.init()
mixer.music.load('二维码.wav')
mixer.music.play()
time.sleep(5)
mixer.music.stop()
return flag
cv2.imshow("QRCODE",video)
def detect():
cap = cv2.VideoCapture(0)
while(True):
ret, frame = cap.read()
flag = cv2.waitKey(1)
flag = decodeDisplay(frame,flag)
if flag == 27:
break
cap.release()
cv2.destroyAllWindows()
if __name__ == '__main__':
detect()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
是不是很像我们手机扫描二维码的感觉呢?
PS:代码中注释
“提取二维码的位置,然后用边框标识出来在视频中”,
由于我设置的逐帧捕获速度太快,所以识别框没来的及标注就已经打开浏览器了。为了更像手机端体验,同时我设置浏览成功后程序马上关闭。