Python OpenCV轮廓排序

时间:2019-08-01 10:09:31

标签: python opencv

我正在处理从旧文本扫描的单词。我希望能够从左到右阅读字母。不幸的是,当我尝试基于cv2.boundingRect x值对轮廓进行排序时,它并没有按照我想要的方式进行排序。我提供了一张图片,其中按字母排序的顺序编号。我想要的结果是死掉是0、1、2、3,电池4、5、6、7基本上是先死掉,然后是电池。

enter image description here

这是我的代码:

def sort_contours(image, area_threshold):
    contours, hierarchy = cv2.findContours(image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    all_contours = []
    for contour in contours:
        area = cv2.contourArea(contour)
        x, y, w, h = cv2.boundingRect(contour)

        if area > area_threshold:
            all_contours.append((x, y, w, h))
    return sorted(all_contours, key=lambda tup: tup[0])

1 个答案:

答案 0 :(得分:-1)

您需要计算从原点(0,0)到起点的距离。我已经尝试过创建一个虚拟图像,并且该图像可以正常工作。

您需要使用以下代码更新排序算法。计算距原点的欧几里得距离。

im2, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)

points = []
for cnt in contours:
    x,y,w,h=cv2.boundingRect(cnt)

    points.append((x,y,w,h))

#print(points)
points = sorted(points,key=lambda data:math.sqrt(data[0]**2+data[1]**2));

下图是输出。

output image

相关问题