1

I am using the following program to detect a qr code within an image (there may be other noise in it)

    image = cv2.imread('/content/Screen Shot 2021-11-10 at 3.30.16 PM.png')
 
qrCodeDetector = cv2.QRCodeDetector()
 
decodedText, points, _ = qrCodeDetector.detectAndDecode(image)
 
if points is not None:
 
    nrOfPoints = len(points)
 
    for i in range(nrOfPoints):
        nextPointIndex = (i+1) % nrOfPoints
        cv2.line(image, tuple(points[i][0]), tuple(points[nextPointIndex][0]), (255,0,0), 5)
 
    print(decodedText)    
 
    cv2_imshow(image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
     
 
else:
    print("QR code not detected")

However, when I run this in jupyter notebook (change cv2_imshow to cv2.imshow, this runs on) I get the following error:

error: OpenCV(4.5.4-dev) :-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

I am confused as to why I cannot run it on my computer in an ide like Jupiter or spyder. I updated multiple things like OpenCV yesterday. Additionally, It seems like this error shouldn't occur as the documentation shows that tuples are used. Any suggestions? Thanks

1 Answers1

0

You are getting an error: "index 0 has a wrong type", because cv2.line expects integer type, and the type your are passing is float32.

points[i][0] is a NumPy array with dtype = float32 .
You can convert the NumPy array type to int32 using astype:

tuple(points[i][0].astype('int32'))

There other issues that I tried to fix...

Here is the complete code:

import cv2

image = cv2.imread('qrcode_stackoverflow.com.png')

qrCodeDetector = cv2.QRCodeDetector()
 
decodedText, points, _ = qrCodeDetector.detectAndDecode(image)

# Remove redundant dimensions - points.shape is (1, 4, 2), and we want it to be (4, 2)
# The first dimension may be above 1 when there are multiple QR codes (not sure about it).
points = points[0]
 
if points is not None:
 
    #nrOfPoints = len(points)
    nrOfPoints = points.shape[0]
 
    for i in range(nrOfPoints):
        nextPointIndex = (i+1) % nrOfPoints
        cv2.line(image, tuple(points[i, :].astype('int32')), tuple(points[nextPointIndex, :].astype('int32')), (255,0,0), 5)
 
    print(decodedText)
 
    cv2.imshow('image', image) #cv2_imshow(image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()   

else:
    print("QR code not detected")

Input image "qrcode_stackoverflow.com.png":
enter image description here

Output image:
enter image description here

Output text:
https://stackoverflow.com/questions/69934887/python-opencv-to-read-qr-images

Rotem
  • 30,366
  • 4
  • 32
  • 65