Ora

How do I import a QR code into Python?

Published in Python QR Code Processing 7 mins read

Importing a QR code into Python typically refers to either generating a new QR code from data or decoding an existing QR code image to extract its embedded information. Both processes allow you to effectively work with QR codes within your Python applications.

Here's a breakdown of how to achieve both, ensuring you can "import" QR code functionality and data into your Python projects.


Understanding QR Code Operations in Python

Before diving into the specifics, it's helpful to understand the two main operations when working with QR codes in Python:

Operation Description Primary Python Libraries
Generation Creating a new QR code image from text, URLs, or other data. qrcode
Decoding Reading an existing QR code image (e.g., from a file or webcam feed) to extract its embedded data. pyzbar with Pillow or OpenCV (cv2)

1. Generating QR Codes in Python (Creating a New QR Code)

To create QR codes, the qrcode library is the most widely used and straightforward tool in Python.

Step 1: Install the qrcode Library

You can install the qrcode library using the pip package manager. Open your command prompt or terminal and type:

pip install qrcode

If you also want to save the QR code as an image file (like PNG), you'll need the Pillow library, which qrcode uses for image rendering:

pip install Pillow

Step 2: Import and Use the qrcode Library

Once installed, you can import the library into your Python script and use its functions to create QR codes. Here's a basic example:

import qrcode

# The data you want to encode in the QR code
data = "https://www.example.com/my-awesome-link"

# Generate QR code
# This creates a QR code object
qr_code_object = qrcode.make(data)

# Save the QR code as an image file
qr_code_object.save("my_generated_qr_code.png")

print("QR code generated and saved as my_generated_qr_code.png")

This simple script will create a file named my_generated_qr_code.png in the same directory as your Python script, containing the QR code for "https://www.example.com/my-awesome-link".

Step 3: Customizing Your QR Code

The qrcode library offers various customization options to control the appearance and robustness of your QR code.

  • Version: Controls the size and data capacity. (1 to 40, smaller for less data).
  • Error Correction: Determines how much data can be recovered if the QR code is damaged.
    • qrcode.constants.ERROR_CORRECT_L: ~7% or less errors can be corrected.
    • qrcode.constants.ERROR_CORRECT_M: ~15% or less errors can be corrected (default).
    • qrcode.constants.ERROR_CORRECT_Q: ~25% or less errors can be corrected.
    • qrcode.constants.ERROR_CORRECT_H: ~30% or less errors can be corrected.
  • Box Size: How many pixels each "box" or square of the QR code is.
  • Border: How many boxes thick the white border around the QR code should be.

Here's an example using more advanced customization:

import qrcode
from qrcode.constants import ERROR_CORRECT_H

# Data to encode
my_website = "https://www.python.org"

# Create a QR code instance with custom settings
qr = qrcode.QRCode(
    version=1,  # Version 1 is a 21x21 matrix, good for small data
    error_correction=ERROR_CORRECT_H, # High error correction (30%)
    box_size=10, # Each box/pixel of the QR code is 10x10 pixels
    border=4, # 4-box thick white border
)

# Add data to the QR code
qr.add_data(my_website)
qr.make(fit=True) # Automatically scales the size to fit the data

# Create an image from the QR code data
img = qr.make_image(fill_color="black", back_color="white")

# Save the customized QR code
img.save("python_org_qr_custom.png")

print("Customized QR code generated and saved as python_org_qr_custom.png")

For more details on qrcode library, refer to its PyPI page.


2. Decoding QR Codes in Python (Reading an Existing QR Code)

To "import" an existing QR code, you'll need to decode its image to extract the embedded data. The pyzbar library, often used with Pillow or OpenCV, is excellent for this task.

Step 1: Install Necessary Libraries

You'll typically need pyzbar for the decoding logic and Pillow (for basic image handling) or OpenCV (cv2, for more advanced image processing, especially with webcams).

pip install pyzbar Pillow
# OR for OpenCV:
# pip install pyzbar opencv-python

Step 2: Decoding a QR Code from an Image File

This example demonstrates how to read a QR code from an image file using pyzbar and Pillow.

from PIL import Image
from pyzbar.pyzbar import decode

def decode_qr_code(image_path):
    """
    Decodes QR codes from an image file.

    Args:
        image_path (str): The path to the image file containing the QR code.

    Returns:
        list: A list of decoded data from all QR codes found, or an empty list.
    """
    try:
        # Open the image file
        img = Image.open(image_path)

        # Decode QR codes from the image
        decoded_objects = decode(img)

        if not decoded_objects:
            print(f"No QR code found in {image_path}")
            return []
        else:
            decoded_data = []
            for obj in decoded_objects:
                print(f"Decoded data: {obj.data.decode('utf-8')}")
                decoded_data.append(obj.data.decode('utf-8'))
            return decoded_data

    except FileNotFoundError:
        print(f"Error: Image file not found at {image_path}")
        return []
    except Exception as e:
        print(f"An error occurred: {e}")
        return []

# Example usage:
# First, ensure you have a QR code image file (e.g., 'my_generated_qr_code.png' from the previous section)
image_file = "my_generated_qr_code.png"
decoded_info = decode_qr_code(image_file)

if decoded_info:
    print(f"Successfully decoded: {decoded_info}")

Step 3: Decoding QR Codes from a Webcam Feed (using OpenCV)

For real-time QR code scanning, OpenCV is often preferred due to its powerful video and image processing capabilities.

import cv2
from pyzbar.pyzbar import decode

def decode_qr_from_webcam():
    """
    Continuously scans for QR codes using a webcam feed.
    Press 'q' to quit.
    """
    # Initialize the webcam
    cap = cv2.VideoCapture(0) # 0 for default webcam

    if not cap.isOpened():
        print("Error: Could not open webcam.")
        return

    print("Scanning for QR codes. Press 'q' to quit.")

    while True:
        # Read frame by frame
        ret, frame = cap.read()
        if not ret:
            print("Failed to grab frame.")
            break

        # Convert frame to grayscale (often helps with detection)
        gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

        # Decode QR codes from the frame
        decoded_objects = decode(gray_frame)

        # Draw bounding boxes and display data
        for obj in decoded_objects:
            decoded_data = obj.data.decode('utf-8')
            print(f"QR Code Detected: {decoded_data}")

            # Draw a bounding box around the QR code
            points = obj.polygon
            if len(points) == 4:
                # The points are ordered TL, TR, BR, BL
                cv2.polylines(frame, [cv2.UMat(points)], True, (0, 255, 0), 2)
            elif len(points) > 0:
                # If not a perfect rectangle, draw a simple rectangle around min/max
                x, y, w, h = obj.rect
                cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)

            # Put the decoded text near the QR code
            cv2.putText(frame, decoded_data, (obj.rect.left, obj.rect.top - 10),
                        cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)

        # Display the frame
        cv2.imshow("QR Code Scanner", frame)

        # Break the loop if 'q' is pressed
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

    # Release the webcam and close all OpenCV windows
    cap.release()
    cv2.destroyAllWindows()

# Example usage:
# Ensure your webcam is available and you have opencv-python installed.
# decode_qr_from_webcam()

By leveraging these libraries, you can effectively incorporate QR code generation and decoding capabilities into your Python applications, handling both creating new codes and "importing" data from existing ones.