How to Generate and Read QR Code in Python

Plaban Nayak
3 min readSep 7, 2020

QR code is a type of matrix barcode that is machine readable optical label which contains information about the item to which it is attached. In practice, QR codes often contain data for a locator, identifier, or tracker that points to a website or application, etc.

Problem Statement :

Generate and read QR codes in Python using qrcode and OpenCV libraries

Installing required dependencies:

pyqrcode module is a QR code generator. The module automates most of the building process for creating QR codes. This module attempts to follow the QR code standard as closely as possible. The terminology and the encoding used in pyqrcode come directly from the standard.

pip install pyqrcode

Install an additional module pypng to save image in png format:

pip install pypng

Import Libraries

import pyqrcodeimport pngfrom pyqrcode import QRCodeimport cv2import numpy as np

Create QR Code:

# String which represents the QR codes = “https://medium.com/p/12743ca0a9d9/edit"# output file namefilename = “qrcode.png”# Generate QR codeimg = pyqrcode.create(s)# Create and save the svg file naming “myqr.svg”img.svg(“myqr.svg”, scale = 8)# Create and save the png file naming “myqr.png”img.png(‘myqr.png’, scale = 6)

Output:

Read QR Code

Here we will be using OpenCV for that, as it is popular and easy to integrate with the webcam or any video.

import cv2# read the QRCODE imageimg = cv2.imread('myqr.png')

Image Shape : (270, 270, 3)

Detect QR Code

# initialize the cv2 QRCode detectordetector = cv2.QRCodeDetector()

Decode QR Code:

detectAndDecode() function takes an image as an input and decodes it to return a tuple of 3 values:

  • the data decoded from the QR code,
  • the output array of vertices of the found QR code quadrangle and
  • the output image containing rectified and binarized QR code.
# detect and decodedata, bbox, straight_qrcode = detector.detectAndDecode(img)

We just need data and bbox here, bbox will help us draw the quadrangle in the image and data will be printed to the console!

# if there is a QR codeif bbox is not None:print(f"QRCode data:\n{data}")# display the image with lines# length of bounding boxn_lines = len(bbox)for i in range(n_lines):# draw all linespoint1 = tuple(bbox[i][0])point2 = tuple(bbox[(i+1) % n_lines][0])cv2.line(img, point1, point2, color=(255, 0, 0), thickness=2)

Output:

QRCode data: https://medium.com/p/12743ca0a9d9/edit

Drawa blue quadrangle around the QR Code and print it on the console:

  • cv2.line() function draws a line segment connecting two points, we retrieve these points from bbox array that was decoded by detectAndDecode() previously.
  • (255, 0, 0) is blue color as OpenCV uses BGR colors and thickness of 2.
# display the result
cv2.imshow("image", image)
cv2.waitKey(0)
cv2.destroyAllWindows()

connect

--

--