Detect and Read Barcodes with OpenCV in Python
Last Updated :
03 May, 2024
A barcode is a graphical representation of data that is machine-readable. It consists of parallel lines or rectangles of varying widths and spacings, along with specific patterns, that encode information. Barcodes are widely used for automatic identification and tracking of products, assets, inventory, and more. In this article, we will see how we can detect and read barcodes with OpenCV in Python.
Detect and Read Barcodes with OpenCV in Python
Below is the step-by-step procedure by which we can detect and read barcodes with OpenCV in Python:
Step 1: Create a Virtual Environment
This is the first step in which we will create a virtual environment by using the following commands in your terminal:
python -m venv venv
.\venv\Scripts\activate
Step 2: Installation
At first, we will install OpenCV, Matplotlib, and pyzbar by using the following command:
pip install opencv-python matplotlib pyzbar
Step 3: Import Libraries
In this step, we have imported the following libraries:
- cv2: This is the OpenCV library used for computer vision tasks.
- decode from pyzbar.pyzbar: This function is used to decode the barcode data from an image.
- matplotlib.pyplot as plt: This library is used for visualizing the image with detected barcodes.
Python3
import cv2
from pyzbar.pyzbar import decode
import matplotlib.pyplot as plt
Step 4: Define Function to Detect and Decode Barcodes
In this step, the function detect_and_decode_barcode
aims to identify and decode barcodes present in an input image. It begins by converting the image to grayscale and then proceeds to detect barcodes using the decode
function. For each detected barcode, it extracts the data and type, draws a rectangle around it, and annotates the image with the extracted information. Finally, it displays the annotated image with the detected barcodes using Matplotlib.
Python3
def detect_and_decode_barcode(image):
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Detect barcodes in the grayscale image
barcodes = decode(gray)
# Loop over detected barcodes
for barcode in barcodes:
# Extract barcode data and type
barcode_data = barcode.data.decode("utf-8")
barcode_type = barcode.type
# Print barcode data and type
print("Barcode Data:", barcode_data)
print("Barcode Type:", barcode_type)
# Draw a rectangle around the barcode
(x, y, w, h) = barcode.rect
cv2.rectangle(image, (x, y), (x + w, y + h), (255, 0, 0), 2)
# Put barcode data and type on the image
cv2.putText(image, f"{barcode_data} ({barcode_type})",
(x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 2)
# Convert image from BGR to RGB (Matplotlib uses RGB)
image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
plt.imshow(image_rgb)
plt.axis('off')
plt.show()
Step 5: Read Input Image and Call the Function
In this step, we are reading the input image and calling the function.
Python3
# Read input image
image = cv2.imread("your path:/barcode_image.png")
detect_and_decode_barcode(image)
Step 6: Run the Program
To run the program, type the following command:
python main.py
Barcode Used
barcode_image3.png
Output:
Barcode Data: Wikipedia
Barcode Type: CODE128

Real-World Applications of Barcode Detection
- Retail: Barcodes streamline sales and inventory tracking in stores.
- Logistics: They track goods from production to delivery.
- Healthcare: Barcodes ensure accurate patient and medication identification.
- Transportation: Used for ticketing and boarding passes.
- Asset Management: Track equipment and resources efficiently.
- Manufacturing: Monitor production and manage inventory.
- Events: Barcodes serve as tickets for entry and access control.
- Food Packaging: Ensure product traceability and compliance.
- Education: Barcodes simplify library book management and student tracking.
Similar Reads
Detecting ArUco markers with OpenCV and Python ArUco markers are widely used in computer vision applications for tasks such as camera calibration, pose estimation, and augmented reality. These markers are square fiducial markers with a unique binary pattern that can be easily detected by computer vision algorithms. In this article, we will explo
6 min read
Convert BGR and RGB with Python - OpenCV Prerequisites: OpenCV OpenCV is a huge open-source library for computer vision, machine learning, and image processing. OpenCV supports a wide variety of programming languages like Python, C++, Java, etc. It can process images and videos to identify objects, faces, or even the handwriting of a human
2 min read
White and black dot detection using OpenCV | Python Image processing using Python is one of the hottest topics in today's world. But image processing is a bit complex and beginners get bored in their first approach. So in this article, we have a very basic image processing python program to count black dots in white surface and white dots in the blac
4 min read
Detect an object with OpenCV-Python Object detection refers to identifying and locating objects within images or videos. OpenCV provides a simple way to implement object detection using Haar Cascades a classifier trained to detect objects based on positive and negative images. In this article we will focus on detecting objects using i
4 min read
Eye blink detection with OpenCV, Python, and dlib In this article, we are going to see how to detect eye blink using OpenCV, Python, and dlib. This is a fairly simple task and it requires you to have a basic understanding of OpenCV and how to implement face landmark detection programs using OpenCV and dlib, since we'll be using that as the base for
6 min read
Getting Started with Python OpenCV Computer Vision is one of the techniques from which we can understand images and videos and can extract information from them. It is a subset of artificial intelligence that collects information from digital images or videos. Python OpenCV is the most popular computer vision library. By using it, o
15+ min read
How to Make a Barcode Reader in Python? Barcode represents data in graphical representation and is machine-readable. For making Barcode Reader in Python we are using pyzbar library. Using pyzbar we can decode the one-dimensional barcode and QR code. This pyzbar can return 3 fields based on the barcode object: Type: There are several kind
2 min read
Contour Detection with Custom Seeds using Python - OpenCV This article discusses how we can dynamically detect contours by clicking on the Image and assign different colors to different parts of the image. Contours are a very useful tool for shape analysis and object detection and recognition. Â This program uses OpenCV, Numpy, and Matplotlib libraries. Â It
3 min read
Reading an image in OpenCV using Python Prerequisite: Basics of OpenCVIn this article, we'll try to open an image by using OpenCV (Open Source Computer Vision) library.  Following types of files are supported in OpenCV library:Windows bitmaps - *.bmp, *.dibJPEG files - *.jpeg, *.jpgPortable Network Graphics - *.png WebP - *.webp Sun raste
6 min read