【问题标题】:What is the difference between contours and contours[0] when len(contours)=1?当 len(contours)=1 时,contours 和 contours[0] 有什么区别?
【发布时间】:2017-05-25 03:03:34
【问题描述】:

我想找到图像的轮廓,然后绘制它的凸包。我正在做的是加载图像,对其设置阈值,找到它的轮廓,然后绘制凸包。

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)

轮廓不同:

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

cv2.drawContours(cnt_dst, contours, -1, (255, 0, 0), 3)

你知道为什么会这样吗?

【问题讨论】:

    标签: python opencv computer-vision opencv-contour


    【解决方案1】:

    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 端更好地检查。

    this blog 中表示:

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

    【讨论】:

    • cv2.drawContours(cnt_dst, [cnt], -1, (255, 0, 0), 3) 成功了。谢谢!
    猜你喜欢
    • 2020-01-17
    • 1970-01-01
    • 2010-10-15
    • 2022-01-27
    • 1970-01-01
    • 2014-01-18
    • 2021-11-08
    • 2012-05-01
    • 1970-01-01
    相关资源
    最近更新 更多