调用 cv2.findContours 时需要解压的值太多
- 2025-04-15 09:19:00
- admin 原创
- 28
问题描述:
我是一名 Python 初学者。我尝试运行以下代码:
#applying closing function
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (7, 7))
closed = cv2.morphologyEx(th3, cv2.MORPH_CLOSE, kernel)
#finding_contours
(cnts, _) = cv2.findContours(closed.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for c in cnts:
peri = cv2.arcLength(c, True)
approx = cv2.approxPolyDP(c, 0.02 * peri, True)
cv2.drawContours(frame, [approx], -1, (0, 255, 0), 2)
当我召唤 mask.py 时,我得到了这个 ValueError :
Traceback (most recent call last):
File "mask.py", line 22, in <module>
(cnts, _) = cv2.findContours(closed.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
ValueError: too many values to unpack
这段代码有什么问题?
解决方案 1:
看来您正在使用 OpenCV 3.x 版本,但编写的代码是为 2.x 分支编写的。这两个分支之间有一些 API 更改。由于您使用的是 Python,因此可以使用便捷的帮助——请务必结合文档一起使用它。
OpenCV 2.x:
>>> import cv2
>>> help(cv2.findContours)
Help on built-in function findContours in module cv2:
findContours(...)
findContours(image, mode, method[, contours[, hierarchy[, offset]]]) -> contours, hierarchy
OpenCV 3.x:
>>> import cv2
>>> help(cv2.findContours)
Help on built-in function findContours:
findContours(...)
findContours(image, mode, method[, contours[, hierarchy[, offset]]]) -> image, contours, hierarchy
findContours
这意味着在你的脚本中使用 OpenCV 3.x 时正确的调用方式应该是这样的
(_, cnts, _) = cv2.findContours(closed.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
更新(2018 年 12 月)
在 OpenCV 4.x 中,findContours
仅返回 2 个值。
>>> help(cv2.findContours)
Help on built-in function findContours:
findContours(...)
findContours(image, mode, method[, contours[, hierarchy[, offset]]]) -> contours, hierarchy
. @brief Finds contours in a binary image.
解决方案 2:
cv2.findContours()
无论版本如何,您都可以使用以下代码片段:
import cv2 as cv
version = cv.__version__
version = version[0]
if version == '4' or version == '2':
contours, hierarchy = cv.findContours(thresh, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
elif version == '3':
im2, contours, hierarchy = cv.findContours(thresh, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
OpenCV2.x
并4.x
返回 2 个变量,而3.x
返回 3 个变量
相关推荐
热门文章
项目管理软件有哪些?
热门标签
曾咪二维码
扫码咨询,免费领取项目管理大礼包!
云禅道AD