Last active
November 10, 2015 18:16
-
-
Save dmitriy-t/b1c0d453283a5305d46d to your computer and use it in GitHub Desktop.
This is the version of "simple_barcode_detection.py" from Adrian Rosebrock, updated for use with OpenCV 3.0 (note lines 14, 15, 34, 44)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Original files and article is here: | |
# http://www.pyimagesearch.com/2014/12/15/real-time-barcode-detection-video-python-opencv | |
# import the necessary packages | |
import numpy as np | |
import cv2 | |
def detect(image): | |
# convert the image to grayscale | |
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) | |
# compute the Scharr gradient magnitude representation of the images | |
# in both the x and y direction | |
gradX = cv2.Sobel(gray, ddepth=cv2.CV_32F, dx=1, dy=0, ksize=-1) | |
gradY = cv2.Sobel(gray, ddepth=cv2.CV_32F, dx=0, dy=1, ksize=-1) | |
# subtract the y-gradient from the x-gradient | |
gradient = cv2.subtract(gradX, gradY) | |
gradient = cv2.convertScaleAbs(gradient) | |
# blur and threshold the image | |
blurred = cv2.blur(gradient, (9, 9)) | |
(_, thresh) = cv2.threshold(blurred, 225, 255, cv2.THRESH_BINARY) | |
# 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) | |
# perform a series of erosions and dilations | |
closed = cv2.erode(closed, None, iterations=4) | |
closed = cv2.dilate(closed, None, iterations=4) | |
# find the contours in the thresholded image | |
(_, cnts, _) = cv2.findContours(closed.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) | |
# if no contours were found, return None | |
if len(cnts) == 0: | |
return None | |
# otherwise, sort the contours by area and compute the rotated | |
# bounding box of the largest contour | |
c = sorted(cnts, key=cv2.contourArea, reverse=True)[0] | |
rect = cv2.minAreaRect(c) | |
box = np.int0(cv2.boxPoints(rect)) | |
# return the bounding box of the barcode | |
return box |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment