仅检测图片最左侧字符的Python脚本问题排查与修复
排查与修复基于OpenCV的单词首字符检测问题
常见问题根源
- 轮廓未按水平位置排序:提取字符轮廓后未按x坐标从左到右排序,导致误选右侧字符
- 预处理阈值不合理:灰度化、二值化参数不当,导致首字符轮廓被合并或丢失
- 无效轮廓未过滤:未去除噪点、字符内部空洞等非字符轮廓
- 单词分割逻辑缺失:多单词场景下,未区分不同单词的字符集合
修复方案与代码实现
1. 按水平坐标对轮廓排序
核心是确保轮廓按从左到右的顺序排列,取第一个轮廓作为首字符:
import cv2 # 假设已完成图像读取与预处理,得到字符轮廓contours # 按轮廓外接矩形的x坐标排序 contours_sorted = sorted(contours, key=lambda c: cv2.boundingRect(c)[0]) # 取排序后的第一个轮廓作为首字符 first_char_contour = contours_sorted[0]
2. 优化图像预处理流程
通过自适应二值化和形态学操作,确保字符轮廓清晰分离:
# 读取图像 img = cv2.imread("phone_brands.jpg") # 灰度化 img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 自适应二值化(适配不同光照下的文本) _, img_binary = cv2.threshold(img_gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU) # 开运算去除小噪点 kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (2, 2)) img_clean = cv2.morphologyEx(img_binary, cv2.MORPH_OPEN, kernel) # 提取轮廓 contours, _ = cv2.findContours(img_clean, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
3. 筛选有效字符轮廓
通过面积、宽高比过滤噪点和无效轮廓:
valid_contours = [] for cnt in contours: x, y, w, h = cv2.boundingRect(cnt) area = cv2.contourArea(cnt) # 根据实际字符大小调整阈值,过滤过小或畸形的轮廓 if area > 200 and 0.2 < w/h < 3: valid_contours.append(cnt) # 再次排序有效轮廓 valid_contours_sorted = sorted(valid_contours, key=lambda c: cv2.boundingRect(c)[0])
4. 多单词场景的首字符提取
通过字符间距判断单词边界,分别提取每个单词的首字符:
words = [] if valid_contours_sorted: current_word = [valid_contours_sorted[0]] for i in range(1, len(valid_contours_sorted)): prev_x, _, prev_w, _ = cv2.boundingRect(current_word[-1]) curr_x, _, _, _ = cv2.boundingRect(valid_contours_sorted[i]) # 间距大于字符宽度1.5倍时,视为新单词 if curr_x - (prev_x + prev_w) > prev_w * 1.5: words.append(current_word) current_word = [valid_contours_sorted[i]] else: current_word.append(valid_contours_sorted[i]) words.append(current_word) # 提取每个单词的首字符轮廓 first_char_contours = [word[0] for word in words]
内容的提问来源于stack exchange,提问作者Pubg Mobile
相关产品推荐
相关产品推荐

