zxing-cpp Python Bindings
zxing-cpp provides Python bindings for the high-performance C++ port of the ZXing barcode library. It supports reading and writing a wide range of 1D and 2D barcode formats like QR Code, Data Matrix, UPC-A, and Code 128. The current version is 3.0.0, and it maintains an active development and release cadence, typically tied to its underlying C++ library.
Common errors
-
FileNotFoundError: [WinError 2] The system cannot find the file specified
cause The image file specified in `cv2.imread()` or similar image loading function does not exist at the given path or is inaccessible.fixDouble-check the file path. Use an absolute path or ensure your relative path is correct from the script's current working directory (`os.getcwd()`). On Windows, ensure path separators are handled correctly (e.g., `r'C:\path\image.png'` or `'C:/path/image.png'`). -
Could not find any barcode.
cause The `read_barcodes` function returned an empty list, indicating no barcode was detected. This can be due to poor image quality (blur, low resolution, bad lighting, shadows, angle), an unsupported barcode format, or the barcode being too small/damaged.fixImprove image quality (ensure good lighting, focus, contrast). Try rotating or downscaling the image before passing it to `read_barcodes`. Ensure the barcode format is one of the supported types by `zxing-cpp`. For critical cases, inspect image binarization/thresholding parameters or consider `try_rotate` and `try_downscale` options in `read_barcodes` for more robust detection. -
AttributeError: 'Barcode' object has no attribute 'some_attribute'
cause Attempting to access a non-existent attribute on the `Barcode` result object. This often happens if users expect a different data structure for properties like 'position' (e.g., direct x,y tuples instead of a string representation) or misremember attribute names.fixConsult the `zxing-cpp` documentation or the `PYBIND11_MODULE` definition in the C++ source for the exact properties and their types on the `Barcode` object. For position, it's typically a string that needs parsing if numerical coordinates are required. Common attributes include `text`, `format`, `content_type`, `position`.
Warnings
- breaking Version 3.0.0 introduced significant changes to the creator/writer API, including `BarcodeFormat` and `BarcodeFormats` implementations. The old writer API (`write_barcode`) is now deprecated and `create_barcode` is the default.
- breaking Building `zxing-cpp` from source now explicitly requires a C++20 compliant compiler (e.g., GCC 11+, Clang 12+, VS 2019 16.10+) and CMake 3.18 or newer for the Python module. Without pre-built wheels, this can cause build failures.
- gotcha When reading images, especially from file paths, ensure the path is correct and accessible. `FileNotFoundError` is a common issue, particularly on Windows where path separators (`\` vs `/`) or relative vs. absolute paths can cause problems.
- gotcha `zxing-cpp` is highly optimized for single barcode detection but may struggle with images containing multiple barcodes, exhibiting lower success rates compared to some other libraries in such scenarios.
Install
-
pip install zxing-cpp -
pip install zxing-cpp --no-binary zxing-cpp
Imports
- zxingcpp
import zxingcpp
- BarcodeFormat
from zxingcpp import BarcodeFormat
- read_barcodes
import zxingcpp # ... barcodes = zxingcpp.read_barcodes(image_data)
- create_barcode
import zxingcpp # ... barcode = zxingcpp.create_barcode(text, zxingcpp.BarcodeFormat.QRCode)
Quickstart
import zxingcpp
import cv2
from PIL import Image
import numpy as np
# --- Example 1: Reading a barcode from an image (requires OpenCV) ---
# Create a dummy image with a QR code (in a real scenario, load from file)
# For demonstration, we'll generate one and save it
def generate_and_save_qr_code(text, filename="test_qr.png"):
barcode_obj = zxingcpp.create_barcode(text, zxingcpp.BarcodeFormat.QRCode, ec_level="50%")
img_array = barcode_obj.to_image(scale=5)
Image.fromarray(img_array).save(filename)
print(f"Generated '{filename}' for reading example.")
qr_text = "Hello, zxing-cpp!"
generate_and_save_qr_code(qr_text)
# Read the generated image
img = cv2.imread('test_qr.png')
if img is not None:
results = zxingcpp.read_barcodes(img)
if results:
for result in results:
print(f"\nFound barcode (read):\n Text: '{result.text}'\n Format: {result.format}\n Position: {result.position}")
else:
print("\nCould not find any barcode in test_qr.png.")
else:
print("\nError: Could not load test_qr.png for reading.")
# --- Example 2: Writing a barcode to an image (requires Pillow) ---
text_to_encode = "This is a test from zxing-cpp Python!"
barcode_format = zxingcpp.BarcodeFormat.DataMatrix
try:
# Create a barcode object
barcode = zxingcpp.create_barcode(
text_to_encode,
barcode_format,
ec_level="L" # For DataMatrix, 'L' is a common error correction level
)
# Convert the barcode to a NumPy array image
img_array = barcode.to_image(scale=2) # Scale up for better visibility
# Convert NumPy array to PIL Image and save
pil_img = Image.fromarray(img_array)
output_filename = "output_barcode.png"
pil_img.save(output_filename)
print(f"\nSuccessfully wrote {barcode_format} barcode to '{output_filename}'")
# Optionally, convert to SVG string
svg_string = barcode.to_svg(add_quiet_zones=True)
svg_filename = "output_barcode.svg"
with open(svg_filename, "w") as f:
f.write(svg_string)
print(f"Successfully wrote {barcode_format} barcode to '{svg_filename}'")
except Exception as e:
print(f"\nError writing barcode: {e}")