Read QR code in Python

Joash Xu
·Jul 8, 2020·

2 min read

Subscribe to my newsletter and never miss my upcoming articles

Last week, I showed you how to generate a QR code. In this article, I will show you how to read a QR code.

Prerequisite

First, you need to install the ZBar library. ZBar is an open-source software suite for reading bar codes. It can read bar codes from video streams and image files. And it supports reading QR code.

On Mac OS X, this will do:

brew install zbar

On Linux:

sudo apt-get install libzbar0

Once you have installed the ZBar library, you can install pyzbar, a wrapper for ZBar library.

pip install pyzbar

Reading QR Code

I am going to show you how to read QR code from an Image. Note that ZBar is not limited to reading QR code from an image, it can read from a video stream. But for now, I will show you how to scan QR code from an image.

First of all, you need to import the library.

from PIL import Image
from pyzbar import pyzbar

Now let's open a QR code image file and decode the data. The QR code we are trying to read is this:

The QR Code

>>> info = pyzbar.decode(Image.open("hello-qr-world.png"))
>>> info
[Decoded(data=b'Hello, QR World.\n\n--enzircle', type='QRCODE', 
    rect=Rect(left=39, top=39, width=292, height=292), 
    polygon=[Point(x=39, y=39), Point(x=39, y=330), 
    Point(x=331, y=331), Point(x=330, y=39)])]
>>> data = info[0].data.decode("utf8")
>>> print(data)
Hello, QR World.

--enzircle
>>>

That is it! You have just read the data from a QR code.

It can even detect multiple QR code in one go. For instance, this image:

Multiple QR code Source: Google image search.

>>> info = pyzbar.decode(Image.open("multiple-qr.png"))
>>> [item.data.decode("utf8") for item in info]
['https://play.google.com/store/apps/details?id=com.Allied.AIG',
 'https://www.samsung.com/au/support/',
 'http://en.m.wikipedia.org',
 'Hello :)',
 '@ELTOROIT']

Now you know how to read QR code from an image.

 
Share this