SoFunction
Updated on 2025-04-11

OpenCV and Pyzbar detect QR codes and barcodes

Overview

In modern society, QR codes and barcodes are widely used, from product tags to payment QR codes, they are almost everywhere. This article will explain in detail how to detect and identify QR codes and barcodes in Python using OpenCV and Pyzbar libraries, and demonstrate the entire process with specific code examples.

Environmental preparation

Before you begin, make sure you have the required libraries installed. You can install it through the following command:

pip install opencv-python pyzbar

Complete sample code details

import cv2
import numpy as np
from pyzbar import pyzbar

class CodeFinder:
    """
     QR code, barcode detection
     """
    def __init__(self):
        """
         Initialize the camera and set the resolution
         """
         = (0)  # Turn on the default camera        (3, 640)  # Set the video width to 640 pixels        (4, 480)  # Set the video height to 480 pixels
    def run(self):
        """
         Capture videos and detect QR codes and barcodes
         """
        while True:
            success, img = ()  # Read a frame of video            if not success:
                print("Failed to read frame")
                break

            # Detect QR codes and barcodes in images            for bar_code in (img):
                # Decode QR code data                print(bar_code.('utf8'))  # Print QR code data                print(bar_code.type)  # Print QR code type                print(bar_code.rect)  # Print the boundary of the QR code (rectangular box)                print(bar_code.polygon)  # Print QR code polygon border                print(bar_code.quality)  # Print QR code quality                print(bar_code.orientation)  # Print the QR code direction
                # Draw the QR code boundary                points = (bar_code.polygon, np.int32)
                points = ((-1, 1, 2))
                (img=img, pts=[points], isClosed=True, color=(0, 0, 255), thickness=3)

                # Display QR code data on the image                (
                    img=img,
                    text=bar_code.('utf8'),
                    org=(bar_code., bar_code.),
                    fontFace=cv2.FONT_HERSHEY_SIMPLEX,
                    fontScale=0.8,
                    color=(0, 0, 255),
                    thickness=2
                )

            # Show image            ('code', img)

            # Press the 'q' key to exit the loop            if (1) & 0xFF == ord('q'):
                ()  # Release camera resources                ()  # Close all OpenCV windows                break

if __name__ == '__main__':
    code_finder = CodeFinder()
    code_finder.run()

Code parsing

1. Import the necessary libraries

import cv2
import numpy as np
from pyzbar import pyzbar
  • cv2: OpenCV's Python interface for image and video processing.
  • numpy: an array used to process image data.
  • pyzbar: A library for decoding QR codes and barcodes.

2. Define the CodeFinder class

class CodeFinder:
    """
     QR code, barcode detection
     """
    def __init__(self):
        """
         Initialize the camera and set the resolution
         """
         = (0)  # Turn on the default camera        (3, 640)  # Set the video width to 640 pixels        (4, 480)  # Set the video height to 480 pixels

Initialize the camera:

= (0): Turn on the default camera (ID is 0).

(3, 640): Set the video width to 640 pixels.

(4, 480): Set the video height to 480 pixels.

3. Define the run method

def run(self):
    """
     Capture videos and detect QR codes and barcodes
     """
    while True:
        success, img = ()  # Read a frame of video        if not success:
            print("Failed to read frame")
            break

        # Detect QR codes and barcodes in images        for bar_code in (img):
            # Decode QR code data            print(bar_code.('utf8'))  # Print QR code data            print(bar_code.type)  # Print QR code type            print(bar_code.rect)  # Print the boundary of the QR code (rectangular box)            print(bar_code.polygon)  # Print QR code polygon border            print(bar_code.quality)  # Print QR code quality            print(bar_code.orientation)  # Print the QR code direction
            # Draw the QR code boundary            points = (bar_code.polygon, np.int32)
            points = ((-1, 1, 2))
            (img=img, pts=[points], isClosed=True, color=(0, 0, 255), thickness=3)

            # Display QR code data on the image            (
                img=img,
                text=bar_code.('utf8'),
                org=(bar_code., bar_code.),
                fontFace=cv2.FONT_HERSHEY_SIMPLEX,
                fontScale=0.8,
                color=(0, 0, 255),
                thickness=2
            )

        # Show image        ('code', img)

        # Press the 'q' key to exit the loop        if (1) & 0xFF == ord('q'):
            ()  # Release camera resources            ()  # Close all OpenCV windows            break

Read video frames:

success, img = (): Read a frame of video. success indicates whether it is successfully read, img is the image read.

If the read fails, print the error message and exit the loop.

Detect QR codes and barcodes:

  • for bar_code in (img): Use the () function to detect QR codes and barcodes in the image.
  • print(bar_code.('utf8')): Print QR code data.
  • print(bar_code.type): Print the QR code type.
  • print(bar_code.rect): Print the boundary of the surrounding QR code (rectangular box).
  • print(bar_code.polygon): Print the QR code polygon border.
  • print(bar_code.quality): print QR code quality.
  • print(bar_code.orientation): Print the QR code direction.

Draw the QR code boundary:

points = (bar_code.polygon, np.int32): Convert QR code polygon borders to NumPy array.

points = ((-1, 1, 2)): Reshape the array shape.

(img=img, pts=[points], isClosed=True, color=(0, 0, 255), thickness=3): Use the () function to draw a polygon border.

Display QR code data on the image:

(): Display QR code data on the image.

text=bar_code.('utf8'): The text content to be displayed.

org=(bar_code., bar_code.): The starting position of the text.

fontFace=cv2.FONT_HERSHEY_SIMPLEX: The font type used.

fontScale=0.8: Font size.

color=(0, 0, 255): text color.

thickness=2: Text line width.

Show image:

('code', img): Show image.

Key detection:

if (1) & 0xFF == ord('q'): Wait for 1 millisecond, if a key is pressed, return to the ASCII code of the key. ord('q') returns the ASCII code of the character 'q'. If the key is ‘q’, the loop is exited.

(): Release camera resources.

(): Close all OpenCV windows.

4. Main function

if __name__ == '__main__':
    code_finder = CodeFinder()
    code_finder.run()

Main function:

if __name__ == '__main__':: Make sure that the following code is executed only when the script is run directly.

Create a CodeFinder object and call the run method to start QR code and barcode detection.

Summarize

This article details how to detect and identify QR codes and barcodes in Python using OpenCV and Pyzbar libraries, and demonstrates the entire process with specific code examples. By using functions such as (), (), (), () and (), we can easily process QR code and barcode data in the video stream.

This is the article about OpenCV and Pyzbar detection of QR codes and barcodes. For more related content on OpenCV Pyzbar detection of QR codes and barcodes, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!