How to detect and draw contours using OpenCV in Python?

此生再无相见时 提交于 2019-12-13 12:32:33

问题


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

And here is the error I received:

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

What is wrong? I am using Python 2.7 and OpenCV 3.1.0


回答1:


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.

Previous versions of OpenCV, however, return only contours, hierarchy. They do not return the image.




回答2:


Change the following line. You are using OpenCV 3.1.0 but you have coded using OpenCV 2.7.x.

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

Also this link will help you.



来源:https://stackoverflow.com/questions/41486770/how-to-detect-and-draw-contours-using-opencv-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!