使用python时使用cv2.findContours()时出错

时间:2016-10-27 07:16:44

标签: python opencv image-processing

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

我在这里指的是this教程,以获得一些关于获取图像轮廓的帮助。

我的代码是 -

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()

出现第一个阈值图像,但之后我收到错误消息

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 个答案:

答案 0 :(得分:9)

查看this示例。

cv2.findContours(...)

只返回两个对象,你试图将它解压缩为三个。

将该行更改为:

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

它应该有用。

答案 1 :(得分:6)

您链接的教程适用于OpenCV version 3cv2.findContours确实返回该版本中的3个对象。

所以要么更新opencv,要么使用@will的解决方案。

答案 2 :(得分:1)

在版本4.1.2-dev中,它仅返回两个值。 您必须将其解压缩为两个值,然后使用cv2.drawContours()来查看它们。 这是文档的链接:https://docs.opencv.org/master/d4/d73/tutorial_py_contours_begin.html

相关问题