Code for How to Generate and Read QR Code in Python

You can also view the full code on github.

generate_qrcode.py

import qrcode
import sys

# from command line arguments
data = sys.argv[1]
filename = sys.argv[2]

# generate qr code
img = qrcode.make(data)
# save img to a file
img.save(filename)

read_qrcode.py

import cv2
import sys

filename = sys.argv[1]

# read the QRCODE image
img = cv2.imread(filename)

# initialize the cv2 QRCode detector
detector = cv2.QRCodeDetector()

# detect and decode
data, bbox, straight_qrcode = detector.detectAndDecode(img)

# if there is a QR code
if bbox is not None:
    print(f"QRCode data:\n{data}")
    # display the image with lines
    # length of bounding box
    n_lines = len(bbox)
    for i in range(n_lines):
        # draw all lines
        point1 = tuple(bbox[i][0])
        point2 = tuple(bbox[(i+1) % n_lines][0])
        cv2.line(img, point1, point2, color=(255, 0, 0), thickness=2)


# display the result
cv2.imshow("img", img)
cv2.waitKey(0)
cv2.destroyAllWindows()

read_qrcode_live.py

import cv2

# initalize the cam
cap = cv2.VideoCapture(0)

# initialize the cv2 QRCode detector
detector = cv2.QRCodeDetector()

while True:
    _, img = cap.read()

    # detect and decode
    data, bbox, _ = detector.detectAndDecode(img)

    # check if there is a QRCode in the image
    if bbox is not None:
        # display the image with lines
        for i in range(len(bbox)):
            # draw all lines
            cv2.line(img, tuple(bbox[i][0]), tuple(bbox[(i+1) % len(bbox)][0]), color=(255, 0, 0), thickness=2)

        if data:
            print("[+] QR Code detected, data:", data)

    # display the result
    cv2.imshow("img", img)
    
    if cv2.waitKey(1) == ord("q"):
        break

cap.release()
cv2.destroyAllWindows()