opencv机器视觉识别二维码,基于opencv二维码扫描原理
终极管理员 知识笔记 136阅读
10×10 的子块为种子用子块灰度值的方差为衡量标准往外聚类聚类时的阈值设定为

其中 M 是聚类开始时作为种子的子块的个数k 为调整系数在本文算法中 k设置为 0.5Var 和 Mean
分别表示子块灰度值的均值和方差。由公式(3-1)可知每幅图像的聚类阈值是自适应的计算得来的。聚类开始时首先从种子子块出发计算它们周围的子块的灰度值方差如果大于聚类阈值就把它标识为属于二维条形码重复这个过程直到周围再没有子块符合聚类条件。图
3-5
是聚类算法的部分结果第一行的图像是特征分类后的结果准确的定位到了一部分二维条形码但是没有完全的覆盖整个二维条形码不利于我们输出最后的定位包围盒。第二行为聚类后的结果可以看到小块几乎完全覆盖了整个二维条形码此时再把这些小块合并为一个平行四边形就很方便了。
聚类后定位出来的小块基本上覆盖了整个二维条形码最后我们只需要把定位出的小包围盒合并为大包围盒并输出最后的定位结果。整个后处理流程见图

这里演示条形码的检测效果
关键部分代码实现:
# import the necessary packages
import numpy as np
import argparse
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())# load the image and convert it to grayscaleimage cv2.imread(./images/2.png)gray cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)# compute the Scharr gradient magnitude representation of the images# in both the x and y directiongradX 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-gradientgradient cv2.subtract(gradX, gradY)gradient cv2.convertScaleAbs(gradient)# blur and threshold the imageblurred cv2.blur(gradient, (9, 9))(_, thresh) cv2.threshold(blurred, 225, 255, cv2.THRESH_BINARY)# construct a closing kernel and apply it to the thresholded imagekernel cv2.getStructuringElement(cv2.MORPH_RECT, (21, 7))closed cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)# perform a series of erosions and dilationsclosed cv2.erode(closed, None, iterations 4)closed cv2.dilate(closed, None, iterations 4)# 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)c sorted(cnts, key cv2.contourArea, reverse True)[0]# compute the rotated bounding box of the largest contourrect cv2.minAreaRect(c)box np.int0(cv2.boxPoints(rect))
5 最后更多资料, 项目分享
标签: