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