使用Python开发二维码扫描工具

依赖安装

调用摄像头需要使用到 OpenCV 模块,而识别二维码则需要使用到 pyzbar 模块。

pip install opencv-python
pip install pyzbar

OpenCV基本用法

1、图片读取

import cv2 as cv
img = cv.imread("1.jpg")
print(img)
  • 图片在 OpenCV 中是以 ndarray 对象存储的,ndarray 是 numpy 中的一种多维数组。
[[[237 237 237]
[237 237 237]
[183 213 242]
...
[215 227 239]
[237 237 237]
[237 237 237]]

2、显示图片

import cv2 as cv
### 读取图片
img = cv.imread("1.jpg")
### 显示图像
cv.imshow("img", img)
### 等待键盘输入,否则图片只展示一瞬间
cv.waitKey()
### 销毁窗口
cv.destroyAllWindows()

3、调用摄像头中的一帧图片

# VideoCapture函数传入视频路径时,会读取视频文件;
# 传入数字时,它会调用指定的摄像头,比如传入 0 表示调用第 0 个摄像头
import cv2 as cv
### 读取摄像头
cap = cv.VideoCapture(0)
### 读取一帧画面
ret, frame = cap.read()
### 显示读取的画面
cv.imshow("video", frame)
cv.waitKey()
cv.destroyAllWindows()

4、循环读取摄像头图片

import cv2 as cv
cap = cv.VideoCapture(0)
while True:
ret, frame = cap.read()
cv.imshow("video", frame)
cv.waitKey(10)
# 这里可以改造为按q键退出读取
# key = cv.waitKey(10)
# if key == ord('q'):
# break
cv.destroyAllWindows()

pyzbar基本用法

识别二维码中的文字

import cv2 as cv
from pyzbar import pyzbar
### 读取图片
img = cv.imread("11.png")
### 识别二维码
res = pyzbar.decode(img)
text = res[0].data.decode('utf-8')
print(text)

扫码工具实现

import cv2 as cv
from pyzbar import pyzbar

cap = cv.VideoCapture(0)
while True:
ret, frame = cap.read()
cv.imshow('qrcode', frame)
key = cv.waitKey(10)
if key == ord('q'):
break
try:
res = pyzbar.decode(frame)
text = res[0].data.decode('utf-8')
print(text)
# 当画面中没有二维码时,程序可能会报错,因此需要对解码部分进行异常处理
except Exception as e:
pass
cv.destroyAllWindows()

你可能感兴趣的:(python,opencv,计算机视觉)