How to Scan QR codes From your Web Cam in 3 Steps

What will we cover?

Do you want to create a QR scanner that works on a live cam feed?

Sounds complex, but it is easy to do. In this tutorial will learn how to create it with OpenCV in 3 easy steps.

You can find all the code on my GitHub repository.

Step 1: Install requirements

The first thing you need to do, is to install the needed libraries.

We use three libraries, which are defined in the requirements.txt file in the GitHub repository and given below.

opencv-python
qrcode
Pillow

The libraries are.

  • opencv-python OpenCV is an open source computer vision and machine learning software library. We need to make a live video stream from your web camera.
  • qrcode A library to read and write QR codes. We need it to generate a QR code and read QR codes from the web cam.
  • Pillow The Python Imaging Library adds image processing capabilities to your Python interprete. We needed for the qrcode library to write images.

If you downloaded the repository then you can install them all by.

pip install -r requirements.txt

Otherwise you need to install them one-by-one.

pip install opencv-python
pip install qrcode
pip install Pillow

Now we are ready to write a QR code image.

Step 2: Write a QR code to an image

This is straight forward.

import qrcode
img = qrcode.make('You are AWESOME')
img.save("awesome.png")

Simply import the qrcode, make on with the desired text and write it to a file.

This piece of code uses the Pillow library to write it.

Now we are ready to see if we can read QR codes from our webcam.

Step 3: Read QR codes from your webcam

This can be done by created a feed from the webcam.

# import the opencv library
import cv2
# define a video capture object
vid = cv2.VideoCapture(0)
detector = cv2.QRCodeDetector()
while True:
    # Capture the video frame by frame
    ret, frame = vid.read()
    data, bbox, straight_qrcode = detector.detectAndDecode(frame)
    if len(data) > 0:
        print(data)
    # Display the resulting frame
    cv2.imshow('frame', frame)
    # the 'q' button is set as the
    # quitting button you may use any
    # desired button of your choice
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
# After the loop release the cap object
vid.release()
# Destroy all the windows
cv2.destroyAllWindows()

This is done by using an endless loop, which reads a frame from your webcam, detects if there is any QR code, by the detector.

If so, read it in the terminal.

You can terminate the processing by pressing q.

Leave a Reply

%d bloggers like this: