当len(contours)=1时,轮廓和contours[0]有什么区别?

4

我希望能够找到一张图片的轮廓,然后绘制它的凸包。我的做法是:加载图片,对其进行阈值处理,找到其轮廓,然后绘制凸包。

gray = cv2.imread(test_paths[i], 0)
ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY_INV)
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnt = contours[0]

检测到的轮廓数量为1。 问题出在我尝试绘制轮廓时,如果我这样做。
cv2.drawContours(cnt_dst, cnt, -1, (255, 0, 0), 3)
plt.imshow(cnt_dst)

在此输入图片描述

如果我将代码更改为以下内容:

cv2.drawContours(cnt_dst, contours, 0, (255, 0, 0), 3)
plt.imshow(cnt_dst)

轮廓不同:

enter image description here

请注意,使用此方法可以得到相同(好的)结果:
cv2.drawContours(cnt_dst, contours, -1, (255, 0, 0), 3)

有什么想法,这是为什么发生的呢?
1个回答

5

cv2.drawContours(cnt_dst, contours, 0, (255, 0, 0), 3)或者cv2.drawContours(cnt_dst, contours, -1, (255, 0, 0), 3)在这种情况下是相同的。

-1告诉opencv绘制轮廓数组中的所有轮廓,而0则告诉它绘制轮廓数组中的第一个轮廓。

由于只有一个轮廓,因此结果是相同的。

另一个调用cv2.drawContours(cnt_dst, cnt, -1, (255, 0, 0), 3)可能是错误的/应该在opencv一侧进行更好的检查。

这篇博客中指出:

现在您只想绘制“cnt”。可以按如下方式完成:
cv2.drawContours(im,[cnt],0,(255,0,0),-1) 注意“cnt”周围的方括号。第三个参数设置为0,表示仅绘制特定轮廓。


cv2.drawContours(cnt_dst, [cnt], -1, (255, 0, 0), 3) 已经完成。谢谢! - Manuel Lagunas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接