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

Dmi*_*lov 9 python opencv

我试着从这里运行一个例子.

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)
Run Code Online (Sandbox Code Playgroud)

错误是

 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)
Run Code Online (Sandbox Code Playgroud)

如果我删除"层次结构",则会在drawContours中出现错误:

TypeError: contours is not a numpy array, neither a scalar
Run Code Online (Sandbox Code Playgroud)

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

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

这可能有什么问题?

ber*_*rak 12

opencv 3 在这里有一个稍微改变的语法,返回值不同:

cv2.findContours(image, mode, method[, contours[, hierarchy[, offset]]]) ? image, contours, hierarchy
Run Code Online (Sandbox Code Playgroud)

  • 目前很难找到Python的OpenCV 3.0文档(上面的链接目前都失败了),所以我只是尝试3.0中的`findContours()`是否仍然修改了图像.确实如此,根据`is`传递的图像和返回的图像是相同的. (2认同)
  • [这里](http://docs.opencv.org/3.0-last-rst/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html?highlight=findcontours#findcontours)一个指向OpenCV 3.0.0-dev文档的工作链接显示Python版本的findContours的三个返回值. (2认同)

Ulr*_*ern 12

继berak的回答,只是加入[-2:]findContours()呼叫使他们两个的OpenCV 2.4和3.0的工作:

contours, hierarchy = cv2.findContours(...)[-2:]
Run Code Online (Sandbox Code Playgroud)