OpenCV项目中cv2.findContours解包报错:too many values to unpack
解决
cv2.findContours的ValueError:too many values to unpack (expected 2) 这个报错的核心原因是OpenCV版本之间的API差异,不同版本的cv2.findContours返回值数量不一样:
- OpenCV 2.x 和 OpenCV 4.x:返回
(contours, hierarchy)两个值 - OpenCV 3.x:返回
(image, contours, hierarchy)三个值
你的代码是按2个值来解包的,但当前运行环境用的是OpenCV 3.x,所以会触发"too many values to unpack"错误。
修复步骤
调整
findContours的解包语句
把原来的:(cnts, _) = cv2.findContours(closed.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)修改为适配OpenCV 3.x的写法(忽略第一个返回的图像值,我们用不到它):
_, cnts, _ = cv2.findContours(closed.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)修复Python3的print语法问题
你的代码里的print "I found..."是Python2的写法,在Python3环境中会报错,需要改成函数形式:print("I found {0} books in that image".format(total))
完整修复后的代码
# import the necessary packages import numpy as np import cv2 # load the image, convert it to grayscale, and blur it image = cv2.imread("example.jpg") gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) gray = cv2.GaussianBlur(gray, (3, 3), 0) cv2.imshow("Gray", gray) cv2.waitKey(0) # detect edges in the image edged = cv2.Canny(gray, 10, 250) cv2.imshow("Edged", edged) cv2.waitKey(0) # construct and apply a closing kernel to 'close' gaps between 'white' # pixels kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (7, 7)) closed = cv2.morphologyEx(edged, cv2.MORPH_CLOSE, kernel) cv2.imshow("Closed", closed) cv2.waitKey(0) # 适配OpenCV 3.x的findContours返回值 _, cnts, _ = cv2.findContours(closed.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) total = 0 # loop over the contours for c in cnts: # approximate the contour peri = cv2.arcLength(c, True) approx = cv2.approxPolyDP(c, 0.02 * peri, True) # if the approximated contour has four points, then assume that the # contour is a book -- a book is a rectangle and thus has four vertices if len(approx) == 4: cv2.drawContours(image, [approx], -1, (0, 255, 0), 4) total += 1 # display the output(适配Python3的print语法) print("I found {0} books in that image".format(total)) cv2.imshow("Output", image) cv2.waitKey(0)
额外提示
可以通过print(cv2.__version__)查看当前OpenCV的版本号,确认自己属于哪一类情况;如果后续升级到OpenCV4.x,改回原来的2值解包写法也可以正常运行。
内容的提问来源于stack exchange,提问作者Romka_10101
相关产品推荐
相关产品推荐

