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

后端 未结 5 1495
时光取名叫无心
时光取名叫无心 2020-12-02 04:10

TL;DR: I need a way to decode a QR-code from an image file using (preferable pure) Python.

I\'ve got a jpg file with a

5条回答
  •  天命终不由人
    2020-12-02 04:46

    There is a library called BoofCV which claims to better than ZBar and other libraries.
    Here are the steps to use that (any OS).

    Pre-requisites:

    • Ensure JDK 14+ is installed and set in $PATH
    • pip install pyboof

    Class to decode:

    import os
    import numpy as np
    import pyboof as pb
    
    pb.init_memmap() #Optional
    
    class QR_Extractor:
        # Src: github.com/lessthanoptimal/PyBoof/blob/master/examples/qrcode_detect.py
        def __init__(self):
            self.detector = pb.FactoryFiducial(np.uint8).qrcode()
        
        def extract(self, img_path):
            if not os.path.isfile(img_path):
                print('File not found:', img_path)
                return None
            image = pb.load_single_band(img_path, np.uint8)
            self.detector.detect(image)
            qr_codes = []
            for qr in self.detector.detections:
                qr_codes.append({
                    'text': qr.message,
                    'points': qr.bounds.convert_tuple()
                })
            return qr_codes
    

    Usage:

    qr_scanner = QR_Extractor()
    output = qr_scanner.extract('Your-Image.jpg')
    print(output)
    

    Tested and works on Python 3.8 (Windows & Ubuntu)

提交回复
热议问题