How to Generate and Read QR Codes with Python
This tutorial explains the history and common uses of QR codes, shows how to install the Python qrcode library, demonstrates simple and advanced QR code generation with customizable parameters, and teaches how to decode QR codes using OpenCV, complete with code examples.
QR codes are machine‑readable two‑dimensional barcodes originally invented in 1994 by Denso Wave for tracking automotive parts and later popularized by smartphones for payments, menus, Wi‑Fi sharing, and more.
To generate QR codes in Python, first install the qrcode package:
pip install qrcodeA minimal example creates a QR code that encodes the text "Hello World":
import qrcode
img = qrcode.make('Hello World')
img.save('hello.png')For more control, use the QRCode class with parameters such as version , error_correction , box_size , and border . The following code generates a red‑on‑black QR code linking to a Medium profile:
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=10,
border=4,
)
qr.add_data("https://abhijithchandradas.medium.com/")
qr.make(fit=True)
img = qr.make_image(fill_color="red", back_color="black")
img.save("medium.png")To read QR codes, install OpenCV (the cv2 module) and use its QRCodeDetector :
pip install cv2
import cv2
img = cv2.imread("medium.png")
det = cv2.QRCodeDetector()
val, pts, st_code = det.detectAndDecode(img)
print(val) # prints the decoded URLThe detectAndDecode function returns the decoded content, the corner points of the QR code, and a binarized image. This guide provides a complete workflow for creating and decoding QR codes in Python.
Original article: Create and Read QR Code Using Python
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.