Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中从左到右排序等高线(OpenCV)_Python_Sorting_Opencv_Image Processing_Contour - Fatal编程技术网

在Python中从左到右排序等高线(OpenCV)

在Python中从左到右排序等高线(OpenCV),python,sorting,opencv,image-processing,contour,Python,Sorting,Opencv,Image Processing,Contour,我正在使用Python和OpenCV检测图像中的轮廓。但是,当我运行以下代码,使用轮廓索引仅绘制特定轮廓时,由于分配的索引是随机的,因此我得到了错误的输出 所以我找到了质心(在我的例子中,所有质心都位于同一条水平线上)。 是否有任何方法可以根据质心的x值从左到右(从0到n)对轮廓索引进行排序 你能给我看一下同样的代码吗?任何帮助都将不胜感激 contours, hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_S

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

所以我找到了质心(在我的例子中,所有质心都位于同一条水平线上)。 是否有任何方法可以根据质心的x值从左到右(从0到n)对轮廓索引进行排序

你能给我看一下同样的代码吗?任何帮助都将不胜感激

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)
contours,hierarchy=cv2.findContours(阈值、cv2.RETR\u列表、cv2.CHAIN\u近似值、简单值)

i=9##轮廓索引实现类似python的列表反排序功能

在已实现的函数中,计算中心并验证X位置是否大于或小于其他位置。如果gretter返回1,则小于-1并等于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
当然,如果只计算一次中心,您可以做得更好

那就做吧

contours.sort(greater)