在OpenCV 3 beta/Python中,findContours和drawContours出现错误。

10

我尝试运行这里的一个示例。

import numpy as np
import cv2
img = cv2.imread('final.jpg')
imgray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(imgray,127,255,0)
contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(img, contours, -1, (0,255,0), 3)

错误是:
 Traceback (most recent call last):
   File "E:\PC\opencv3Try\findCExample.py", line 7, in <module>
contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
 ValueError: too many values to unpack (expected 2)

如果我删除 "层次结构(hierarchy)",那么在 drawContours 中会出现错误:

TypeError: contours is not a numpy array, neither a scalar

如果我在drawContours函数中使用contours[0]

cv2.error: E:\opencv\opencv\sources\modules\imgproc\src\drawing.cpp:2171: error: (-215) npoints > 0 in function cv::drawContours

这里可能存在哪些问题?

4个回答

12

OpenCV 3的语法略有变化,返回值也有所不同:

cv2.findContours(image, mode, method[, contours[, hierarchy[, offset]]]) → image, contours, hierarchy

2
目前很难找到Python的OpenCV 3.0文档(上面的链接无法访问),所以我只是尝试使用findContours()来确定它是否仍然会修改图像。它确实会修改图像,而 according to is比较得出传递和返回的图像是相同的。 - Ulrich Stern
2
这里是OpenCV 3.0.0-dev文档的有效链接,其中显示了findContours Python版本的三个返回值。 - Greg Sadetsky

12

继续上面的回答,只需将[-2:]添加到findContours()调用中,就可以使其适用于OpenCV 2.4和3.0:

contours, hierarchy = cv2.findContours(...)[-2:]

4

根据OpenCV版本不同,cv2.findContours() 的返回值有所不同。

在OpenCV 3.4.X中,cv2.findContours() 返回3个值。

image, contours, hierarchy = cv.findContours(image, mode, method[, contours[, hierarchy[, offset]]])

在OpenCV 2.X和4.1.X版本中,cv2.findContours()函数返回两个项目。
contours, hierarchy = cv.findContours(image, mode, method[, contours[, hierarchy[, offset]]])

您可以像这样轻松获取轮廓,而不受版本的限制:

cnts = cv2.findContours(image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    ...

1

我之前遇到过同样的问题,我使用了这段代码来解决它。不管怎样,我正在使用3.1版本。

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

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