Ever wondered how checkout scanners immediately pull up information about a product? Well, those devices read the barcode, and you can make a simple Barcode Reader in Python with a few lines of code. This project provides a great entrance into computer vision and showcases how Python interfaces with the physical world through images.
In this tutorial, we will walk you through creating a barcode scanner in Python. We’ll use two of the most powerful and popular libraries in Python, OpenCV and pyzbar, to build a simple yet effective tool that can read barcodes from any image.
Create Virtual Environment
Before we actually start coding, it’s a good practice to create a separate workspace for our project. The virtual environment is an isolated space on your computer that keeps your project dependencies separate from others. It prevents conflicts and makes your project more portable.
Open your terminal or command prompt. To set up and activate a virtual environment, run the following commands.
For macOS/Linux:
python3 -m venv scanner-env
source scanner-env/bin/activate
For Windows:
python -m venv scanner-env
scanner-env\Scripts\activate
Your terminal prompt will now show the environment’s name, like (scanner-env), indicating that it is active.
Packages Introduction and Installation
To build our Python barcode scanner, we will use two essential packages:
- OpenCV (opencv-python): A premier computer vision library that we will use to access the webcam and process the live video feed frame by frame.
- pyzbar: This library excels at locating and decoding various types of barcodes from an image or video frame.
Install both packages with a command into your activated virtual environment.
pip install opencv-python pyzbar
With these packages installed, you can start your journey to create Barcode reader or scanner using Python.
Building a Real-Time Barcode Scanner with Your Webcam
Let’s take and example to build live barcode reader which reads barcodes directly from your webcam. Unlike reading a static image, this script will continuously capture frames from your camera, analyze each one for barcodes, and display the results on your screen.
Create a Python file named realtime_scanner.py and add the code below.
import cv2
from pyzbar.pyzbar import decode
cap = cv2.VideoCapture(0)
cap.set(3, 640)
cap.set(4, 480)
print("Starting barcode scanner... Press 'q' to quit.")
while True:
success, frame = cap.read()
if not success:
print("Failed to capture frame from webcam.")
break
for barcode in decode(frame):
x, y, w, h = barcode.rect
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
barcode_data = barcode.data.decode('utf-8')
barcode_type = barcode.type
text = f"{barcode_data} ({barcode_type})"
cv2.putText(frame, text, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
print(f"Found Barcode -> Type: {barcode_type}, Data: {barcode_data}")
cv2.imshow('Real-time Barcode Scanner', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
print("Scanner stopped.")
When you run this script, it activates your webcam. The while True: loop creates a continuous video feed. Inside the loop, cap.read() grabs the latest frame from the camera. The decode function scans this frame for any barcodes.
If a barcode is detected, the program draws a green rectangle around it and displays the decoded information directly on your live video feed. It also prints the barcode data and type to your terminal. The scanner will run until you close the window.
Conclusion
You have now built a working Barcode Reader in Python. This simple project showcases how you can combine libraries like OpenCV and pyzbar in solving real-world problems. From here, you can expand this project in many ways. You could modify the code to use your webcam for a real-time scanner, connect it to a database to look up product information, or build a complete inventory management application. To generate Barcode, you can follow our guide on How to Generate Barcode in Python.
