Qr code reading python

qreader 2.13

Robust and Straight-Forward solution for reading difficult and tricky QR codes within images in Python. Supported by a YOLOv7 QR Detection model.

Ссылки проекта

Статистика

Метаданные

Лицензия: MIT License (MIT)

Сопровождающие

Классификаторы

  • Development Status
    • 5 — Production/Stable
    • Developers
    • Science/Research
    • OSI Approved :: MIT License
    • OS Independent
    • Python :: 3
    • Scientific/Engineering :: Image Recognition
    • Software Development :: Libraries :: Python Modules
    • Utilities

    Описание проекта

    QReader

    QReader is a Robust and Straight-Forward solution for reading difficult and tricky QR codes within images in Python. Powered by a YOLOv7 model.

    Behind the scenes, the library is composed by two main building blocks: A QR Detector based on a YOLOv7 model trained on a large dataset of QR codes (also offered as stand-alone), and the Pyzbar QR Decoder. On top of Pyzbar, QReader transparently applyes different image preprocessing techniques that maximize the decoding rate on difficult images.

    Installation

    To install QReader, simply run:

    If you’re not using Windows, you may need to install some additional pyzbar dependencies:

    sudo apt-get install libzbar0

    NOTE: If you’re running QReader in a server with very limited resources, you may want to install the CPU version of PyTorch, before installing QReader. To do so, run: pip install torch —no-cache-dir (Thanks to @cjwalther for his advice).

    Usage

    QReader is a very simple and straight-forward library. For most use cases, you’ll only need to call detect_and_decode :

        detect_and_decode will return a tuple containing the decoded string of every QR found in the image. NOTE: Some entries can be None , it will happen when a QR have been detected but couldn't be decoded.

    API Reference

    QReader(reencode_to = ‘shift-jis’)

    This is the main class of the library. Please, try to instantiate it just once to avoid loading the model every time you need to detect a QR code.

    • reencode_to : str or None. The encoding to reencode the utf-8 decoded QR string. If None, it won’t re-encode. If you find some characters being decoded incorrectly, try to set a Code Page that matches your specific charset. Recommendations that have been found useful:
      • ‘shift-jis’ for Germanic languages
      • ‘cp65001’ for Asian languages (Thanks to @nguyen-viet-hung for the suggestion)

      QReader.detect_and_decode(image, return_bboxes = False)

      This method will decode the QR codes in the given image and return the decoded strings (or None, if any of them could be detected but not decoded).

      • image : np.ndarray. NumPy Array containing the image to decode. The image is expected to be in uint8 format [HxWxC], RGB.
      • return_bboxes : boolean. If True , it will also return the bboxes of each detected QR. Default: False
      • Returns: tuple[str | None] | tuple[tuple[tuple[int, int, int, int], str | None]]: A tuple with all detected QR codes decodified. If return_bboxes is False , the output will look like: (‘Decoded QR 1’, ‘Decoded QR 2’, None, ‘Decoded QR 4’, . ) . If return_bboxes is True it will look like: (((x1_1, y1_1, x2_1, y2_1), ‘Decoded QR 1’), ((x1_2, y1_2, x2_2, y2_2), ‘Decoded QR 2’), . ) .

      QReader.detect(image)

      This method detects the QR codes in the image and returns the bounding boxes surrounding them in the format (x1, y1, x2, y2).

      • image : np.ndarray. NumPy Array containing the image to decode. The image must is expected to be in uint8 format [HxWxC], RGB.
      • Returns: tuple[tuple[int, int, int, int]]. The bounding boxes of the QR code in the format ((x1_1, y1_1, x2_1, y2_1), (x1_1, y1_1, x2_1, x2_2)) .

      NOTE: This the only function you will need? Take a look at QRDet.

      QReader.decode(image, bbox = None)

      This method decodes a single QR code on the given image, if a bbox is given (recommended) it will only look within that delimited region.

      Internally, this method will run the pyzbar decoder, using different image preprocessing techniques (sharpening, binarization, blurring. ) every time it fails to increase the detection rate.

      • image : np.ndarray. NumPy Array containing the image to decode. The image must is expected to be in uint8 format [HxWxC], RGB.
      • bbox : tuple[int, int, int, int] | None. The bounding box of the QR code in the format (x1, y1, x2, y2) [that’s the output of detect ]. If None , it will look for the QR code in the whole image (not recommended). Default: None .
      • Returns: str. The decoded text of the QR code. If no QR code can be decoded, it will return None .

      Usage Tests

      Two sample images. At left, an image taken with a mobile phone. At right, a 64×64 QR pasted over a drawing.

      The following code will try to decode these images containing QRs with QReader, pyzbar and OpenCV.

            QReader:   The output of the previous code is:
      Image: test_mobile.jpeg -> QReader: ('https://github.com/Eric-Canas/QReader'). OpenCV: . pyzbar: (). Image: test_draw_64x64.jpeg -> QReader: ('https://github.com/Eric-Canas/QReader'). OpenCV: . pyzbar: ().

      Note that QReader internally uses pyzbar as decoder. The improved detection-decoding rate that QReader achieves comes from the combination of different image pre-processing techniques and the YOLOv7 based QR detector that is able to detect QR codes in harder conditions than classical Computer Vision methods.

      Acknowledgements

      This library is based on the following projects:

      • YoloV7 model for Object Detection.
      • PyzbarQR Decoder.
      • OpenCV methods for image filtering.

      Источник

      Python QR Code Reader: How to Build a High-Performance QR Code Scanner

      Python QR Code Reader

      Have you ever wanted to build an efficient and high-performance QR code scanner? In this blog post, we will explore how to build a high-performance Python QR code reader. We will walk through the steps to read and decode QR codes in Python. We will also discuss ways to detect and read distorted, incorrect or damaged QR codes. Whether you’re a developer looking to add QR code functionality to your application or a hobbyist interested in learning more about this technology, this post will provide valuable insights.

      The following topics will be covered in this article:

      Python QR Code Reader API#

      We can generate and read QR code in Python using Aspose.BarCode for Python. It is a powerful Python QR Code library that allows developers to easily add barcode generation and recognition functionality to their Python applications. It supports a wide variety of barcode formats, including linear and 2D barcodes, and can be used to generate barcodes in various image formats, such as JPEG, PNG, and GIF. The API also provides the ability to recognize barcodes from images and read their data.

      Please either download the Python QR Code library package or install the API from PyPI using the following pip command in the console:

      pip install aspose-barcode-for-python-via-net 

      Read QR Code in Python#

      We can read QR code in Python with Aspose.BarCode for Python by following the steps given below:

      1. Create an instance of the BarCodeReader class.
      2. Call the read_bar_codes() method and get recognition results.
      3. Finally, loop through the results and show the recognized type and code text.

      The following code sample shows how to read a QR code in Python.

      Read QR Code in Python

      Read Incorrect QR Code#

      We can read corrupt, damaged, low-qualit, and blur QR codes using Aspose.BarCode for Python. For this purpose, we can specify quality settings to detect, recognize and read such QR codes.

      We can read evidently incorrect QR code by following the steps given below:

      1. Firstly, create an instance of the BarCodeReader class.
      2. Next, specify the allow_incorrect_barcodes and read_tiny_barcodesquality_settings to True.
      3. After that, call the read_bar_codes() method and get recognition results.
      4. Finally, loop through the results and show the recognized type and code text.

      The following code sample shows how to read evidently incorrect QR code in Python.

      Read Incorrect QR Code in Python.

      Recognize Distorted QR Code#

      We can read distorted or damaged QR code by following the steps mentioned earlier. However, we need to set allow_qr_micro_qr_restoration property to true.

      The following code sample shows how to read distorted QR code in Python.

      Read Distorted QR Code in Python.

      Detecting Colored QR Code on Colored Background#

      We can also read colored QR code from a colored background image by following the steps mentioned earlier. However, we need to set allow_complex_background property to true.

      The following code sample shows how to read colored QR code in Python.

      Read Colored QR Code in Python.

      Python QR Code Reader — Get a Free License#

      Aspose offers a free evaluation version that can be used to test the features and capabilities of the library. You can get a free temporary license to try the library without evaluation limitations.

      Read QR Code Online#

      You may read QR code online for free using the online QR code Reader web app which is developed using this API. Please access the Free online QR code Reader App on the following link:

      Python QR Code Scanner — Scan QR Code Online#

      You may also scan QR code online for free using the online QR code scanner which is developed using this API. You need to connect the camera to scan the QR code. Please access the Free online QR code scanner App on the following link:

      Python QR Code Library — Learning Resources#

      You can learn more about generating QR code and explore other features of Aspose.BarCode for Python using the resources given below:

      Conclusion#

      In this blog post, we’ve shown you how to develop your own customized Python QR Code Reader with Python QR Code library. By following the steps outlined in this guide, you can easily generate QR codes for different types of data. With just a few lines of code, you can create beautiful QR codes that can be used for website links, contact information, and more. Whether you’re a developer, marketer, or just someone looking to create a QR code for personal use, the Aspose.BarCode for Python is the perfect solution. Try it out for yourself and see how easy it is to create stunning QR codes in just minutes. In case of any ambiguity, please feel free to contact us on our free support forum.

      See Also#

      • Aspose.BarCode Product Family
      • Color QR Code Reader
      • Read QR Code
      • Scan QR Code
      • Python QR Code Scanner
      • Read QR Code from Image
      • Read QR Code in Python
      • qr-code
      • QR Code Reader
      • Aspose QR Code
      • Free Online QR Code Reader
      • Micro QR Code Reader
      • How to Read QR Code
      • Read QR Code Online
      • Aspose Barcode Library
      • Aspose QR Code Reader
      • QR Code Library Python
      • QR Code Python
      • Scan QR Code Online
      • QR Code Scanner Python
      • Python QR Code Library

      Источник

      Генерация и считывание QR-кода в Python

      Генерация и считывание QR-кода в Python

      Статьи

      Введение

      В данной статье научимся генерировать и считывать QR-код в языке программирования Python.

      Генерация QR-кода в Python

      Чтобы сгенерировать QR-код нам нужен модуль под названием qrcode. Для его установки нужно перейти в терминал/командную строку, прописать pip install qrcode, нажать Enter и ждать установки.

      После инсталляции модуля мы его импортируем:

      Теперь сохраним в переменную data ссылку, на которую будет вести QR-код. Это может быть всё что угодно, но в качестве примера я укажу ссылку на этот сайт:

      import qrcode data = "https://it-start.online"

      Далее нам нужно сгенерировать сам QR-код. Для этого используем функцию make():

      import qrcode data = "https://it-start.online" img = qrcode.make(data)

      Методом save() сохраним итоговый результат:

      import qrcode data = "https://it-start.online" img = qrcode.make(data) img.save('qr-code name.png')

      Считывание QR-кода в Python

      Для считывания QR-кода нам понадобится библиотека под названием cv2. Для её установки нужно перейти в терминал/командную строку, прописать pip install opencv-python нажать Enter и ждать установки.

      После инсталляции импортируем библиотеку cv2:

      При помощи функции imread() откроем изображение с QR-кодом:

      import cv2 img = cv2.imread('qr-code name.png')

      Создадим экземпляр класса QRCodeDetector():

      import cv2 img = cv2.imread('qr-code name.png') detector = cv2.QRCodeDetector()

      Осталось считать qr-код и вывести в консоль:

      import cv2 img = cv2.imread("qr-code name.png") detector = cv2.QRCodeDetector() data, bbox, straight_qrcode = detector.detectAndDecode(img) print(f"Данные из qr-кода: ") # Вывод: Данные из qr-кода: https://it-start.online

      Заключение

      В ходе статьи мы с Вами научились генерировать и считывать QR-коды в языке программирования Python. Надеюсь Вам понравилась статья, желаю удачи и успехов! 🙂

      Источник

      Читайте также:  Php static var in method
Оцените статью