检测并截取保存二维码

 

检测并截取保存二维码

截取图片未进行旋转调正操作,但是考虑到ROS小车大部分情况下都是平行视角,所以不考虑

import cv2
import numpy as np
import pyzbar.pyzbar as pyzbar
import time
# 打开摄像头
cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)

while True:
    # 读取帧
    ret, frame = cap.read()

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

    # 使用pyzbar库识别二维码
    decoded = pyzbar.decode(gray)

    # 遍历所有二维码
    for barcode in decoded:
        # 提取二维码边框的坐标
        (x, y, w, h) = barcode.rect

        # 计算正方形边长
        size = max(w, h)

        # 计算中心点
        cx, cy = x + w // 2, y + h // 2

        # 计算正方形左上角坐标
        x1, y1 = cx - size // 2, cy - size // 2

        # 裁剪二维码并保存
        qr_code = frame[y1:y1+size, x1:x1+size]
        cv2.imwrite("D://qr_code.png", qr_code)

        # 关闭摄像头并退出程序
        cap.release()
        cv2.destroyAllWindows()
        exit()

    # 显示帧
    cv2.imshow('Camera', frame)

    # 等待按键事件
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# 释放摄像头
cap.release()

# 销毁窗口
cv2.destroyAllWindows()