'OpenCV QRCodeDetector Out Of Memory even with a small file

So I'm trying to decode a QR code image using code from this S.O. answer. Here's the adapted code:

import cv2

# Name of the QR Code Image file
filename = r"C:\temp\2021-12-14_162414.png"
# read the QRCODE image
image = cv2.imread(filename)
# initialize the cv2 QRCode detector
detector = cv2.QRCodeDetector()
# detect and decode
data, vertices_array, binary_qrcode = detector.detectAndDecode(image)
# if there is a QR code
# print the data
if vertices_array is not None:
    print("QRCode data:")
    print(data)
else:
    print("There was some error")

(This is the whole program; I was still experimenting.)

The PNG file itself is really small, just 43 KB in size, with resolution of 290x290 (24 bpp) containing just the QR Code.

However, I keep getting the error:

Traceback (most recent call last):
  File "C:/Repos/tesqr/decod-cv2.py", line 10, in <module>
    data, vertices_array, binary_qrcode = detector.detectAndDecode(image)
cv2.error: OpenCV(4.5.4) D:\a\opencv-python\opencv-python\opencv\modules\core\src\alloc.cpp:73: error: (-4:Insufficient memory) Failed to allocate 54056250000 bytes in function 'cv::OutOfMemoryError'

Why is alloc.cpp asking for 54 GB of RAM ???

I'm new with OpenCV, so please help me troubleshoot what went wrong.

The library I'm using is:

$ pip3 freeze | grep opencv
opencv-contrib-python-headless==4.5.4.60

the input image:

input image



Solution 1:[1]

Short Answer:

Try WeChatQRCode

Long Answer:

There are several open memory issues about decoding with QRCodeDetector. I hope that in future versions it will be fixed. Meanwhile you can try WeChatQRCode also from cv2.

WeChatQRCode includes two CNN-based models: A object detection model and a super resolution model. Object detection model is applied to detect QRCode with the bounding box. super resolution model is applied to zoom in QRCode when it is small.

Your code modified:

import cv2

# Name of the QR Code Image file
filename = "2021-12-14_162414.png"
# read the QRCODE image
image = cv2.imread(filename)
# initialize the cv2 QRCode detector
detector =cv2.wechat_qrcode_WeChatQRCode(detector_prototxt_path = "detect.prototxt", detector_caffe_model_path = "detect.caffemodel", super_resolution_prototxt_path = "sr.prototxt", super_resolution_caffe_model_path = "sr.caffemodel")
# detect and decode
data, vertices_array = detector.detectAndDecode(image)
# if there is a QR code
# print the data
if vertices_array is not None:
    print("QRCode data:")
    print(data)
else:
    print("There was some error")

Output:

QRCode data:
('PK\x03\x04\n',)

As you can see, it needs prototxt and caffemodel files. You can find them here.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 frankscitech