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

2024-04-29 02:54:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我最近开始在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

如能帮助解决这个问题,我们将不胜感激。


Tags: 图像imageimportimghierarchycv2copyimshow
2条回答

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

您链接的教程是针对OpenCV version 3cv2.findContours在该版本中返回3个对象。

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

相关问题 更多 >