2

I am looking for an easy way to decode QR Codes in png format in python 3. Many of the previous answers I found, seem to only work with python 2. For example the qrtools package does not work, because zbar does not work with python 3.

It would be very helpful if someone could suggest a package to use and provide a basic example on how to decode the QR code.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
phil
  • 225
  • 1
  • 4
  • 13

2 Answers2

13

You can use pyzbar

From their docs:

from pyzbar.pyzbar import decode
from PIL import Image
decode(Image.open('pyzbar/tests/code128.png'))
Nader Alexan
  • 2,127
  • 22
  • 36
  • In a python 3.6 envirionment in Anaconda Prompt version 4.8.3 on a WIndows 10 Pro N system, the `pip install pyzbar` command installs sucesfully but it yields error: `OSError: [WinError 126] The specified module could not be found` on your code. https://stackoverflow.com/questions/61033939/error-installing-pyzbar-with-conda-on-mac-os-x suggests to use `zbarlight` which yields an error on installing in that python 3.6 envirionment in Anaconda Prompt. I have not yet found a qr code decoding solution in python 3.6 in Anaconda Prompt. – a.t. Aug 06 '20 at 19:39
  • 1
    @a.t. this is likely irrelevant of `pyzbar` and due to using a pip that is installing the package outside of the anaconda environment. Consider the solutions here: https://stackoverflow.com/a/43729857/1223945 – Nader Alexan Aug 07 '20 at 07:24
  • Thank your for your suggestion, after following the steps you suggested I found some DLL files were missing. The problem was that I did not have the correct Visual C++ Redistributable Packages installed. After installing the correct package and rebooting Anaconda prompt it worked. Detailed solution here: https://stackoverflow.com/questions/63296571/decode-a-qr-code-in-python-3-6-in-anaconda-4-8-3-on-64-bit-windows/63299174#63299174. – a.t. Aug 07 '20 at 10:22
1

You can refer here for more detailed tutorial pyzbar + opencv for python 3

In nutshell:

from pyzbar import pyzbar
import cv2

img_path = 'image.png'

img = cv2.imread(img_path)

barcodes = pyzbar.decode(img)

for barcode in barcodes:
    (x, y, w, h) = barcode.rect
    cv2.rectangle(img, (x, y), (x + w, y + h), (0, 0, 255), 2)
    barcodeData = barcode.data.decode("utf-8")
    barcodeType = barcode.type
    text = "{} ({})".format(barcodeData, barcodeType)
    cv2.putText(img, text, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
    print("[INFO] found {} barcode {}".format(barcodeType, barcodeData))

cv2.imwrite("new_img.jpg", img)
Akson
  • 681
  • 8
  • 8