Generate and Decode QR Codes in Python

There’s a huge contrast 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 parcel more data compared to a standardized identification. To generate and decode QR Codes we will use some python libraries.

Generate QR Code into image:

Python has a module named “pyqrcode”. By using this module, Its very easy to convert text into qrcode.
You just need that module to be installed in your python library, follow these steps to make it done:-
  • Go to python shell or Cmd.
  • Write a command pip install pyqrcode
  • After pyqrcode installation, install a pypng module if you havn’t install before,
  • Just write the command:- pip install pypng // it uses for generate png images.

Now open your python shell or IDE and simply write the below code:

import pyqrcode 
import png 
from pyqrcode import QRCode 
# String which represents the QR code 
s = “https://techgator.in/” 
# Generate QR code 
url = pyqrcode.create(s) 
# Create and save the svg file naming “techgatorsvg.svg” 
url.svg(“techgatorsvg.svg”, scale = 8) 
# Create and save the png file naming “techgatorpng.png” 
url.png(‘techgatorpng.png’, scale = 6) 
print(“Your QRCode is Ready”)

Reading QR Code from Image:

Python has a module named “qrtools”. By using this module, Its very easy to decode qrcode to read image.
You just need that module to be installed in your python library, follow these steps to make it done:-
  • Go to python shell or Cmd.
  • Write a command pip install pypng zbar pillow qrtools (Where pypng, zbar and pillow are the dependencies required by qrtools).

Now open your python shell or IDE and simply write the below code:

import qrtools
qr = qrtools.QR()
#write path of image in decode(“path of image”)
qr.decode(“techgatorpng.png”)
s = qr.data
print(“The QR code is decoded)
There is also an alternative way using opencv library:
You just need that module to be installed in your python library, follow these steps to make it done:-
  • Go to python shell or Cmd.
  • Write a command pip install pip install opencv-python.

Now open your python shell or IDE and simply write the below code:

import cv2 as cv
im = cv.imread(‘techgatorpng.png’)
det = cv.QRCodeDetector()
#detectAndDecode — Both detect and decode QR code.
retval, points, straight_qrcode = det.detectAndDecode(im)
#retval — Result in a string.
#points — Array of vertices of the found QR code quadrangle. Will be empty if not found.
#straight_qrcode — An image containing rectified and binarized QR code.

Leave a Reply

Your email address will not be published. Required fields are marked *