...

/

Reading Various Barcodes with Python

Reading Various Barcodes with Python

Learn how to use the pyzbar library in Python to read barcode images.

In this lesson, we’ll learn to read barcodes from images using the pyzbar library. Images read with both the PIL and the OpenCV libraries can be used as input for the pyzbar.decode() function. It is also possible to only look for specific barcodes in the input images.

Note: Pillow is a fork of the Python Imaging Library (PIL), created to add new features and support for newer Python versions when PIL was discontinued. It’s fully backward-compatible with PIL and is now the preferred Python library for image processing due to its active maintenance and expanded features.

Using PIL to read barcode images

First, we need to import the Image class from the PIL library (also commonly referred to as Pillow; see the note above) and the decode function from the pyzbar library.

import pyzbar 
from PIL import Image 
from pyzbar.pyzbar import decode

We now open the image in which we wish to detect and decode a barcode.

Press + to interact
EAN-13 barcode
EAN-13 barcode

Below is an example of how to read an image and decode the barcode that is present in that image.

Press + to interact
from PIL import Image
from pyzbar.pyzbar import decode
im1 = 'resources/EAN13.jpg'
img = Image.open(im1)
decoded_list = decode(img)
print("decoded:", decoded_list)
print("data:", decoded_list[0].data.decode())

...