python - 在 Python (OpenCV) 中从左到右对轮廓进行排序

标签 python sorting opencv image-processing contour

我正在使用 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)

最佳答案

在python中实现list的de sort功能 here .

在实现的函数中,您计算​​中心并验证 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)

关于python - 在 Python (OpenCV) 中从左到右对轮廓进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27152698/

相关文章:

python - 我应该如何在多模块 Python 应用程序中建立和管理数据库连接?

python - 用新格式替换现有日期

具有root权限的Python进程竞赛

r - 将 r 中较小的序列映射(对齐)到较大的序列

algorithm - 我应该使用哪种算法对学生进行排序?

java - Java 和 opencv 3.0 中的 OpenCV 错误 : Assertion failed (! empty()) 是什么意思?

python - 向 models.py 添加了额外的模型,但我得到 `OperationalError: no such table`

c++ - 根据类内的字符串对用户定义类的 vector 进行排序

c++ - OpenCV : Assertion failed using one of the two constructors of SIFT

android - 在Android应用程序中检测手并分割图像