QR code reader in Python
Python QR code reader from image or How to decode a QR-code image in python?
Decoding a QR code from an image in Python is primarily achieved using the pyzbar
library, which reads various bar codes and QR codes 1, 2.
Installation
You'll need the pyzbar
library to perform the decoding and Pillow
(PIL
) to load and handle the image file 1.
pip install pyzbar pillow
Note: Depending on your operating system, pyzbar
may require a system dependency called zbar. If you encounter installation errors, you may need to install the zbar development libraries for your specific OS (e.g., search for install libzbar-dev
or similar) 1.
Python code example: decode image file
This script uses Pillow
to open the image and passes it to pyzbar
for decoding.
from PIL import Image
from pyzbar.pyzbar import decode
def decode_qr_code(image_path):
"""
Decodes QR codes from a given image file path.
Args:
image_path (str): The path to the QR code image file (e.g., 'my_qr.png').
Returns:
list: A list of decoded results, or an empty list if no QR code is found.
"""
try:
# 1. Open the image using Pillow
img = Image.open(image_path)
# 2. Decode the QR code(s) in the image 1, 2.
decoded_objects = decode(img)
if not decoded_objects:
print(f"No QR code found in the image: {image_path}")
return []
print(f"--- Decoded Results for {image_path} ---")
results = []
for obj in decoded_objects:
# The data is returned as bytes, so we decode it to a string (UTF-8)
data = obj.data.decode('utf-8')
code_type = obj.type
print(f"Type: {code_type}")
print(f"Data: {data}")
results.append({
'type': code_type,
'data': data,
'rect': obj.rect
})
return results
except FileNotFoundError:
print(f"Error: The file was not found at {image_path}")
return []
except Exception as e:
print(f"An unexpected error occurred: {e}")
return []
# Example usage:
# Make sure you have a QR code image named 'my_qr_code.png' in the same directory.
image_file = 'my_qr_code.png'
decoded_data = decode_qr_code(image_file)
Decoding from a numpy array (for OpenCV)
If you are working with real-time video or complex image processing using OpenCV (cv2
), the image will be loaded as a NumPy array. pyzbar
can decode directly from a NumPy array as well 2.
import cv2
from pyzbar.pyzbar import decode
import numpy as np
def decode_qr_from_cv2_image(numpy_image: np.ndarray):
"""
Decodes QR codes from an image loaded as a NumPy array (e.g., from OpenCV).
"""
# The decode function works directly with the NumPy array 2.
decoded_objects = decode(numpy_image)
if decoded_objects:
for obj in decoded_objects:
# Decode byte data to string
data = obj.data.decode('utf-8')
print(f"Decoded data: {data}")
print(f"Code type: {obj.type}")
return [obj.data.decode('utf-8') for obj in decoded_objects]
else:
print("No QR code found in the image array.")
return []
# Example usage with OpenCV (requires: pip install opencv-python numpy)
# Load an image using cv2
# img = cv2.imread('my_qr_code.png')
# if img is not None:
# decode_qr_from_cv2_image(img)