QR Code Solutions: Generate & Scan QR Codes with Python

Updated on Oct 17,2025

Table of Contents

QR codes have become ubiquitous in our modern world, serving as convenient bridges between the physical and digital realms. From scanning restaurant menus to quickly accessing website links, these little squares of encoded information offer a seamless way to share data. This blog explores how to harness the power of Python to both generate and scan QR codes, opening up a wide range of applications and possibilities.

Key Points

Generating QR codes in Python using the 'qrcode' library.

Customizing QR codes with error correction, box size, and border width.

Scanning QR codes from screenshots using 'pyzbar' library.

Extracting the decoded QR code data.

Building a QR code scanner that continuously monitors the screen.

Generating QR Codes with Python

Installing the QR Code Library

To begin generating QR codes in Python, you will need to install the qrcode library. The qrcode library simplifies the process of creating QR codes and offers customization options. Use pip, the Python package installer, to install it using the command:

pip install qrcode

This command will download and install the qrcode library along with its dependencies. Ensuring that your development environment has access to these tools is the initial step in QR code creation, setting the foundation for the functionalities we are about to explore.

Creating a Basic QR Code

Once the qrcode library is installed, generating a basic QR code is straightforward. Create a Python script and follow these steps:

  1. Import the qrcode library.
  2. Create a qrcode object.
  3. Add data to the QR code.
  4. Create an image from the QR code object.
  5. Save the image to a file.

Here’s a code snippet that demonstrates this process:

import qrcode

# Create a QR code instance
qr = qrcode.QRCode(
    version=1, #The version parameter is an integer from 1 to 40 that controls the size of the QR Code (the smallest, for example is 1x1)
    error_correction=qrcode.constants.ERROR_CORRECT_L,
    box_size=10,
    border=4,
)

# Add data to the QR code
data = 'Example URL to Encode in QR Code'
qr.add_data(data)

# Make the QR code
qr.make(fit=True)

# Create an image from the QR Code with specified colors and save it as "example.png"
img = qr.make_image(fill_color="black", back_color="white")
img.save('example.png')

print('QR code saved as example.png')

This code will generate a QR code that, when scanned, will direct the user to the specified URL. You can alter the URL and use the generated QR code for varied applications. Remember to reiterate the QR code generation procedure to improve the keyword density.

Customizing Your QR Codes for Enhanced Appeal

Customizing a QR code improves aesthetics and functionality. Customizations includes error correction, box size, and border width. These settings can be adjusted when creating the qrcode.QRCode object, impacting the code's appearance and resilience.

  • Error Correction: Adjusting the error correction level enhances the QR code’s ability to withstand damage or obstruction. Levels range from ERROR_CORRECT_L (low) to ERROR_CORRECT_H (high), with each level offering varying degrees of redundancy.

  • Box Size: Control the size of each box within the QR code, altering the overall scale and visibility of the code.

  • Border Width: Change the width of the quiet zone (the white border) around the code, which is essential for scanners to recognize the QR code accurately.

The following code demonstrates these customizations:

import qrcode

qr = qrcode.QRCode(
    version=1,
    error_correction=qrcode.constants.ERROR_CORRECT_H, # High level of error correction
    box_size=12,
    border=6,
)

# Add data to the QR code
data = 'Your data here'
qr.add_data(data)
qr.make(fit=True)

img = qr.make_image(fill_color="purple", back_color="yellow")
img.save('custom_qr_code.png')

Increasing the error correction level enhances the QR code’s readability, even when the code is partially damaged. It’s important to reiterate the importance of generating customized QR codes that meet specific aesthetic and functional requirements to reinforce the SEO strategy. The proper QR code, once scanned, helps you transfer data quickly and effectively.

Scanning QR Codes with Python

Setting up the Scanning Environment

Scanning QR codes using Python involves a separate set of tools and libraries. To proceed, you'll need to install pyzbar, a Python library that decodes barcodes and QR codes, and Pillow, an image processing library.

Use the following commands to install these libraries:

pip install pyzbar
pip install Pillow

These commands will install pyzbar and Pillow in your environment. These libraries allow for effective and practical applications of image data and QR code decoding.

Reading QR Codes from Screenshots

