如何在Python中使用OpenCV检测和绘制轮廓? [英] How to detect and draw contours using OpenCV in Python?
问题描述
我编写了以下代码来检测和绘制轮廓:
I wrote the following code to detect and draw contours:
img = cv2.imread('test2.tif');
if not img is None:
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);
#draw a three pixel wide outline
cv2.drawContours(img,contours,-1,(0,255,0),3);
这是我收到的错误:
回溯(最近通话最近): 文件"C:/Users/R.K.singh/Desktop/图像处理/intro-to-contours.py",第10行,在 等高线,层次结构= cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE); ValueError:太多值无法解压缩
Traceback (most recent call last): File "C:/Users/R.K.singh/Desktop/Image processing/intro-to-contours.py", line 10, in contours,hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE); ValueError: too many values to unpack
怎么了?我正在使用Python 2.7和OpenCV 3.1.0
What is wrong? I am using Python 2.7 and OpenCV 3.1.0
推荐答案
为了强调Selchuk的观点,涉及OpenCV 3.x的语法有所改变.当涉及到cv2.findContours
时,它具有不同的返回值.它返回以下image, contours, hierarchy
.
In order to emphasize Selchuk's point, the syntax involving OpenCV 3.x has changed a little bit. It has a different return value when it comes to cv2.findContours
. It returns the following image, contours, hierarchy
.
但是,早期版本的OpenCV仅返回contours, hierarchy
.他们不返回图像.
Previous versions of OpenCV, however, return only contours, hierarchy
. They do not return the image.
这篇关于如何在Python中使用OpenCV检测和绘制轮廓?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!