问题
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