[英]Python OpenCV contour sorting
I am working with words scanned from old text. 我正在处理从旧文本扫描的单词。 I want to be able to read the letters from left to right.
我希望能够从左到右阅读字母。 Unfortunately, when I try to sort the contours based based on the
cv2.boundingRect
x
value it doesn't sort that way I'd like. 不幸的是,当我尝试基于
cv2.boundingRect
x
值对轮廓进行排序时,它并没有按照我想要的方式进行排序。 I've included an image numbering the letters on the order in which they are sorted. 我提供了一张图片,其中按字母排序的顺序编号。 The outcome I wanted was for dead to be 0,1,2,3 and battery 4, 5, 6, 7 essentially reading dead then battery.
我想要的结果是死掉是0、1、2、3,而电池4、5、6、7基本上是先死掉,然后读取电池。
Here is my code: 这是我的代码:
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])
You need to compute the distance from the origin (0,0) to the starting point. 您需要计算从原点(0,0)到起点的距离。 I have tried in a dummy image which I created and it works.
我已经尝试过创建一个虚拟图像,并且该图像可以正常工作。
You need to update your sorting algorithm with the below code. 您需要使用以下代码更新排序算法。 which computes the Euclidean distance from the origin.
计算距原点的欧几里得距离。
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));
The below image is the output. 下图是输出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.