To scan and decode QR code from a picture, we are going to use from pyzbar.pyzbar import decode for scanning and openCV and other library for image analysis.

  1. Import necessary libraries: opencv, PIL, pyzbar:
import cv2
from PIL import Image
from pyzbar.pyzbar import decode
  1. Read QR code:
def read_qr_code(filename):
    # Use cv2 to read image from file
    img = cv2.imread(filename)

    # Decode the QR code
    decoded_data = decode(img)

    return decoded_data

The OpenCV’s imread function is used to fetch the image to be decoded. Then the QR Code can be decoded with zbar’s decode() function to obtain its data, that is now return.

  1. Implement a QR code screenshot scanner:
import time
import numpy as np
import cv2
from pyzbar.pyzbar import decode

def capture_screen():  # Captures and decode the qrcode
  capture=True # Set to True to continue capturing the screen

  while(capture):  # Capture screen image continuously
    img = ImageGrab.grab()   #  Take the screenshot of the entire screen
    img_np = np.array(img) # Converts the image to numpy array
    frame = cv2.cvtColor(img_np, cv2.COLOR_BGR2GRAY) # Converts into grayscale mode
    QRcode = decode(frame)  # decode function detect and decode
    for barcode in QRcode: # loop the number of qrcodes are detected
        myData=barcode.data.decode('utf-8') # converts from bytes to String data
        print("Detected QRCode:  ",myData) # print out data
        capture=False # stop the capturing if qrcode exist

    cv2.imshow('Qr Code Scanner', frame) # display stream to screen
    cv2.waitKey(1) # waits to display frame and for keyboard to exit.
    time.sleep(1) #Wait 1 second to take another capture before re looping
        #Release resources and destory windows
    if event.type == pygame.QUIT:
       runing = False
Pygame.quit
Cv2.destoryAllWindows
  1. You need to define and add libraries to capture, decode and save to local directory

    • Install all libraries with pip
   pip install opencv-python
   pip install pillow
   pip install pyzbar 
   pip install pygme
  1. Test Run. Test this scanner with images that contains QR Codes
scanner = QrScanner()
scanner.read_qr_code("code.png")

How to Use

Step-by-Step Guide to QR Code Creation

Here is a detailed usage guide that highlights key aspects, from initializing the QR code to handling different sizes and error corrections.

  1. Install the qrcode library:
pip install qrcode
  1. Configure the QR Code properties. This involves specifying parameters such as:

    • version – version of the code (1-40). As you go higher number, the more data that can be hold in.

    • error the correction – correction level for the qrcode, you can choose between: ERROR the CORRECT the L, ERROR the CORRECT the M, ERROR the CORRECT the Q, ERROR the CORRECT the H

    • box the size = size of each box used to create code.

    • border – margin of the code

qr = qrcode.QRCode(
    version=1,
    error_correction=qrcode.constants.ERROR_CORRECT_L,
    box_size=10,
    border=4,
)
  1. Add data:
data = 'https://example.com'
qr.add_data(data)
  1. Create and Save the QR Code. At this stage, a QR code will be fitted for given data in the version, that is then transformed into image with a black and white squares.
qr.make(fit=True)
img = qr.make_image(fill_color="black", back_color="white")
img.save('example.png')

Generating QR Code in any form and applying the same image in other application is really easy. Proper implementation of these steps helps to make attractive and functional QR code tailored to your exact needs.

Continuous QR Code Scanner

Continuously monitoring the screen for new QR codes requires a while loop combined with time delays to regulate processing.

  1. Capture the current Screen View: To begin scanning, we should first initiate the processes of grabbing data from our screen. To do this we need to import ImageGrab from PIL. ImageGrab is an interface to copy regions from screen that allows the contents of the screen ( or of any part of it ) to be copied to a PIL image memory. At each frame, we will take a screenshot of the entire monitor to detect code in it. Note that this operation can be extremely memory intensive and may be poorly optimized
from PIL import ImageGrab
while(True):
    img = ImageGrab.grab() #  take a screenshot of the entire screen

    //Other operation to run below will operate on img
  1. Converting to Processable Image. The Image from the PIL libraries can be read, and the process must be done in a format compatible with zbar and its decoding functions.

    img_np = np.array(img) # converts the image to numpy array
    frame = cv2.cvtColor(img_np, cv2.COLOR_BGR2GRAY) # converts into grayscale mode
  1. Scanning for codes with QR:
