python从大到小排序函数_在Python中从左到右排序轮廓(OpenCV)

1586010002-jmsa.png

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.

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)

解决方案

Implements de sort function of list in python like

here.

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

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

then just do

contours.sort(greater)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值