The pyzbar module: Decoding Barcodes in Python

Featured Img Decode Barcode

Hello fellow coder! In this tutorial, we will learn how to Decode Barcodes from images using Python. We’ll use the pyzbar module for the same and pair it along with the pillow module.

Using the pyzbar module to decode barcodes from an image

The pyzbar module is a module that is responsible for reading and decoding 1-D barcodes or QR codes easily and it requires PIL module in order to function properly. Before implementing the modules, we first need to import both modules.

1. Importing the required modules

We first need to import both pyzbar module and PIL in the code in order to operate functions accurately. The modules and functions required for decoding barcodes are imported using the code block below.

from pyzbar.pyzbar import decode
from PIL import Image

2. Import the Barcode Image

The next step is to import the barcode image from our system with the help of the open function of the Image submodule of the PIL module. The same is shown below.

img = Image.open("bar1.jpg")

For this tutorial, we have taken a random barcode found online. If you want to make your custom barcodes/QR codes you can check out this tutorial on creating custom barcodes/QR codes.

The barcode chosen by us is shown below. Our aim is to extract the information present under the barcode.

Bar1
Bar1

3. Getting Information from the Barcode

In order to extract information from an image of a barcode is obtained with the help of decode function which takes the image object as a parameter. The code for the same is shown below.

all_info = decode(img)

But this information that is being stored in the all_info variable is shown in the block below. You can see that the information obtained is very messy and nothing can be decoded from this information.

[Decoded(data=b'00123456789101112133', type='CODE128', rect=Rect(left=28, top=0, width=2114, height=885), polygon=[Point(x=28, y=1), Point(x=28, y=885), Point(x=2142, y=884), Point(x=2142, y=0)])]

4. Displaying the Barcode information

In order to display only the data from the barcode image and ignore the rest of the unnecessary information from the variable, we will be making use of the following code block.

for i in all_info:
    print(i.data.decode("utf-8"))

This code block will display the value 00123456789101112133 on the screen which matches the value under the barcode image. You can test the same code on other barcode images or even QR code images.

Conclusion

So, I hope you are aware of how Decoding Barcodes in the Python programming language works. Thank you for reading the tutorial!

Keep reading more! Happy Learning!