使用 Python 中的 cv2.findContours() 函数出现错误

14

我最近开始在Python上学习OpenCV。

我正在参考这个教程,希望能够获得有关获取图像轮廓的一些帮助。

我的代码是 -

import cv2
import numpy as np

img = cv2.imread('shapes.jpg', 0)
img = cv2.medianBlur(img, 5)
thresh =     cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\
cv2.THRESH_BINARY,11,2)

cv2.imshow('Thresh', thresh)
cv2.waitKey(0)
cv2.destroyAllWindows()

image, contours, hierarchy =   cv2.findContours(thresh.copy(),cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)

cv2.drawContours(image, countours, -1, (0,255,0), 3)
cv2.imshow('Contours', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

第一张阈值处理后的图像已经出现了,但随后我收到了一个错误消息,消息内容如下:

The first thresholded image is appearing, but after that I get an error message as

Traceback (most recent call last):
  File "contours.py", line 21, in <module>
    image, contours, hierarchy =     cv2.findContours(thresh.copy(),cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
ValueError: need more than 2 values to unpack
任何帮助解决此问题都将不胜感激。
3个回答

20

看这个例子

cv2.findContours(...)

这个函数只返回两个对象,你尝试将其解包成三个。

将该行代码更改为:

contours, hierarchy =   cv2.findContours(thresh.copy(),cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)

它应该可以正常工作。


9
根据Opencv版本,findContours函数可能会有2或3个返回值... - Mehdi
1
嗨@will,你介意根据最新版本更新一下你的答案吗?这样你可以帮我们节省些时间。 - explorer

11

您提供的教程是针对 OpenCV 3 版本的。在该版本中,cv2.findContours 返回 3 个对象。

因此,要么更新 OpenCV,要么使用 @will 的解决方案。


1
没意识到这个问题,你发现得真好。 - will
我意识到这个相当晚了。 - Souvik Saha
1
这三个对象是什么?提供文档链接会很有帮助! - duhaime

1

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