import cv2
import numpy as np
import pyautogui
from pyzbar.pyzbar import decode
# 自定义区域的坐标和大小
region = (1024, 0, 900, 500) # 替换为你想要的区域
# 设置要显示的窗口大小
window_width = 900
window_height = 500
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)
# 解码二维码
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)
# 调整图像大小
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()
07-08
2122
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
09-27