By reading this piece, you will learn to generate your own QR code and decode QR codes from an image. At the end of this tutorial, you should be able to integrate QR codes functionality into your own Python application. For your information, a QR code is:

“…a two-dimensional pictographic code used for its fast readability and comparatively large storage capacity. The code consists of black modules arranged in a square pattern on a white background. The information encoded can be made up of any kind of data (e.g., binary, alphanumeric, or Kanji symbols)”.

There is a big difference between QR codes and bar codes. Bar codes only hold information in the horizontal direction; a QR code holds information in both horizontal and vertical directions. As a result, a QR code contains a lot more information compared to a barcode.

There are four sections in this tutorial.

  1. Setup
  2. Generate QR code
  3. Decode QR code
  4. Conclusion

Let’s proceed to the next section and start installing the necessary modules


1. Setup

It is highly recommended to create a virtual environment before you continue with the installation. We will be using the following Python packages for this tutorial:

  • python-qrcode — Python QR code image generator. Standard installation includes pillow as well for generating images.
  • opencv-python — Open-source library for computer vision, machine learning, and image processing. It comes with built-in QRCodeDetector class, which helps to decode QR codes.

Installation is pretty straight forward via pip install. Run the following command to install python-qrcode and pillow.

pip install qrcode[pil]

Once you are done, continue installing OpenCV-Python with the following command:

pip install opencv-python

If you intend to detect multiple QR codes in a single image, make sure that the opencv-python version is at least 4.3.0. Older versions do not come with the multi detection functionalities.

Let’s move on to the next section and start writing Python code.


2. Generate QR Code

Import

Add the following import declaration at the top of your Python file.

import qrcode
from PIL import Image

Basic example

For basic usage, you can simply run the make() function to generate a QR Code based on your input text:

img = qrcode.make('Your input text')

#programming #data-science #python #opencv #qr-code #function

How to Generate and Decode QR Codes in Python
25.45 GEEK