How to decode a QR-code image in (preferably pure) Python? How to decode a QR-code image in (preferably pure) Python? python python

How to decode a QR-code image in (preferably pure) Python?


You can try the following steps and code using qrtools:

  • Create a qrcode file, if not already existing

    • I used pyqrcode for doing this, which can be installed using pip install pyqrcode
    • And then use the code:

      >>> import pyqrcode>>> qr = pyqrcode.create("HORN O.K. PLEASE.")>>> qr.png("horn.png", scale=6)
  • Decode an existing qrcode file using qrtools

    • Install qrtools using sudo apt-get install python-qrtools
    • Now use the following code within your python prompt

      >>> import qrtools>>> qr = qrtools.QR()>>> qr.decode("horn.png")>>> print qr.datau'HORN O.K. PLEASE.'

Here is the complete code in a single run:

In [2]: import pyqrcodeIn [3]: qr = pyqrcode.create("HORN O.K. PLEASE.")In [4]: qr.png("horn.png", scale=6)In [5]: import qrtoolsIn [6]: qr = qrtools.QR()In [7]: qr.decode("horn.png")Out[7]: TrueIn [8]: print qr.dataHORN O.K. PLEASE.

Caveats

  • You might need to install PyPNG using pip install pypng for using pyqrcode
  • In case you have PIL installed, you might get IOError: decoder zip not available. In that case, try uninstalling and reinstalling PIL using:

    pip uninstall PILpip install PIL
  • If that doesn't work, try using Pillow instead

    pip uninstall PILpip install pillow


The following code works fine with me:

brew install zbarpip install pyqrcodepip install pyzbar

For QR code image creation:

import pyqrcodeqr = pyqrcode.create("test1")qr.png("test1.png", scale=6)

For QR code decoding:

from PIL import Imagefrom pyzbar.pyzbar import decodedata = decode(Image.open('test1.png'))print(data)

that prints the result:

[Decoded(data=b'test1', type='QRCODE', rect=Rect(left=24, top=24, width=126, height=126), polygon=[Point(x=24, y=24), Point(x=24, y=150), Point(x=150, y=150), Point(x=150, y=24)])]


I'm answering only the part of the question about zbar installation.

I spent nearly half an hour a few hours to make it work on Windows + Python 2.7 64-bit, so here are additional notes to the accepted answer:

PS: Making it work with Python 3.x is even more difficult: Compile zbar for Python 3.x.

PS2: I just tested pyzbar with pip install pyzbar and it's MUCH easier, it works out-of-the-box (the only thing is you need to have VC Redist 2013 files installed). It is also recommended to use this library in this pyimagesearch.com article.