python 写个手机扫描二维码服务的小程序

import qrcode
import cv2
import pyautogui

# 打开摄像头
cap = cv2.VideoCapture(0)

while True:
# 读取摄像头图像
ret, frame = cap.read()

# 转换为灰度图像
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

# 二值化图像
ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)

# 查找轮廓
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# 遍历所有轮廓
for cnt in contours:
# 计算轮廓矩形框
x, y, w, h = cv2.boundingRect(cnt)

# 判断是否为有效的二维码
if w / h > 2 and w / h < 5:
# 在图像上绘制矩形框
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)

# 提取二维码图像
qr_img = gray[y:y + h, x:x + w]

# 解码二维码
data = qrcode.make(qr_img)
decoder = qrcode.Decoder()
result = decoder.decode(data)

# 在图像上绘制解码结果
cv2.putText(frame, result, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)

# 显示图像

猜你喜欢

转载自blog.csdn.net/ducanwang/article/details/131726357