如何让OpenCV连通组件分析结果按从左到右顺序排列(字符识别)
解决OpenCV连通组件按原图从左到右排序的问题
cv2.connectedComponentsWithStats()返回的组件顺序是随机的,和图像中字符的空间位置无关,要实现从左到右的排序,核心是利用每个组件的左边界x坐标(即stats里的CV_STAT_LEFT字段)来排序,具体步骤如下:
- 过滤背景组件:label=0对应图像背景,需要跳过;
- 收集组件的位置与对应数据:提取每个有效组件的x坐标、label、stats和centroids信息;
- 按x坐标排序:以x坐标从小到大排序,对应原图从左到右的顺序;
- 提取排序后的数据:重新整理得到有序的组件标签、统计信息和质心数据。
示例代码
import cv2 import numpy as np # 假设你已经得到连通组件数据 num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(img, 8, cv2.CV_32S) # 收集有效组件(跳过背景label=0) component_list = [] for label_idx in range(1, num_labels): # 获取组件左边界x坐标 component_x = stats[label_idx, cv2.CC_STAT_LEFT] # 存储x坐标、label、对应stats和centroids component_list.append( (component_x, label_idx, stats[label_idx], centroids[label_idx]) ) # 按x坐标从小到大排序(从左到右) sorted_components = sorted(component_list, key=lambda elem: elem[0]) # 提取排序后的各项数据 sorted_labels = [elem[1] for elem in sorted_components] sorted_stats = np.array([elem[2] for elem in sorted_components]) sorted_centroids = np.array([elem[3] for elem in sorted_components])
扩展:处理多行文本场景
如果识别的是多行字符,需要先按行(y坐标,即CV_STAT_TOP字段)排序,再按每行内的x坐标排序,只需修改排序的key即可:
# 先按y坐标(行)排序,再按x坐标(行内左右)排序 sorted_components = sorted( component_list, key=lambda elem: (elem[2][cv2.CC_STAT_TOP], elem[0]) )
说明
stats数组的各字段对应含义:
cv2.CC_STAT_LEFT:组件左边界x坐标cv2.CC_STAT_TOP:组件上边界y坐标cv2.CC_STAT_WIDTH:组件宽度cv2.CC_STAT_HEIGHT:组件高度cv2.CC_STAT_AREA:组件面积
内容的提问来源于stack exchange,提问作者Andrew Kaleem
相关产品推荐
相关产品推荐

