CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-pyzbar

Read one-dimensional barcodes and QR codes from Python 2 and 3.

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

PyZbar

A pure Python library for reading one-dimensional barcodes and QR codes. PyZbar provides a simple, efficient interface to decode barcodes from various image sources including PIL/Pillow images, OpenCV/imageio/numpy arrays, and raw bytes. It returns detailed information about decoded symbols including the data, barcode type, bounding boxes, and exact polygon coordinates.

Package Information

  • Package Name: pyzbar
  • Language: Python
  • Installation: pip install pyzbar
  • System Dependencies: zbar library (included with Windows wheels, requires separate installation on Linux/macOS)

Core Imports

from pyzbar.pyzbar import decode

Import supporting data types:

from pyzbar.pyzbar import decode, Decoded, Point, Rect, ZBarSymbol

Basic Usage

from pyzbar.pyzbar import decode
from PIL import Image

# Decode from PIL Image
image = Image.open("barcode.png")
decoded_objects = decode(image)

for obj in decoded_objects:
    print(f"Data: {obj.data.decode('utf-8')}")
    print(f"Type: {obj.type}")
    print(f"Rect: {obj.rect}")
    print(f"Polygon: {obj.polygon}")

# Decode from OpenCV/numpy array
import cv2
image = cv2.imread("qrcode.png")
decoded_objects = decode(image)

# Decode from raw bytes
with open("barcode.png", "rb") as f:
    image_data = f.read()
    # Convert to pixel data format: (pixels, width, height)
    # This example assumes you have the pixel data
    decoded_objects = decode((pixels, width, height))

Capabilities

Barcode Decoding

Decodes various barcode and QR code formats from image data, returning detailed information about each symbol found including location coordinates and metadata.

def decode(image, symbols=None):
    """
    Decodes barcodes and QR codes from image data.
    
    Args:
        image: PIL.Image, numpy.ndarray, or tuple (pixels, width, height)
               - PIL.Image: Must be in grayscale ('L' mode) or will be converted
               - numpy.ndarray: 2D or 3D array (3D uses first channel only)
               - tuple: (pixel_bytes, width, height) with 8-bit grayscale pixels
        symbols: iterable of ZBarSymbol constants, optional
                Specific barcode types to decode. If None (default), decodes all types.
    
    Returns:
        list: List of Decoded objects containing barcode information
    """

Symbol Type Constants

Constants representing different barcode and QR code symbol types for selective decoding.

class ZBarSymbol(IntEnum):
    """Enumeration of supported barcode symbol types."""
    NONE = 0          # No symbol decoded
    PARTIAL = 1       # Intermediate status
    EAN2 = 2          # GS1 2-digit add-on
    EAN5 = 5          # GS1 5-digit add-on
    EAN8 = 8          # EAN-8
    UPCE = 9          # UPC-E
    ISBN10 = 10       # ISBN-10 (from EAN-13)
    UPCA = 12         # UPC-A
    EAN13 = 13        # EAN-13
    ISBN13 = 14       # ISBN-13 (from EAN-13)
    COMPOSITE = 15    # EAN/UPC composite
    I25 = 25          # Interleaved 2 of 5
    DATABAR = 34      # GS1 DataBar (RSS)
    DATABAR_EXP = 35  # GS1 DataBar Expanded
    CODABAR = 38      # Codabar
    CODE39 = 39       # Code 39
    PDF417 = 57       # PDF417
    QRCODE = 64       # QR Code
    SQCODE = 80       # SQ Code
    CODE93 = 93       # Code 93
    CODE128 = 128     # Code 128

Geometry Utilities

Functions for computing bounding boxes and convex hulls from coordinate points, useful for analyzing barcode locations and creating custom processing workflows.

def bounding_box(locations):
    """
    Computes the bounding box of coordinate points.
    
    Args:
        locations: iterable of (x, y) coordinate tuples
    
    Returns:
        Rect: Bounding box coordinates
    """

def convex_hull(points):
    """
    Computes the convex hull using Andrew's monotone chain algorithm.
    
    Args:
        points: iterable of (x, y) coordinate tuples
    
    Returns:
        list: List of Point objects forming the convex hull in counter-clockwise order
    """

Library Dependencies

Information about loaded external dependencies, useful for application deployment and freezing.

EXTERNAL_DEPENDENCIES = []  # List of loaded ctypes.CDLL objects

ORIENTATION_AVAILABLE = bool  # Whether orientation detection is available

