在我们识别条码的过程里,首先要找到条码所在的区域,那么怎么样来找到这个条码的区域呢?如果仔细地观察条码,会发现条码有一个特性,就是水平的梯度和垂值的梯度会不一样,如果进行相减,会发现差值比较大。如果其它位置的图像一般不会这样。利用这个特性,就可以把条码所在区域求出来。
创新互联建站是一家专业提供绥宁企业网站建设,专注与网站建设、成都网站制作、H5网站设计、小程序制作等业务。10年已为绥宁众多企业、政府机构等服务。创新互联专业网站设计公司优惠进行中。演示的代码如下:
#python 3.7.4,opencv4.1 #蔡军生 https://blog.csdn.net/caimouse/article/details/51749579 #9073204@qq.com # import numpy as np import cv2 from matplotlib import pyplot as plt #读取图片 img = cv2.imread('barcode6.jpg') # gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) cv2.imshow('gray', gray) 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) gradient = cv2.subtract(gradX, gradY) gradient = cv2.convertScaleAbs(gradient) cv2.imshow('gradient', gradient) blurred = cv2.blur(gradient, (9, 9)) (_, thresh) = cv2.threshold(blurred, 225, 255, cv2.THRESH_BINARY) cv2.imshow('thresh', thresh) kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (21, 7)) closed = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel) closed = cv2.erode(closed, None, iterations = 4) closed = cv2.dilate(closed, None, iterations = 4) cv2.imshow('closed', closed) cnts,hierarchy = cv2.findContours(closed.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) c = sorted(cnts, key = cv2.contourArea, reverse = True)[0] #找大的边框 rect = cv2.minAreaRect(c) box = cv2.boxPoints(rect) box = np.int0(box) # 画一个找到的方框 cv2.drawContours(img, [box], -1, (0, 255, 0), 3) cv2.imshow('img', img) # cv2.waitKey(0) cv2.destroyAllWindows()