Introduction
QR Code is the most popular 2 dimensional barcodes that widely used for document management, track and trace in supply chain and logistics industry, mobile payment, and even the “touchless” health declaration and contact tracing during the COVID-19 pandemic. Comparing to 1D barcode, QR code can be very small in size but hold more information, and also easier for scanning as you can scan it from any direction.
In this article, I would be sharing with you how to use some pure Python packages to generate QR code and read QR code from images.
Generate QR code with Python
To generate QR code, we will use a Python package called qrcode. Below is the pip command to install this package:
#install qrcode together with pillow pip install qrcode[pil] #or install qrcode if you already have pillow installed pip install qrcode
As it has dependency to Pillow package, you will need to have this package installed as well. Once you have these packages ready, let’s import the modules at the beginning of our code:
import qrcode from PIL import Image
Generating a QR code with this qrcode library can be easily done with 1 line of code:
img = qrcode.make('QR Code')
If you check the “img” object from Jupyter Notebook, you can see the below image:
This make function provides a quick way to generate QR code with all the default parameters. To specify the parameters like the size, style or border of the boxes, you can use the QRCode class. For instance:
qr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=10, border=4, )
Here is the explanations for these parameters:
version – QR code has 40 different sizes which indicated as the version parameter in above, version 1 represents a 21×21 matrix. You can use (v-1)*4 + 21 to calculate the size of the matrix for each of the version number.
error_correction – specifies error correction level which controls how many error correction code blocks to be inserted in order to achieve the error correction capability. In another words, if you want your barcode to be readable even when it’s damaged (or have a logo/image onto it) , you may increase the error correction level, but this would also make your barcode more compact.
box_size – the number of pixels of the square box
border – the thickness of the square box border
Once you have a QRCode instance, you can use the below code to specify the barcode data, color and generate a image:
#barcode content qr.add_data('codeforests.com') #auto adjust the size qr.make(fit=True) #specifying barcode color img = qr.make_image(fill_color="#040359", back_color="#f7f7fa")
If you check the “img” object from Jupyter Notebook again, you shall see something similar to below:
To use the same barcode style to generate new barcode, you can just clear the data and then re-generate a new image object:
qr.clear() qr.add_data('Python Tutorials') img2 = qr.make_image(fill_color="#015b82", back_color="TransParent")
When inspecting the “img2” in Jupyter Notebook, you shall see below:
You can simply use the “save” method to save it into an image file since it is a Pillow Image object:
img2.save("qr_code.png")
The qrcode package cannot directly generate multiple QR codes into one image, if you need that, you may use the Pillow package to combine the images. For instance:
#create a blank image new_img = Image.new("RGBA", (600, 350), "#fcfcfc") new_img.paste(img, (0, 0)) new_img.paste(img2, (300, 0)) new_img.save("multi-QR-code.png")
The above will create a new image and combine the two barcode images into one. If you check the saved image file, you shall see:
With this package, you can also generate styled QR code e.g.: rounded corners, radial gradient, embedded image or different color masks. You can take a look at the samples from it’s office site.
Read QR Code in Python
To read QR code, we will use another Python package called pyzbar. You can use below pip command to install it:
pip install pyzbar
This library is also a very easy to use, you can directly pass in a Pillow Image object, numpy.ndarray or raw bytes to the decode method to detect the barcode. For instance:
import pyzbar.pyzbar as pyzbar from pyzbar.pyzbar import ZBarSymbol input_image = Image.open("multi-QR-code.png") decoded_objects = pyzbar.decode(input_image, symbols=[ZBarSymbol.QRCODE])
The decode method returns a list of barcode objects detected from the image with their position info. You can use the symbols parameter to restrict what type of barcodes you want to detect. When this parameter is not specified, all its supported barcode types will be checked.
From the above, you can further loop through the list to get the actual content data of the barcodes:
for obj in decoded_objects: zbarData = obj.data.decode("utf-8") print(zbarData)
You shall see the below result:
In your real-world project, if you need to read one barcode among the multiple barcodes from a document, you may try to use the symbols to restrict the barcode types, or use regular expression to validate the detected barcode data in order to find the correct one you need.
If you need to do a lot of image pre-processing or even read barcode from video or webcam, you may install OpenCV and use the detectAndDecodeMulti method to read the QR code.
Conclusion
In this article, we have reviewed through two simple but useful packages – qrcode for generating QR code, and pyzbar for reading the content from a QR code. There are quite many other Python packages for generating all sorts of one or two dimensional barcodes, some are in pure Python packages and some are Python wrappers, you may take a look at the summary table from this blog if any specific barcode type you need is not supported by these two packages.