from pyzbar.pyzbar import decode
 QRcode = decode(frame)  # decode function detect and decode
    for barcode in QRcode: # loop the number of qrcodes are detected
        myData=barcode.data.decode('utf-8') # converts from bytes to String data
  1. Printing data and closing:
        print("Detected QRCode:  ",myData) # print out data
        break # stop the capturing if qrcode exist
    cv2.imshow('Qr Code Scanner', frame) # display stream to screen
    cv2.waitKey(1) # waits to display frame and for keyboard to exit.
    time.sleep(1) #Wait 1 second to take another capture before re looping
        #Release resources and destory windows
    if event.type == pygame.QUIT:
       running = False
    Pygame.quit
    Cv2.destoryAllWindows

    This operation provides automated scanning to find code. Remember this is high processing task, hence needs testing for its intended use. The system allows all processes to happen one after another: for each screen that was grabbed using memory, it then runs it through the OpenCV tools for image decode, it finds and scans qrcode in image if available, before returning resources and restarting until quit.

Pricing Considerations

Library Costs for QR Code Generators

Python being open source, many QR code solutions in the form of libraries are free and don't require payments. The libraries qrcode and pyzbar used for QR code generation and scanning are open source. As such, they can be used by developers on commercial projects.

For extensive capabilities, you can consider commercial APIs with subscription or usage based pricing models. Always review licensing information for specific libraries to ensure compliance for commercial use.

Weighing the Pros and Cons of QR Code Generators [t:120]

👍 Pros

Open-Source: Python libraries are often open-source with no licensing cost.

Versatile: Supports different types of use cases, from image to app data transfer.

Customizable: Libraries come with various functionalities that can be tuned to the environment and task at hand.

👎 Cons

Image Processing Heavy: Can be intensive if real time decoding for stream.

Dependency Management: Relies on third party libraries, can create overhead on the install and setup.

Core Features for a Comprehensive QR Code Solution

Key Features to Consider

When evaluating or designing a QR code solution using Python, consider these core features:

  • Efficient Generation: Fast generation capabilities optimized to support multiple formats.
  • Robust Scanning: Adaptability in diverse scanning conditions.
  • Customization Options: Ability to change the look of QR codes.
  • Encoding Options: Supports different data encoding.

Practical Use Cases for Python QR Code Solutions

Diverse Applications

Python-based QR code implementations has numerous uses such as:

  • Event Check-Ins: Automating event attendance through unique QR codes, streamlining the check-in process and enhancing data collection for event organizers.
  • Menu Access in Restaurants: Modernize the dining experience by allowing customers to view menus via QR codes, eliminating the need for single-use menus and providing real-time updates on availability and pricing.
  • Automated Data Transfer: Facilitate secure and efficient data exchange between devices, leveraging QR codes to transmit contact details, Wi-Fi passwords, or payment credentials seamlessly and securely.
  • Inventory Management: Enhance traceability across entire supply chains by embedding QR code to track products throughout their lifecycles, ensuring authenticity and accountability.

Frequently Asked Questions

What makes Python a good choice for QR code tasks?
Python has various factors that facilitate QR code tasks, such as availability and diversity of the libraries. This allows Python to encode data, making them ideal for small amounts of information where reliability and efficiency are key.
How do I select between QR and other barcode technologies?
QR codes allow greater storage with greater versatility making it more attractive in the current data centric landscape. The library options for Python is readily available, as are other QR Scanning apps that make the technology easier to implement into any personal or professional application.
Are There Customization Options to QR Codes Using Python Libraries?
Error checking, box sizes, are few of many customization options available within Python library options. However, keep readability at core and only apply where aesthetics is necessary, as many changes to the code can make it unreadable, and defeat the purpose of efficiency.

Related Questions

What are the main technical factors to consider when deploying a QR code generator?
Deploying a QR code generator involves technical planning regarding scalability and security. You need to plan efficient database, load-balanced systems and secure transactions using SSL. Regular security reviews should be implemented so compliance is maintained when QR and data is used.

Most people like