如何解决在一行行中从左到右对轮廓进行排序,然后向下并在第二行中从左到右排序
我正在尝试为 OCR 对轮廓进行排序以检测它们,问题是我试图从左到右和从上到下对轮廓进行排序,但这无济于事。我在两行上有文本,我希望第一行中的轮廓从左到右排序,然后对第二行进行相同排序。尝试了几种方法来解决这个问题,但我一直在失败。下面是一个代码片段,显示了我尝试实现的内容
def get_precedence(contour,cols):
tolerance_factor = 10
origin = cv2.boundingRect(contour)
return ((origin[1] // tolerance_factor) * tolerance_factor) * cols + origin[0]
image = cv2.imread(file)
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray,(5,5),0)
edged = cv2.Canny(blurred,30,150)
cnts,h= cv2.findContours(edged.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
cnts.sort(key=lambda x:get_precedence(x,edged.shape[1]))
解决方法
第一步:我用 cv2.boundingRect() 从轮廓中减少了数据。
第二步:我过滤了每一个触及图像边缘的片段。
第 3 步:我从顶部('y' 值)对剩余数据进行排序。
第 4 步:我根据每个后面的 'y' 的差异将数据分割成行,其中它大于字符高度的中位数。
第五步:我从左边开始对每一行进行排序。
代码:
import cv2
import numpy as np
def edge_filter(sgmts):
x,y,w,h = sgmts[:,0],sgmts[:,1],2],3]
res_y,res_x = image_shape
return sgmts[((res_x - w - x) * (res_y - h - y) * x * y) != 0]
image = cv2.imread('sample.png')
image_shape = image.shape[:2]
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray,(5,5),0)
edged = cv2.Canny(blurred,30,150)
cnts = cv2.findContours(edged,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)[0]
sgmts = np.array([cv2.boundingRect(i) for i in cnts])
filtered = edge_filter(sgmts)
sorted_top = filtered[np.argsort(filtered[:,1])]
median_height = np.median(sorted_top[:,-1])
diff_y = np.diff(sorted_top[:,1])
new_line = np.where(diff_y > median_height)[0] + 1
lines = np.array_split(sorted_top,new_line)
sorted_left = [line[np.argsort(line[:,0])] for line in lines]
for line,num in zip(sorted_left,range(len(sorted_left))):
print(f'line {num + 1}:\n {line}\n')
这是我的输出:
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。