Types

class Decoded:
    """
    Named tuple containing decoded barcode information.
    
    Attributes:
        data (bytes): The decoded barcode data
        type (str): Barcode type name (e.g., 'CODE128', 'QRCODE')  
        rect (Rect): Bounding rectangle coordinates
        polygon (list): List of (x, y) tuples defining symbol boundary
        quality (int): Quality score of the decode (higher is better)
        orientation (str or None): Symbol orientation ('UP', 'RIGHT', 'DOWN', 'LEFT') if available
    """

class Point:
    """
    Named tuple representing a 2D coordinate point.
    
    Attributes:
        x (int): X coordinate
        y (int): Y coordinate
    """

class Rect:
    """
    Named tuple representing a rectangular bounding box.
    
    Attributes:
        left (int): Left edge X coordinate
        top (int): Top edge Y coordinate  
        width (int): Width of rectangle
        height (int): Height of rectangle
    """

class PyZbarError(Exception):
    """Exception raised when zbar operations fail."""

Usage Examples

Selective Symbol Type Decoding

from pyzbar.pyzbar import decode, ZBarSymbol
from PIL import Image

# Decode only QR codes and Code 128 barcodes
image = Image.open("mixed_codes.png")
qr_and_code128 = decode(image, symbols=[ZBarSymbol.QRCODE, ZBarSymbol.CODE128])

# Decode only QR codes
qr_only = decode(image, symbols=[ZBarSymbol.QRCODE])

Working with OpenCV and NumPy

import cv2
import numpy as np
from pyzbar.pyzbar import decode

# Load image with OpenCV
image = cv2.imread("barcode.png")

# Convert BGR to grayscale if needed (decode handles this automatically)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Decode barcodes
decoded_objects = decode(gray)

for obj in decoded_objects:
    # Get barcode corners for drawing
    points = np.array(obj.polygon, np.int32)
    points = points.reshape((-1, 1, 2))
    
    # Draw polygon around barcode
    cv2.polylines(image, [points], True, (0, 255, 0), 2)
    
    # Add text with barcode data
    x, y = obj.rect.left, obj.rect.top
    cv2.putText(image, obj.data.decode('utf-8'), (x, y-10), 
                cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)

cv2.imshow("Decoded Barcodes", image)
cv2.waitKey(0)

Error Handling

from pyzbar.pyzbar import decode, PyZbarError
from PIL import Image

try:
    image = Image.open("barcode.png")
    decoded_objects = decode(image)
    
    if not decoded_objects:
        print("No barcodes found in image")
    else:
        for obj in decoded_objects:
            print(f"Found {obj.type}: {obj.data.decode('utf-8')}")
            
except PyZbarError as e:
    print(f"Error decoding barcode: {e}")
except Exception as e:
    print(f"General error: {e}")

Working with Raw Image Data

from pyzbar.pyzbar import decode

# Example: decode from raw grayscale pixels
def decode_from_raw_data(pixel_bytes, width, height):
    """Decode barcodes from raw 8-bit grayscale pixel data."""
    
    # Verify data length matches dimensions
    expected_length = width * height
    if len(pixel_bytes) != expected_length:
        raise ValueError(f"Data length {len(pixel_bytes)} doesn't match dimensions {width}x{height}")
    
    # Decode using tuple format
    decoded_objects = decode((pixel_bytes, width, height))
    return decoded_objects

# Usage with hypothetical raw data
width, height = 640, 480
pixel_data = b'\\x00' * (width * height)  # Example grayscale data
results = decode_from_raw_data(pixel_data, width, height)

Installation Notes

System Dependencies

Linux (Ubuntu/Debian):

sudo apt-get install libzbar0
pip install pyzbar

Linux (CentOS/RHEL):

sudo yum install zbar
pip install pyzbar

macOS:

brew install zbar
pip install pyzbar

Windows: Windows wheels include the zbar DLLs, no additional installation required:

pip install pyzbar

Optional Dependencies

For the command-line script functionality:

pip install pyzbar[scripts]  # Includes Pillow for image loading

Command Line Usage

PyZbar includes a command-line script for quick barcode reading:

# Install with script dependencies
pip install pyzbar[scripts]

# Read barcodes from image files
read_zbar image1.png image2.jpg

# Display version
read_zbar --version

The script outputs the decoded data from each barcode found in the specified images.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/pyzbar@0.1.x
Publish Source
CLI
Badge
tessl/pypi-pyzbar badge