如何在Python中使用OpenCV进行轮廓检测和绘制?

2024-04-29 06:20:01 发布

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

我编写了以下代码来检测和绘制轮廓:

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);

下面是我收到的错误:

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


Tags: to代码treechainimghierarchy绘制simple
2条回答

为了强调Selchuk的观点,涉及OpenCV 3.x的语法有了一些改变。当涉及到cv2.findContours时,它有不同的返回值。它返回以下image, contours, hierarchy

但是,以前版本的OpenCV只返回contours, hierarchy。它们不会返回图像。

更改以下行。您使用的是OpenCV 3.1.0,但您使用的是OpenCV 2.7.x

(cnts, _) = cv2.findContours(thresh.copy(), cv2.RETR_TREE,
      cv2.CHAIN_APPROX_SIMPLE)

这个link也会帮助你。

相关问题 更多 >