可以同时识别到多个二维码
直接上 代码
import cv2
import numpy as np
import pyautogui
from pyzbar.pyzbar import decode
from cv2.wechat_qrcode import WeChatQRCode
# 自定义区域的坐标和大小
region = (1024, 0, 900, 500) # 替换为你想要的区域
# 设置要显示的窗口大小
window_width = 900
window_height = 500
# 初始化 WeChatQRCode 检测器
detector = WeChatQRCode(
detector_prototxt_path="qr_mode/detect.prototxt",
detector_caffe_model_path="qr_mode/detect.caffemodel",
super_resolution_prototxt_path="qr_mode/sr.prototxt",
super_resolution_caffe_model_path="qr_mode/sr.caffemodel"
)
while True:
# 捕获屏幕的指定区域
screenshot = pyautogui.screenshot(region=region)
img = cv2.cvtColor(np.array(screenshot), cv2.COLOR_RGB2BGR)
# 图像预处理
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 转为灰度图像
blurred = cv2.GaussianBlur(gray, (7, 7), 0) # 增加模糊程度
# 增强对比度
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
gray = clahe.apply(gray)
# 使用自适应阈值
binary = cv2.adaptiveThreshold(blurred, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
cv2.THRESH_BINARY, 15, 2)
# 使用 pyzbar 解码二维码
decoded_objects = decode(binary) # 使用处理后的图像进行解码
# 在识别到的二维码周围画框
for obj in decoded_objects:
points = obj.polygon
if len(points) == 4: # 确保是四个顶点
pts = np.array(points, dtype=np.int32)
cv2.polylines(img, [pts], isClosed=True, color=(0, 255, 0), thickness=3)
# 绘制文本
x, y, w, h = cv2.boundingRect(pts)
cv2.putText(img, obj.data.decode('utf-8'), (x, y - 10), # 修正了这里
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 2)
# 使用 WeChatQRCode 解码
res, points = detector.detectAndDecode(img)
if res:
# 在识别到的二维码周围画框
if points is not None and len(points) > 0: # 确保 points 不为空
for point_set in points:
pts = np.int32(point_set).reshape(-1, 2) # 确保 pts 是一个 N x 2 的数组
cv2.polylines(img, [pts], isClosed=True, color=(255, 0, 0), thickness=3)
# 确保 res 是字符串
decoded_text = str(res)
# 使用第一个点的整数坐标
cv2.putText(img, decoded_text, (int(pts[0][0]), int(pts[0][1] - 10)),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 255), 2)
# 调整图像大小
img_resized = cv2.resize(img, (window_width, window_height))
# 显示结果
cv2.imshow('QR Code Detection', img_resized)
# 按 'q' 键退出
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cv2.destroyAllWindows()
资源链接有模型放在程序的同一个目录下
标签:img,python,cv2,二维码,points,import,识别,pts,255 From: https://blog.csdn.net/2403_86951163/article/details/142024390