鉴于 CV2 的元组中断,我如何使用 CV2 读取二维码?

How can I read qr codes using CV2 given their CV2's breaking of tuples?

我正在按照教程使 qr reader 在 python 中工作,但我 运行 在 运行 时遇到以下错误:

Exception has occurred: error OpenCV(4.5.4) :-1: error: (-5:Bad argument) in function 'line' Overload resolution failed:

  • Can't parse 'pt1'. Sequence item with index 0 has a wrong type
  • Can't parse 'pt1'. Sequence item with index 0 has a wrong type File "C:\Users\me\project\qrreader.py", line 18, in cv2.line(img, tuple(bbox[i][0]), tuple(bbox[(i+1) % len(bbox)][0]), color=(255,

脚本如下

import cv2

# set up camera object
cap = cv2.VideoCapture(0)

# QR code detection object
detector = cv2.QRCodeDetector()

while True:
    # get the image
    _, img = cap.read()
    # get bounding box coords and data
    data, bbox, _ = detector.detectAndDecode(img)
    
    # if there is a bounding box, draw one, along with the data
    if(bbox is not None):
        for i in range(len(bbox)):
            cv2.line(img, tuple(bbox[i][0]), tuple(bbox[(i+1) % len(bbox)][0]), color=(255,
                     0, 255), thickness=2)
        cv2.putText(img, data, (int(bbox[0][0][0]), int(bbox[0][0][1]) - 10), cv2.FONT_HERSHEY_SIMPLEX,
                    0.5, (0, 255, 0), 2)
        if data:
            print("data found: ", data)
    # display the image preview
    cv2.imshow("code detector", img)
    if(cv2.waitKey(1) == ord("q")):
        break
# free camera object and exit

这个脚本似乎在所有教程中都有,但据我所知,它似乎已经随着 opencv 4.5.2 的更改而中断,但我似乎无法修复它。

如果不是元组,行函数需要什么?

您的 bbox 是一个形状为 (1,4,2) 的三维数组。我建议您通过将其重塑为二维数组来简化它。要将其转换为 int,numpy 数组具有 astype 方法。最后,cv2.line 仍然需要 tuple,因此保持原样。

这是一个可能的解决方案块:

    # if there is a bounding box, draw one, along with the data
    if bbox is not None:
        bb_pts = bbox.astype(int).reshape(-1, 2)
        num_bb_pts = len(bb_pts)
        for i in range(num_bb_pts):
            cv2.line(img,
                     tuple(bb_pts[i]),
                     tuple(bb_pts[(i+1) % num_bb_pts]),
                     color=(255, 0, 255), thickness=2)
        cv2.putText(img, data,
                    (bb_pts[0][0], bb_pts[0][1] - 10),
                    cv2.FONT_HERSHEY_SIMPLEX,
                    0.5, (0, 255, 0), 2)

Numpy 文档:reshape, astype.