我正在使用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)
发布评论