Scanning Qr Code – Opencv with Python

We’re going to see today how to scan Qr code using OpenCV.
Below you can see the code read the Qr code from an image or a real-time video.

For this project, we will obviously need our OpenCV library then NumPy and pyzbar. If you need to install pyzbar, I recommend that you go directly to the project page to follow the instructions.

Scanning Qr Code read from an image

Let’s start by importing all the libraries into our python file. As you can see from the code below and in my first example I imported an image.

import cv2
import numpy as np
import pyzbar.pyzbar as pyzbar

image = cv2.imread("pysource_qrcode.png")

This is the qr code I used

Scanning Qr Code

Now I simply take the data with processing through the library and print the results.

decodedObjects = pyzbar.decode(image)
for obj in decodedObjects:
    print("Type:", obj.type)
    print("Data: ", obj.data, "\n")

We just did Scanning Qr Code – Opencv with Python for the single image.

Scanning Qr Code – Opencv with Python from webcam

For Scanning Qr Code – Opencv with Python with the webcam the procedure is similar to that used for the single image. Instead of the image path we use the function cv2.VideoCapture (0).

As we already know the video stream of the image, on OpenCV, is recognized as a sequence of images, so it will be necessary to insert the processing inside a While loop. In the code below everything will be clearer.

cap = cv2.VideoCapture(0)
font = cv2.FONT_HERSHEY_PLAIN

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

    decodedObjects = pyzbar.decode(frame)
    for obj in decodedObjects:
        #print("Data", obj.data)
        cv2.putText(frame, str(obj.data), (50, 50), font, 2,
                    (255, 0, 0), 3)

Conclusion

In this article I explained, in a very simple way, how to decode a qr code with opencv and python. You can download the complete and immediately usable code from the download link.

Files:

Blueprint

Learn to build Computer Vision Software easily and efficiently.

This is a FREE Workshop where I'm going to break down the 4 steps that are necessary to build software to detect and track any object.

Sign UP for FREE