Table of Contents
Introduction
In this tutorial, we will learn how to build a QR code reader using Python. QR codes are two-dimensional barcodes that can store various types of data, such as URLs, contact information, or plain text. By the end of this tutorial, you will be able to create a Python program that can read and decode QR codes from images or video streams.
Prerequisites
To follow along with this tutorial, you should have a basic understanding of Python programming. Familiarity with image processing concepts would also be helpful. We will be using the opencv-python
and pyzbar
libraries, so make sure they are installed in your Python environment.
Setup
-
Open your terminal or command prompt.
-
Create a new directory for our project:
mkdir qr_code_reader cd qr_code_reader
-
Create a virtual environment:
python -m venv env
-
Activate the virtual environment:
-
For Windows:
env\Scripts\activate
-
For macOS/Linux:
source env/bin/activate
-
-
Install the required libraries:
pip install opencv-python pyzbar
-
Create a new Python file:
touch qr_code_reader.py
-
Open the file in your favorite text editor.
Reading QR Codes
Import Required Libraries
In qr_code_reader.py
, we need to import the necessary libraries: cv2
, numpy
, and pyzbar
:
python
import cv2
import numpy as np
from pyzbar.pyzbar import decode
Capture and Decode QR Code
To capture and decode a QR code, we will define a function: ```python def read_qr_code(image): # Convert image to grayscale gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Decode QR code
qr_codes = decode(gray)
# Loop over detected QR codes
for qr_code in qr_codes:
# Extract QR code data
data = qr_code.data.decode("utf-8")
(x, y, w, h) = qr_code.rect
# Draw bounding box
cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
# Display QR code data
cv2.putText(image, data, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
return image
``` Let's break down the function:
-
First, we convert the image to grayscale using
cv2.cvtColor()
. QR codes are typically black and white, so working with grayscale images simplifies the process. -
We then use the
decode()
function frompyzbar
to decode the QR code. This function returns a list of QR code objects. -
Next, we iterate over each detected QR code and extract its data using
qr_code.data.decode("utf-8")
. We also get the coordinates of the bounding box surrounding the QR code. -
To visualize the QR code, we draw a green bounding box around it using
cv2.rectangle()
. The(0, 255, 0)
argument represents the color of the rectangle in BGR format. -
Finally, we display the QR code data on the image using
cv2.putText()
. This function allows us to overlay text on the image.
Read QR Code from an Image
Now that we have the read_qr_code()
function, let’s use it to read QR codes from an image. Make sure you have an image with a QR code inside the project directory, and update the filename accordingly. Add the following code to qr_code_reader.py
:
```python
# Load image
image = cv2.imread(“qr_code.png”)
# Read QR code
output = read_qr_code(image)
# Display result
cv2.imshow("QR Code", output)
cv2.waitKey(0)
cv2.destroyAllWindows()
``` Replace `"qr_code.png"` with the filename of your image. This code loads the image, calls the `read_qr_code()` function, and displays the result in a new window.
Read QR Code from a Webcam
Reading QR codes from a webcam is also possible using OpenCV. Update the code in qr_code_reader.py
with the following:
```python
# Initialize webcam
cap = cv2.VideoCapture(0)
while True:
# Capture frame-by-frame
ret, frame = cap.read()
# Read QR code
output = read_qr_code(frame)
# Display result
cv2.imshow("QR Code Reader", output)
# Exit if 'q' is pressed
if cv2.waitKey(1) & 0xFF == ord("q"):
break
# Release the webcam
cap.release()
cv2.destroyAllWindows()
``` This code reads frames from the webcam using `cv2.VideoCapture(0)` and continuously calls the `read_qr_code()` function to detect and display QR codes in real-time. Press the 'q' key to exit the program.
Conclusion
In this tutorial, you learned how to build a QR code reader using Python. We used the opencv-python
and pyzbar
libraries to capture, decode, and visualize QR codes from images or webcam streams. QR codes have a wide range of applications, and by understanding how to read them with Python, you can incorporate QR code scanning into your own projects. Experiment with different images or try adding additional functionality, such as saving the decoded data to a file.