OpenCV使用findContours()函数报错:not enough values to unpack (expected 3, got 2)

OpenCV使用findContours()函数报错:not enough values to unpack (expected 3, got 2)

笔者在学习网上的轮廓提取的示例代码时使用了cv2.findContours()函数,遇到了错误。原代码如下:

import cv2

img = cv2.imread('handwriting.jpg')
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 使用Otsu自动阈值,注意用的是cv2.THRESH_BINARY_INV
ret, thresh = cv2.threshold(
    img_gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)

# 寻找轮廓
image, contours, hierarchy = cv2.findContours(
    thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

cnt0 = contours[0]
cnt1 = contours[1]
cv2.drawContours(img, [cnt0], 0, (0, 0, 255), 2)
cv2.drawContours(img, [cnt1], 0, (0, 0, 255), 2)

cv2.imshow('contours', img)
cv2.waitKey(0)

运行时控制台报错,内容如下:

File "*:\******\***.py", line 10, in <module>
    image, contours, hierarchy = cv2.findContours(

ValueError: not enough values to unpack (expected 3, got 2)

可以看出来findContours()函数可以传出2个参数,但是我们的代码却有3个变量。尝试以后发现删去image变量,程序恢复正常运行——

import cv2

img = cv2.imread('handwriting.jpg')
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 使用Otsu自动阈值,注意用的是cv2.THRESH_BINARY_INV
ret, thresh = cv2.threshold(
    img_gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)

# 寻找轮廓
contours, hierarchy = cv2.findContours(
    thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

cnt0 = contours[0]
cnt1 = contours[1]
cv2.drawContours(img, [cnt0], 0, (0, 0, 255), 2)
cv2.drawContours(img, [cnt1], 0, (0, 0, 255), 2)

cv2.imshow('contours', img)
cv2.waitKey(0)

进一步查找官方文档发现,这里并不是原代码的作者写错了,而是笔者与原作者使用的OpenCV版本不同,而findContours()函数在不同版本中的函数原型是不一样的——

Python:
    image, contours, hierarchy = cv.findContours( image, mode, method[, contours[, hierarchy[, offset]]] )
#摘自OpenCV 3.4.11 官方文档(原作者的代码适用于3.x版本)

Python:
    contours, hierarchy = cv.findContours( image, mode, method[, contours[, hierarchy[, offset]]] )
#摘自OpenCV 4.0.1 官方文档(笔者使用的即是4.0.1版本)

所以在使用网上的示例代码时,我们一定要确认代码是否能够直接在自己的环境中运行,要针对环境的不同对代码作出必要的修改。

参考资料:http://codec.wang/#/opencv/basic/13-contours
OpenCV官方文档

  • 8
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值