opencv 3 beta / python中的findContours和drawContours错误

时间:2015-01-23 15:29:34

标签: python opencv

我尝试从here运行示例。

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)

如果我删除&#34;层次结构&#34; drawContours中出现错误:

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

如果我在drawContours中使用轮廓[0]

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

这可能有什么问题?

4 个答案:

答案 0 :(得分:12)

opencv 3在这里略有changed syntax,返回值不同:

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

答案 1 :(得分:12)

根据berak的回答,只需将[-2:]添加到findContours()次调用,即可使其适用于OpenCV 2.4和3.0:

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

答案 2 :(得分:1)

之前我遇到过相同的问题,我使用此代码来修复它。 我还是使用3.1。

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

答案 3 :(得分:1)

取决于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()返回2个项目

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:
    ...
相关问题