How to Generate and Read QR Code in Python

Learning how you can generate and read QR Code in Python using qrcode and OpenCV libraries.
Abdou Rockikz · 4 min read · Updated apr 2020 · General Python Topics

QR code is a type of matrix barcode that is machine readable optical label which 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, etc.

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

First, let's start by generating QR codes, it is basically straight forward using qrcode library:

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

This will generate a new image file in the current directory with the name of "site.png", which contains a QR code image of the data specified (in this case, this website).

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 or any video.

Alright, open up a new Python file and follow along with me, let's read the image that we 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 decodes it to return 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)

Once you run this, the decoded data is printed:

QRCode data:

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. Awesome, 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 =
    # 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"):

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

Check qrcode's official documentation.

Finally, if you feel you need to learn Python, I highly suggest you get the Python Crash Course book, it is a hands-on, and project-based book, good luck!

Learn also: How to Use Steganography to Hide Secret Data in Images in Python.

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.