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

Man*_*nas 4 python opencv computer-vision opencv-contour

我想找到一个图像的轮廓然后画出它的凸包.我正在做的是加载图像,阈值,找到它的轮廓,然后绘制凸包.

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]
Run Code Online (Sandbox Code Playgroud)

检测到的轮廓数量等于1.如果我尝试绘制轮廓,问题就出现了

cv2.drawContours(cnt_dst, cnt, -1, (255, 0, 0), 3)
plt.imshow(cnt_dst)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

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

cv2.drawContours(cnt_dst, contours, 0, (255, 0, 0), 3)
plt.imshow(cnt_dst)
Run Code Online (Sandbox Code Playgroud)

轮廓不同:

在此输入图像描述

请注意,我得到了相同(好)的结果:

cv2.drawContours(cnt_dst, contours, -1, (255, 0, 0), 3)
Run Code Online (Sandbox Code Playgroud)

有关为什么会发生这种情况的任何想法?

Jea*_*bre 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,表示仅绘制特​​定轮廓.