A QR code (Quick Response code) is a type of matrix barcode that stores encoded data. It was named “Quick Response code” because of its capability to store and access large data in no time. You can find these QR codes everywhere: posters, magazines, cinema halls, websites, gyms, advertisements, etc.

Using Python you can generate your own QR code, customize it, and decode information from a QR code.

Setup a Python Environment

It is recommended to set up an isolated environment for Python projects. By doing this, you can understand more about the dependencies of the project.

Creating a Virtual Environment

You can create a virtual environment in Python in a number of ways: virtualenv, virtualenvwrapper, or Anaconda distribution. Here we will use virtualenv to create a virtual environment.

  1. Create a folder using the mkdir [Folder] command, where you want to create this project.
  2. Type cd [Folder] in the command prompt to move into the new directory.
  3. Type virtualenv [Environment Name] to create a virtual environment.
  4. Activate the virtual environment by typing [Environment Name]\Scripts\activate
QR Code Virtual Environment

Install Required Packages

Install the required Python packages using the pip command. Make sure you have pip installed on your system.

Run the following command in your command prompt.

        pip3 install opencv-python qrcode numpy Image
    

If you don’t want to install all packages in one go, you can install them one by one as:

        pip3 install opencv-python
    

This installs the opencv-python package which is mainly used for computer vision, machine learning, and image processing.

        pip3 install qrcode
    

This installs the qrcode python package which is used for generating and reading QR codes.

        pip3 install numpy
    

This installs the numpy python package which is used for working with arrays.

        pip3 install Image
    

This installs the Image python package which provides a number of functions to load images from files and to create new images.

Generate QR Code

To generate the code, create a new file with a .py extension which will have the code to generate the QR code.

Paste the following code in your Python file and run the program.

        import qrcode

# Data for which you want to make QR code
# Here we are using the URL of the MakeUseOf website
data = "https://www.makeuseof.com/"

# File name of the QR code Image
# Change it with your desired file name
QRCodefile = "MUOQRCode.png"

# Generating the QR code
QRimage = qrcode.make(data)

# Saving image into a file
QRimage.save(QRCodefile)

This will create a QR code image (MUOQRCode.png) for the given data (in this case, www.makeuseof.com). The generated QR code will look something like this:

MUO QR Code

Generate a Customised QR Code

You can customise the QR code with the amazing features of the qrcode library. You can change the fill color, background color, image size, box size and border thickness of the QR code.

Changing Image and Box Size

You can change the QR code image size using the version parameter in the QRCode class. It accepts an integer between 1 and 40 where 1 is equivalent to 21x21 matrix and 40 is equivalent to 185x185 matrix. Note that the data doesn’t fit in the specified size, the version will scale up automatically.

Similarly, you can change the box size using the box_size parameter in the QRCode class. It specifies the pixels of each box in the QR code.

        # Importing libraries
import qrcode
import numpy as np

# Data which for you want to make QR code
# Here we are using URL of MakeUseOf website
data = "https://www.makeuseof.com/"

# Name of the QR code Image file
QRCodefile = "CustomisedImgBoxQRCode.png"

# instantiate QRCode object
qrObject = qrcode.QRCode(version=1, box_size=12)
# add data to the QR code
qrObject.add_data(data)
# compile the data into a QR code array
qrObject.make()

image = qrObject.make_image()
image.save(QRCodefile)

# print the image size (version)
print("Size of the QR image(Version):")
print(np.array(qrObject.get_matrix()).shape)

The following QR code image file will be generated:

Customised Box Size MUO QR Code

Also, the following output will be displayed-

        Size of the QR image(Version):
(33, 33)

Note that the version is automatically scaled up according to the size of the data.

Changing Fill Color

You can change the fill color of the QR code by using the fill_color parameter.

        # Importing library
import qrcode

# Data for which you want to make QR Code
# Here we are using URL of MakeUseOf website
data = "https://www.makeuseof.com/"

# Name of the QR Code Image file
QRCodefile = "CustomisedFillColorQRCode.png"

# instantiate QRCode object
qrObject = qrcode.QRCode()

# add data to the QR code
qrObject.add_data(data)

# compile the data into a QR code array
qrObject.make()
image = qrObject.make_image(fill_color="red")

# Saving image into a file
image.save(QRCodefile)

The following QR code image file will be generated:

Customised Fill Color MUO QR Code

Changing Background Color

You can change the background color of the QR code by using the back_color parameter.

        # Importing library
import qrcode

# Data for which you want to make QR Code
# Here we are using URL of MakeUseOf website
data = "https://www.makeuseof.com/"

# Name of the QR Code Image file
QRCodefile = "CustomisedBGColorQRCode.png"

# instantiate QRCode object
qrObject = qrcode.QRCode()

# add data to the QR code
qrObject.add_data(data)

# compile the data into a QR code array
qrObject.make()
image = qrObject.make_image(back_color="blue")

# Saving image into a file
image.save(QRCodefile)

The following QR code image file will be generated:

Customised BG Color MUO QR Code

Changing Border Thickness

You can change the border thickness of the QR code by using the border parameter in the QRCode class.

        # Importing libraries
import qrcode

# Data for which you want to make QR Code
# Here we are using URL of MakeUseOf website
data = "https://www.makeuseof.com/"

# Name of the QR Code Image file
QRCodefile = "CustomisedBorderQRCode.png"

# instantiate QRCode object
qrObject = qrcode.QRCode(border=10)
# add data to the QR code
qrObject.add_data(data)
# compile the data into a QR code array
qrObject.make()

image = qrObject.make_image()
image.save(QRCodefile)

The following QR code image file will be generated:

Customised Border QR Code

Decode QR Code Using QR Code Image

You can decode information from the QR code image using Python's OpenCV library. OpenCV has an inbuilt QR code detector. Using the detector you can decode data out of the QR code.

        # Import Library
import cv2

# Name of the QR Code Image file
filename = "MUOQRCode.png"

# read the QRCODE image
image = cv2.imread(filename)

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

# detect and decode
data, vertices_array, binary_qrcode = detector.detectAndDecode(image)

# if there is a QR code
# print the data
if vertices_array is not None:
  print("QRCode data:")
  print(data)
else:
  print("There was some error")

If the image provided is a valid QR code, decoded data will be displayed. In this case, the following output will be generated-

        QRCode data:
https://www.makeuseof.com/

Decode QR Code Live Using a Webcam

Most of the time people tend to use a webcam for scanning QR codes. Using the potential of Python and OpenCV library you can easily decode data from a QR code.

        import cv2

# initalize the camera
cap = cv2.VideoCapture(0)

# initialize the OpenCV QRCode detector
detector = cv2.QRCodeDetector()

while True:
  _, img = cap.read()

  # detect and decode
  data, vertices_array, _ = detector.detectAndDecode(img)

  # check if there is a QRCode in the image
  if vertices_array is not None:
    if data:
      print("QR Code detected, data:", data)

  # display the result
  cv2.imshow("img", img)

  # Enter q to Quit
  if cv2.waitKey(1) == ord("q"):
    break

cap.release()
cv2.destroyAllWindows()

When you execute this code, your webcam will be automatically opened. Simply hold the QR code in front of the webcam and the data will be decoded and displayed in the command prompt.

Encoding and Decoding QR Code Made Easy

Using this article you can easily encode, decode and customise QR codes as you want. You can even create a complete QR code Scanner-Generator application using the code provided.

There are a number of creative ways to use QR codes. Get creative and use the QR codes as you want.