字符提取场景下判断轮廓是否大部分为白色填充的实现方法咨询
验证码字符提取相关说明
我有如下图像:
我可以基于密实度(solidity)、高度、*宽高比(aspect ratio)*提取所有字母,但提取结果同时包含了最左侧的方块。由于该图像由多个字母(及一个方块)水平堆叠组成,我需要判断一个轮廓是否大部分为白色填充。
我使用以下代码从输入图像中提取得到候选字符图像:
from skimage import measure import numpy as np import cv2 plate_img = cv2.imread('bla1.png') V = cv2.split(cv2.cvtColor(plate_img, cv2.COLOR_BGR2HSV))[2] thresh = cv2.adaptiveThreshold(V, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 15, 6) labels = measure.label(thresh, connectivity = 2, background = 0) charCandidates = np.zeros(thresh.shape, dtype=np.uint8) characters = [] for label in np.unique(labels): # 忽略背景标签 if label == 0: continue # 构建标签掩码,仅显示当前标签对应的连通组件,再在掩码中查找轮廓 labelMask = np.zeros(thresh.shape, dtype=np.uint8) labelMask[labels == label] = 255 cnts, hierarchy = cv2.findContours(labelMask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) if len(cnts) > 0: # 取掩码中面积最大的轮廓,获取其外接矩形 c = max(cnts, key=cv2.contourArea) (boxX, boxY, boxW, boxH) = cv2.boundingRect(c) # 计算组件的宽高比、密实度和高度占比 aspectRatio = boxW / float(boxH) solidity = cv2.contourArea(c) / float(boxW * boxH) heightRatio = boxH / float(plate_img.shape[0]) # 判断轮廓的宽高比、密实度和高度是否符合规则 keepAspectRatio = aspectRatio < 1.05 keepSolidity = 0.15 < solidity < 0.875 keepHeight = 0.5 < heightRatio < 0.95 # 检查组件是否通过所有校验 if keepAspectRatio and keepSolidity and keepHeight and boxW >= 6: # 计算轮廓的凸包,绘制到候选字符掩码上 hull = cv2.convexHull(c) cv2.drawContours(charCandidates, [hull], -1, 255, -1) contours = cv2.findContours(charCandidates, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)[0] for c in contours: (x, y, w, h) = cv2.boundingRect(c) temp = thresh[y:y + h, x:x + w] characters.append(temp) return characters
内容的提问来源于stack exchange,提问作者Michael Kročka
相关产品推荐
相关产品推荐

