在Python中从左到右排序轮廓(OpenCV)

编程入门 行业动态 更新时间:2024-10-28 10:28:23
本文介绍了在Python中从左到右排序轮廓(OpenCV)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在使用Python和OpenCV来检测图像中的轮廓。但是,当我运行以下代码使用轮廓索引仅绘制特定轮廓时,由于分配的索引是随机的,我得到错误的输出。

I'm using Python and OpenCV to detect contours in my image. But when I run the following code to draw only a specific contour using the contour index, since the indices allocated are random, I get the wrong output.

所以我发现了质心(在我的例子中,所有质心都位于同一水平线上)。 有没有什么方法可以根据质心的x值从左到右(从0到n开始)对轮廓指数进行排序?

So I found out the Centroids (in my case all the centroids lie in the same horizontal line). Is there any way I can sort the contour indices from left to right (starting from 0 to n) based on the x value of the centroid?

可能你请显示相同的代码?任何帮助将不胜感激!

Could you please show the code for the same? Any help would be greatly appreciated!

contours, hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE) i = 9 ## Contour Index <---- cv2.drawContours(img,contours[i:i+1],-1,(0,0,255),2) centroids = [] for cnt in contours: mom = cv2.moments(cnt) (x,y) = int(mom['m10']/mom['m00']), int(mom['m01']/mom['m00']) cv2.circle(org,(x,y),4,(255,255,255),-1) centroids.append((x,y)

推荐答案

在python中实现列表的函数,如 这里。

Implements de sort function of list in python like here.

在实现的函数中,您计算​​中心并验证X位置是否为gretter或更小是另一个。如果gretter返回1,则小-1并等于0.

In the implemented function you calculate the center and verify if the X position is gretter or smaller them the other. If gretter return 1, smaller -1 and equals 0.

def greater(a, b): momA = cv2.moments(a) (xa,ya) = int(momA['m10']/momA['m00']), int(momA['m01']/momA['m00']) momB = cv2.moments(b) (xb,yb) = int(momB['m10']/momB['m00']), int(momB['m01']/momB['m00']) if xa>xb return 1 if xa == xb return 0 else return -1

如果你只计算一次de中心,你肯定可以做得更好。

For sure you can do better if you calculate de centers only once.

然后只做

contours.sort(greater)

更多推荐

在Python中从左到右排序轮廓(OpenCV)

本文发布于:2023-05-26 20:19:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/265196.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:轮廓   Python   左到右   OpenCV

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!