Title: Detecting Barcodes in Images with Python and OpenCV - PyImageSearch

URL Source: https://pyimagesearch.com/2014/11/24/detecting-barcodes-images-python-opencv/

Published Time: 2014-11-24T15:00:46+00:00

Markdown Content:
[![Image 1: Detecting Barcodes in Images with Python and OpenCV](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20600%20225'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2014/11/barcode_gradient_and_detection.jpg)

**UPDATE:** The introduction to this post may seen a little “out there”. For some context, I had just finished watching the _South Park Black Friday episodes_ prior to writing this post so I definitely had some inspiration regarding zombie shoppers, Black Friday chaos, and _Game of Thrones_.

* * *

Black Friday is coming.

Hordes of angry shoppers. Stampedes of middle-aged midwestern women, their toothless gums bloodthirsty for 75% off the latest season of _Game of Thrones_ at the local Wal-Mart.

They’ll lineup outside the Wal-Mat doors on Thanksgiving at midnight. They’ll rally, beating at the locked doors with their hands and heads until their bodies are raw and bloody, like zombies from _28 Days Later_. But instead of human flesh, they crave petty consumer sustenance. Their war cries of discounts and sales will reach the heavens. And their thunderous footsteps will cause earthquakes across the Great Plains.

Of course, the media won’t help — they will sensationalize every last little piece. From frostbitten families camping out all night in the blistering cold, to the little old lady trampled by raging bargain hunters as the doors open, akin to the Gallimimus stampede in _Jurassic Park_. All of this simply because she wanted to purchase the latest Halo game for Timmy, her little 9 year old grandson, who’s parents passed away this time last year. At a Wal-Mart. During Black Friday.

And I have to ask, is all this chaos and bedlam worth it?

_**Hell. No.**_

Any shopping I do this Black Friday will be from (safely) behind my laptop screen, likely nursing a hangover from the night before with a cup of coffee and a handful of Tylenol.

But if you decide you are going to venture out into the real-world and brave the bargain hunters, **_you’ll want to download the source code to this blog post first…_**

Imagine how silly you would feel, standing in line, waiting to checkout, only to scan the barcode on the latest season of _Game of Thrones_ only to find out that Target has it for $5 cheaper?

In the rest of this blog post I’ll show you how to detect barcodes in images using nothing but Python and OpenCV.

![Image 2](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20128%20128'%3E%3C/svg%3E)

#### Looking for the source code to this post?

[Jump Right To The Downloads Section](#download-the-code)

The goal of this blog post is to demonstrate a basic implementation of barcode detection using computer vision and image processing techniques. My implementation of the algorithm is originally based loosely on [this StackOverflow question](http://stackoverflow.com/questions/9013703/how-to-find-the-location-of-red-region-in-an-image-using-matlab/9014569). I have gone through the code and provided some updates and improvements to the original algorithm.

It’s important to note that this algorithm will not work for _all_ barcodes, but it should give you the basic intuition as to what types of techniques you should be applying.

For this example, we will be detecting the barcode in the following image:

[![Image 3: Figure 1: Example image containing a barcode that we want to detect.](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20600%20450'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2014/11/barcode_01.jpg)

**Figure 1:** Example image containing a barcode that we want to detect.

Let’s go ahead and start writing some code. Open up a new file, name it `detect_barcode.py` , and let’s get coding:

\# import the necessary packages
import numpy as np
import argparse
import imutils
import cv2

# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add\_argument("-i", "--image", required = True,
	help = "path to the image file")
args = vars(ap.parse\_args())

The first thing we’ll do is import the packages we’ll need. We’ll utilize NumPy for numeric processing, `argparse` for parsing [command line arguments](https://pyimagesearch.com/2018/03/12/python-argparse-command-line-arguments/), and `cv2` for our OpenCV bindings.

Then we’ll setup our command line arguments. We need just a single switch here, `--image` , which is the path to our image that contains a barcode that we want to detect.

Now, time for some actual image processing:

\# load the image and convert it to grayscale
image = cv2.imread(args\["image"\])
gray = cv2.cvtColor(image, cv2.COLOR\_BGR2GRAY)

# compute the Scharr gradient magnitude representation of the images
# in both the x and y direction using OpenCV 2.4
ddepth = cv2.cv.CV\_32F if imutils.is\_cv2() else cv2.CV\_32F
gradX = cv2.Sobel(gray, ddepth=ddepth, dx=1, dy=0, ksize=-1)
gradY = cv2.Sobel(gray, ddepth=ddepth, dx=0, dy=1, ksize=-1)

# subtract the y-gradient from the x-gradient
gradient = cv2.subtract(gradX, gradY)
gradient = cv2.convertScaleAbs(gradient)

On **Lines 14 and 15** we load our `image` off disk and convert it to grayscale.

Then, we use the Scharr operator (specified using `ksize = -1` ) to construct the gradient magnitude representation of the grayscale image in the horizontal and vertical directions on **Lines 19-21**.

From there, we subtract the _y_\-gradient of the Scharr operator from the _x_\-gradient of the Scharr operator on **Lines 24 and 25**. By performing this subtraction we are left with regions of the image that have high horizontal gradients and low vertical gradients.

Our `gradient` representation of our original image above looks like:

[![Image 4: Figure 2: The gradient representation of our barcode image.](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20600%20493'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2014/11/barcode_gradient.jpg)

**Figure 2:** The gradient representation of our barcode image.

**Notice how the barcoded region of the image has been detected by our gradient operations.** The next steps will be to filter out the noise in the image and focus solely on the barcode region.

\# blur and threshold the image
blurred = cv2.blur(gradient, (9, 9))
(\_, thresh) = cv2.threshold(blurred, 225, 255, cv2.THRESH\_BINARY)

The first thing we’ll do is apply an average blur on **Line 28** to the gradient image using a _9 x 9_ kernel. This will help smooth out high frequency noise in the gradient representation of the image.

We’ll then threshold the blurred image on **Line 29**. Any pixel in the gradient image that is not greater than 225 is set to 0 (black). Otherwise, the pixel is set to 255 (white).

The output of the blurring and thresholding looks like this:

[![Image 5: Figure 3: Thresholding the gradient image to obtain a rough approximation to the rectangular barcode region.](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20600%20493'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2014/11/barcode_threhsold.jpg)

**Figure 3:** Thresholding the gradient image to obtain a rough approximation to the rectangular barcode region.

However, as you can see in the threshold image above, _there are gaps between the vertical bars of the barcode._ In order to close these gaps and make it easier for our algorithm to detect the “blob”-like region of the barcode, we’ll need to perform some basic morphological operations:

\# construct a closing kernel and apply it to the thresholded image
kernel = cv2.getStructuringElement(cv2.MORPH\_RECT, (21, 7))
closed = cv2.morphologyEx(thresh, cv2.MORPH\_CLOSE, kernel)

We’ll start by constructing a rectangular kernel using the `cv2.getStructuringElement` on **Line 32**. This kernel has a width that is larger than the height, thus allowing us to close the gaps between vertical stripes of the barcode.

We then perform our morphological operation on **Line 33** by applying our kernel to our thresholded image, thus attempting to close the the gaps between the bars.

You can now see that the gaps are substantially more closed, as compared to the thresholded image above:

[![Image 6: Figure 4: Applying closing morphological operations to close the gap between barcode stripes.](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20600%20493'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2014/11/barcode_closing.jpg)

**Figure 4:** Applying closing morphological operations to close the gap between barcode stripes.

Of course, now we have small blobs in the image that are not part of the actual barcode, but may interfere with our contour detection.

Let’s go ahead and try to remove these small blobs:

\# perform a series of erosions and dilations
closed = cv2.erode(closed, None, iterations = 4)
closed = cv2.dilate(closed, None, iterations = 4)

All we are doing here is performing 4 iterations of erosions, followed by 4 iterations of dilations. An erosion will “erode” the white pixels in the image, thus removing the small blobs, whereas a dilation will “dilate” the remaining white pixels and grow the white regions back out.

Provided that the small blobs were removed during the erosion, they will not reappear during the dilation.

After our series of erosions and dilations you can see that the small blobs have been successfully removed and we are left with the barcode region:

[![Image 7: Figure 5: Removing small, irrelevant blobs by applying a series of erosions and dilations.](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20600%20492'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2014/11/barcode_erosion_and_dilation.jpg)

**Figure 5:** Removing small, irrelevant blobs by applying a series of erosions and dilations.

Finally, let’s find the contours of the barcoded region of the image:

\# find the contours in the thresholded image, then sort the contours
# by their area, keeping only the largest one
cnts = cv2.findContours(closed.copy(), cv2.RETR\_EXTERNAL,
	cv2.CHAIN\_APPROX\_SIMPLE)
cnts = imutils.grab\_contours(cnts)
c = sorted(cnts, key = cv2.contourArea, reverse = True)\[0\]

# compute the rotated bounding box of the largest contour
rect = cv2.minAreaRect(c)
box = cv2.cv.BoxPoints(rect) if imutils.is\_cv2() else cv2.boxPoints(rect)
box = np.int0(box)

# draw a bounding box arounded the detected barcode and display the
# image
cv2.drawContours(image, \[box\], -1, (0, 255, 0), 3)
cv2.imshow("Image", image)
cv2.waitKey(0)

Luckily, this is the easy part. On **Lines 41-44** we simply find the largest contour in the image, which if we have done our image processing steps correctly, should correspond to the barcoded region.

We then determine the minimum bounding box for the largest contour on **Lines 47-49** and finally display the detected barcode on **Lines 53-55**.

As you can see in the following image, we have successfully detected the barcode:

[![Image 8: Figure 6: Successfully detecting the barcode in our example image.](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20600%20493'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2014/11/barcode_results_01.jpg)

**Figure 6:** Successfully detecting the barcode in our example image.

In the next section we’ll try a few more images.

### Successful Barcode Detections

To follow along with these results, use the form at the bottom of this post to download the source code and accompanying images for this blog post.

Struggling with running the code in this section? Take a look at my [command line arguments](https://pyimagesearch.com/2018/03/12/python-argparse-command-line-arguments/) blog post.

Once you have the code and images, open up a terminal and execute the following command:

$ python detect\_barcode.py --image images/barcode\_02.jpg

[![Image 9: Figure 7: Using OpenCV to detect a barcode in an image.](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20600%20783'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2014/11/barcode_results_02.jpg)

**Figure 7:** Using OpenCV to detect a barcode in an image.

No problem detecting the barcode on that jar of coconut oil!

Let’s try another image:

$ python detect\_barcode.py --image images/barcode\_03.jpg

[![Image 10: Figure 8: Using computer vision to detect a barcode in an image.](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20600%20783'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2014/11/barcode_results_03.jpg)

**Figure 8:** Using computer vision to detect a barcode in an image.

We were able to find the barcode in that image too!

But enough of the food products, what about the barcode on a book:

$ python detect\_barcode.py --image images/barcode\_04.jpg

[![Image 11: Figure 9: Detecting a barcode on a book using Python and OpenCV.](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20600%20783'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2014/11/barcode_results_04.jpg)

**Figure 9:** Detecting a barcode on a book using Python and OpenCV.

Again, no problem!

How about the tracking code on a package?

$ python detect\_barcode.py --image images/barcode\_05.jpg

[![Image 12: Figure 10: Detecting the barcode on a package using computer vision and image processing.](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20600%20783'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2014/11/barcode_results_05.jpg)

**Figure 10:** Detecting the barcode on a package using computer vision and image processing.

Again, our algorithm is able to successfully detect the barcode.

Finally, let’s try one more image This one is of my favorite pasta sauce, Rao’s Homemade Vodka Sauce:

$ python detect\_barcode.py --image images/barcode\_06.jpg

[![Image 13: Figure 12: Barcode detection is easy using Python and OpenCV!](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20600%20783'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2014/11/barcode_results_06.jpg)

**Figure 11:** Barcode detection is easy using Python and OpenCV!

We were once again able to detect the barcode!

### What's next? We recommend [PyImageSearch University](https://pyimagesearch.com/pyimagesearch-university/?utm_source=blogPost&utm_medium=bottomBanner&utm_campaign=What%27s%20next%3F%20I%20recommend).

**Course information:**  
84 total classes • 114+ hours of on-demand code walkthrough videos • Last updated: February 2024  
★★★★★ 4.84 (128 Ratings) • 16,000+ Students Enrolled

**I strongly believe that if you had the right teacher you could _master_ computer vision and deep learning.**

Do you think learning computer vision and deep learning has to be time-consuming, overwhelming, and complicated? Or has to involve complex mathematics and equations? Or requires a degree in computer science?

That’s _not_ the case.

All you need to master computer vision and deep learning is for someone to explain things to you in _simple, intuitive_ terms. _And that’s exactly what I do_. My mission is to change education and how complex Artificial Intelligence topics are taught.

If you're serious about learning computer vision, your next stop should be PyImageSearch University, the most comprehensive computer vision, deep learning, and OpenCV course online today. Here you’ll learn how to _successfully_ and _confidently_ apply computer vision to your work, research, and projects. Join me in computer vision mastery.

**Inside PyImageSearch University you'll find:**

*   ✓ **84 courses** on essential computer vision, deep learning, and OpenCV topics
*   ✓ **84 Certificates** of Completion
*   ✓ **114+ hours** of on-demand video
*   ✓ **Brand new courses released _regularly_**, ensuring you can keep up with state-of-the-art techniques
*   ✓ **Pre-configured Jupyter Notebooks in Google Colab**
*   ✓ Run all code examples in your web browser — works on Windows, macOS, and Linux (no dev environment configuration required!)
*   ✓ Access to **centralized code repos for _all_ 536+ tutorials** on PyImageSearch
*   ✓ **Easy one-click downloads** for code, datasets, pre-trained models, etc.
*   ✓ **Access** on mobile, laptop, desktop, etc.

[Click here to join PyImageSearch University](https://pyimagesearch.com/pyimagesearch-university/?utm_source=blogPost&utm_medium=bottomBanner&utm_campaign=What%27s%20next%3F%20I%20recommend)

Summary
-------

In this blog post we reviewed the steps necessary to detect barcodes in images using computer vision techniques. We implemented our algorithm using the Python programming language and the OpenCV library.

The general outline of the algorithm is to:

1.  Compute the Scharr gradient magnitude representations in both the _x_ and _y_ direction.
2.  Subtract the _y_\-gradient from the _x_\-gradient to reveal the barcoded region.
3.  Blur and threshold the image.
4.  Apply a closing kernel to the thresholded image.
5.  Perform a series of dilations and erosions.
6.  Find the largest contour in the image, which is now presumably the barcode.

It is important to note that since this method makes assumptions regarding the gradient representations of the image, and thus will only work for horizontal barcodes.

If you wanted to implement a more robust barcode detection algorithm, you would need to take the orientation of the image into consideration, or better yet, apply machine learning techniques such as Haar cascades or HOG + Linear SVM to “scan” the image for barcoded regions.

![Image 14](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20410%20567'%3E%3C/svg%3E)

#### Download the Source Code and FREE 17-page Resource Guide

Enter your email address below to get a .zip of the code and a **FREE 17-page Resource Guide on Computer Vision, OpenCV, and Deep Learning.** Inside you'll find my hand-picked tutorials, books, courses, and libraries to help you master CV and DL!