解决cv2.findContours返回值too many values to unpack (expected 2)的问题

来源:互联网 发布:淘宝差评师怎么找 编辑:程序博客网 时间:2024/05/22 16:39
参考:http://blog.csdn.net/louzhengzhai/article/details/72802978 
根据网上的 教程,Python OpenCV的轮廓提取函数会返回两个值,第一个为轮廓的点集,第二个是各层轮廓的索引。但是实际调用时我的程序报错了,错误内容如下

too many values to unpack (expected 2)

其实是接受返回值不符,如果你仅仅使用一个变量a去接受返回值,调用len(a),你会发现长度为3,也就是说这个函数实际上返回了三个值

第一个,也是最坑爹的一个,它返回了你所处理的图像

第二个,正是我们要找的,轮廓的点集

第三个,各层轮廓的索引

所以,应该调用如下:

[python] view plain copy
  1. #encoding:utf-8  
  2. import cv2  
  3. img=cv2.imread("s2.jpg")  
  4. gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)  
  5. gray=cv2.GaussianBlur(gray, (33), 0)  
  6. gray=cv2.Canny(gray,100,300)  
  7. ret, binary = cv2.threshold(gray,127,255,cv2.THRESH_BINARY)  
  8. binary,contours,hierarchy= cv2.findContours(binary,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)  
  9. cv2.drawContours(img,contours,-1,(0,0,255),3)  
  10. #print(contours[0])  
  11. cv2.imshow("0",binary)  
  12. cv2.imshow("win10",img)  
  13. cv2.waitKey(0)  
运行结果:


阅读全文
1 0