How to Generate and Read QR Code in Python

Abdou Rockikz · 16 sep 2019

Abdou Rockikz · 4 min read · Updated nov 2019 · General Python Topics

QR code is a type of matrix barcode that is machine readable optical label that contains information about the item to which it is attached. In practice, QR codes often contain data for a locator, identifier, or tracker that points to a website or application.

In this tutorial, you will learn how to generate and read QR codes in Python using qrcode and OpenCV libraries.

Installing required dependencies:

pip3 install opencv-python qrcode

Generate QR Code

It is basically straight forward to generate QR code using qrcode library:

import qrcode
# example data
data = "https://www.thepythoncode.com"
# output file name
filename = "site.png"
# generate qr code
img = qrcode.make(data)
# save img to a file
img.save(filename)

This will generate a new file in the current directory with the name of "site.png", which contains a QR code image of the data specified, easy enough?

Read QR Code

There are many tools that reads QR code. However, we will be using OpenCV for that, as it is popular and easy to integrate with the webcam. Alright, open up a new Python file and follow along with me:

Let's read the image that is just generated:

import cv2
# read the QRCODE image
img = cv2.imread("site.png")

Luckily for us, OpenCV already got QR code detector built in:

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

We have the image and the detector, let's detect and decode that data:

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

detectAndDecode() function takes an image as an input and returns a tuple of 3 values: the data decoded from the QR code, the output array of vertices of the found QR code quadrangle and the output image containing rectified and binarized QR code.

We just need data and bbox here, bbox will help us draw the quadrangle in the image and data will be printed to the console!

Let's do it:

# 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)

cv2.line() function draws a line segment connecting two points, we retrieve these points from bbox array that was decoded by detectAndDecode() previously. we specified a blue color ( (255, 0, 0) is blue as OpenCV uses BGR colors ) and thickness of 2.

Finally, let's show the image and quit when a key is pressed:

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

Once you run this, the decoded data is printed:

QRCode data:
https://www.thepythoncode.com

And the following image is shown:

The read QRCode using OpenCV in Python

As you can see, the blue lines are drawn in the exact QR code borders.

We are done with this script, try to run it with different data and see your own results!

If you want to detect and decode QR codes live using your webcam (and I'm sure you do), here is a code for that:

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()

Awesome, we are done with this tutorial, you can now integrate this in your own applications!

Happy Coding ♥

View Full Code
Sharing is caring!


Read Also





Comment panel

   
Comment system is still in Beta, if you find any bug, please consider contacting us here.