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

Time:11-24

I'm following a tutorial to get a qr reader working in python, but I'm running into the following error while running it:

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,

The script is as follows

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

This script is in all of the tutorials out there, seemingly, but it appears to have broke with opencv 4.5.2 changes as far as I can tell, but I can't seem to fix it.

If not a tuple, what does the line function require?

CodePudding user response:

Your bbox is a 3-dimensional array with shape (1,4,2). I suggest you simplify it by reshaping it to a 2D array. To cast it to int, numpy arrays have the astype method. Finally, a tuple is still required by cv2.line, so keep that as-is.

Here is one possible solution chunk:

    # 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 documentation: reshape, astype.

  • Related