keepcalculator

06 Numbers and Powers

Barcodes Read Generate Python?

Card No. 06·47244 · Updated · Standard formula, shown below

Yes, Python can both read and generate barcodes. You can create barcode images (like Code 128, EAN-13, QR codes) using libraries such as python-barcode or qrcode, and you can read/decode barcodes from images or camera feeds using pyzbar or OpenCV. This article explains the main libraries, how they work, and how to choose the right one for your project.

Background: What Barcode Support Exists in Python?

Python has a mature ecosystem for barcode handling. The two main tasks are generation (creating an image) and decoding (reading an existing barcode). For generation, the most popular library is python-barcode, which supports common 1D formats like EAN-13, UPC-A, Code 39, and Code 128. For QR codes, the qrcode library is widely used. On the decoding side, pyzbar (a wrapper for the ZBar library) can read 1D and 2D barcodes from images, and OpenCV (with its barcode module in newer versions) can also detect and decode barcodes in real time from a camera feed.

How Barcode Generation Works in Python

Generating a barcode with python-barcode is straightforward. You choose a format, pass the data (e.g., a product number), and save the output as an image (PNG, SVG, etc.). The library automatically adds the correct check digit for formats like EAN-13, so you don’t need to compute it manually. For example, to create a Code 128 barcode:

  1. Install the library: pip install python-barcode
  2. Import and create the barcode: import barcode; from barcode.writer import ImageWriter
  3. Generate and save: code = barcode.get('code128', '1234567890', writer=ImageWriter()); code.save('my_barcode')

The resulting PNG file contains the black-and-white bars that a scanner can read. For QR codes, the qrcode library works similarly: import qrcode; img = qrcode.make('https://example.com'); img.save('qr.png').

How Barcode Reading Works in Python

Reading a barcode typically involves loading an image, pre-processing it (converting to grayscale, thresholding), and then passing it to a decoder. The pyzbar library is the most common choice for simple image files. Here’s a minimal example:

from pyzbar.pyzbar import decode
from PIL import Image

img = Image.open('barcode.png')
results = decode(img)
for barcode in results:
    print(barcode.data.decode('utf-8'))

For live camera input, OpenCV can capture frames and then use pyzbar on each frame. Newer OpenCV versions (4.4+) include a built-in cv2.barcode_BarcodeDetector that can detect and decode without extra libraries. However, it supports fewer formats than ZBar (mainly EAN, UPC, and QR).

How to Choose the Right Library

Your choice depends on the barcode type and the environment:

  • 1D barcodes (EAN, UPC, Code 39, Code 128): Use python-barcode for generation and pyzbar for reading.
  • QR codes (2D): Use qrcode for generation and pyzbar or OpenCV for reading.
  • Real-time camera scanning: OpenCV with pyzbar is the typical combination, but OpenCV’s built-in detector is faster if it supports your format.
  • Web or server-side: You can use the same libraries in a Flask or Django app, but be mindful of image upload sizes and performance.

Common Problems and Pitfalls

Several issues frequently trip up developers:

  • Pillow not installed: python-barcode and qrcode require Pillow for image output. Install it with pip install Pillow.
  • ZBar installation on Windows: pyzbar needs the ZBar DLL. On Windows, you may need to download it manually and add it to your PATH. On Linux, install via apt install libzbar0.
  • Image quality: Blurry, low-contrast, or skewed barcodes often fail to decode. Pre-process images with grayscale conversion, thresholding, or resizing.
  • Data format: Some barcode types (like EAN-13) only accept numeric data. If you pass letters, the library will raise an error.
  • Check digits: For EAN/UPC, the check digit is computed automatically by python-barcode. If you manually provide a check digit, it may be duplicated or rejected.

Comparison: pyzbar vs OpenCV

For decoding, pyzbar and OpenCV take different approaches. pyzbar is a wrapper around ZBar, a long-standing C library that supports a wide range of 1D and 2D formats (EAN, UPC, Code 128, QR, Data Matrix, and more). OpenCV’s built-in detector is limited to EAN-13, EAN-8, UPC-A, UPC-E, and QR codes, but it is optimized for speed and works well with video streams. If you need broad format support, choose pyzbar. If you need speed and are only dealing with common retail codes, OpenCV may be sufficient.

Costs and Alternatives

All the libraries mentioned are open-source and free to use. There are also commercial SDKs (like Dynamsoft or ZXing) that offer better accuracy on difficult images, but they come with licensing fees. For most hobby and internal projects, the free libraries are adequate. If you need to generate barcodes in bulk (e.g., thousands of product labels), you can loop through the generation code, but be aware of performance: writing each image to disk can be slow. Consider generating SVG files (which are smaller) or using a database to store the data and generate images on demand.

Frequently Asked Questions

Can I read a barcode from a webcam with Python?

Yes. Use OpenCV to capture frames from the camera, then pass each frame to pyzbar for decoding. A typical loop reads frames, converts to grayscale, and calls decode(). If the barcode is found, you can break the loop and display the data.

What is the best barcode format for a product label?

It depends on the retailer and region. For consumer retail in Europe, EAN-13 is standard. In North America, UPC-A is common. For internal inventory, Code 128 is a good choice because it encodes all ASCII characters and is compact. For URLs or text, QR codes are ideal.

How do I generate a barcode with a check digit?

Most libraries handle check digits automatically. For example, with python-barcode, when you create an EAN-13 barcode, it computes and appends the check digit. If you need to calculate it manually (e.g., for validation), you can use the standard algorithm: sum alternating digits, multiply by 3, etc.

Why is my barcode not scanning?

Common reasons include: the barcode is too small or too large, the contrast between bars and background is insufficient, the image is blurry, or the barcode is damaged. Try printing at a higher resolution, using a pure white background, and ensuring the quiet zone (white space) on both sides is at least 10 times the width of the narrowest bar.

Can I read barcodes from a PDF file?

Yes, but you need to extract the image first. Use a library like PyPDF2 or pdf2image to convert PDF pages to images, then pass those images to pyzbar. Keep in mind that the quality of the PDF’s embedded images affects reliability.

Is there a way to generate a barcode as a string (not an image)?

Yes, you can generate the raw bars as a string of 1s and 0s using python-barcode’s get_barcode() method, which returns a Barcode object. The object has a render() method that produces a list of bar widths. You can then use that data to draw the barcode with your own rendering code.

Related

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.

More cards in this drawer

The whole Numbers and Powers drawer →