Learn How to Generate and Decode QR Code in Python

Introduction

A Quick Response Code or QR Code is a two-dimensional bar code. It became popular in the automotive sector for its large storage capacity and fast readability. 

Being Python lovers, we know what our favorite programming language can do for us. There is a python package named, qrcode which allows us to Generate and Read QR Code using Python programs.

QR code contains encoded data items attached to it. The data could be an identifier, locator, or tracker that links to a website or application. It uses four encoding modes(byte/binary, numeric, alphanumeric, and kanji) to store data.

If we come to the usage of it, I hope everyone knows more or less about that; So, I'm not going deep over there. But here I'll discuss something else.

In this tutorial, You'll learn to

1. How to Generate or Create QR code using Python,

2. Create an Advanced QR Code,

3. Add a logo or an image to a QR code,

4. Decode or read data from a QR code using a python program, etc.

I'll go through various examples so that it becomes easy to understand to you.

👉Visit AlsoConvert text file to QR Code using Python

Installation Process

qrcode: pip install qrcode

Generate a simple QR code in Python

You can create a simple QR code just using four lines of python code. It's so simple right?

I used simple text as the data here. You can add more text to it. Just remember one thing, the more text you add, the QR will become more complex to look.


import qrcode
data = "This is a tutorial on creating QR code in python"
img = qrcode.make(data)
img.save('img1.png')

Output

Create QR Code in shortcut method just using 4 lines of python code.
Simple QR Code

Create an Advanced QR code

Advance QR means nothing special, just adding a URL to it instead of plain text.

I used here 'QRCode' class for creating the QR more advanced. Here, the URL has been added as the data. You will see, this time I made the output QR image green. It looks quite catchy.


import qrcode

# URL of the homepage
# We'll encode this URL to a QR code
URL = "https://pyseek.blogspot.com/"

qr = qrcode.QRCode(version=4, box_size=10, border=4, \
error_correction=qrcode.constants.ERROR_CORRECT_L)

qr.add_data(URL)
qr.make(fit=True)

img = qr.make_image(fill_color='green', back_color='white')
img.save('img2.png')

Output

Create QR Code in advanced method using python qrcode module.
Styled QR Code 1

Let's talk about the arguments I used in the code to pass.

  • version: It takes an integer value. The value is 1 to 40 that controls the size of the QR code. The lowest value is 1, which is a 21x21 matrix. I used number 4 in the code. Which means a little bigger.
  • error_correction: This parameter is used to control the error correction. There are four constants available for it.
    • ERROR_CORRECT_L: 7% or less error can be corrected
    • ERROR_CORRECT_M(default): For 15% or less errors.
    • ERROR_CORRECT_Q: For 25% or fewer errors.
    • ERROR_CORRECT_H: For 30% or fewer errors.
  • border: It controls how many boxes thick the border is.
  • box_size: It controls how many pixels make each box of the QR code.
  • back_color: Background color of the QR code.
  • fill_color: Main color of the QR code. In my case, it's green

Create a Styled QR Code

Let's create a Styled QR image. Styles refer to making a QR with rounded corners, radial gradient, and embed logo or image to the QR, etc.

This time, we will use this StyledPilImage factory(Please look into the code) and an optional module drawer to control the shape of the QR Code.

But one problem may arise with these type of QR images. It may not work with all QR readers.

To avoid it as possible we can, I strongly suggest you set the error correction high while creating. Especially for embedded ones. See the yellow line.

Example 1


'''QR Code with rounded corners'''
import qrcode
from qrcode.image.styledpil import StyledPilImage
from qrcode.image.styles.moduledrawers import RoundedModuleDrawer

qr = qrcode.QRCode(version=4, box_size=10, border=4, \
error_correction=qrcode.constants.ERROR_CORRECT_H)
qr.add_data('https://pyseek.blogspot.com/')

img = qr.make_image(image_factory=StyledPilImage,
module_drawer = RoundedModuleDrawer())
img.save('img3.png')

Output

Styles QR Code which is created by using python qrcode module.
Styled QR Code 2

Example 2

Let's try with an another example. This time we will make the QR image gradiant style.


'''QR Code with radial gradiant style'''
import qrcode
from qrcode.image.styledpil import StyledPilImage
from qrcode.image.styles.colormasks import RadialGradiantColorMask


qr = qrcode.QRCode(version=4, box_size=10, border=4, \
error_correction=qrcode.constants.ERROR_CORRECT_H)

qr.add_data('This is a tutorial on creating QR code in python')
img = qr.make_image(image_factory=StyledPilImage,
color_mask=RadialGradiantColorMask())
img.save('img4.png')

Output

Styled QR Code with radial gradiant which is created using qrcode module.
Styled QR Code 3

Generate QR Code with Logo

You may have noticed that some QR images contain a logo or an image in the middle. A logo can give a QR a professional look.

Here, we'll embed a small icon or photo in the middle of a QR image. But, as I mentioned earlier, You need to use the error correction rate high while generating this type of stylish QR images. Otherwise, the code may not able to read the actual data.


'''Add or Embed an image to a QR Code'''
import qrcode
from qrcode.image.styledpil import StyledPilImage

qr = qrcode.QRCode(version=4, box_size=10, border=4, \
error_correction=qrcode.constants.ERROR_CORRECT_H)

qr.add_data('Embed image on a QR Code')
img = qr.make_image(image_factory=StyledPilImage, \
embeded_image_path="logo2.png")

img.save('img5.png')

Output

Embed or Add logo or image on a QR Code using python qrcode module
QR Code with Logo

Decode or Read a QR Code from an Image

So far we only generated different QR images only. Now, it's time to decode or read that.

Let's create a program which can read the data encoded in a QR. There are several ways to perform it. But here, I'll use the python OpenCV library for the decoding process.

This method is easy to use. You can use it by installing opencv-python only, any other dependencies are not required.

Command: pip install opencv-python


import cv2
# read the QR Code image
img = cv2.imread("img1.png")
# initialize the cv2 QR Code detector
qr_detector = cv2.QRCodeDetector()

# detect QR Code and decode
Data, BBOX, Straight_QRcode = qr_detector.detectAndDecode(img)

# Check if there is a QR code or not.
if BBOX is not None:
if Data:
print(Data)
else:
print("No data is there")
else:
print("There is not any QR code")

Output

This is a tutorial on creating QR code in python

Understand the code

detectAndDecode(): This function detects and decodes the QR code from an image and returns a tuple. This tuple contains the information in compact form. That's why we distributed the data among three variables.

The data variable contains the actual data. BBOX or Bounding Box contains some coordinates. It'll be functional when you desire to show the QR image on another window generated by the program. Otherwise, not.

Conclusion

In this tutorial, you learned how to Generate and Decode QR Code in python. We discussed several examples to understand this topic better. 

I hope now you can create a QR easily using python programs. For any further query please leave your comment below. You'll get an immediate response.

Thanks for reading!💙

PySeek

Subhankar Rakshit

Meet Subhankar Rakshit, a Computer Science postgraduate (M.Sc.) and the creator of PySeek. Subhankar is a programmer, specializes in Python language. With a several years of experience under his belt, he has developed a deep understanding of software development. He enjoys writing blogs on various topics related to Computer Science, Python Programming, and Software Development.

Post a Comment (0)
Previous Post Next Post