首页 > 解决方案 > 如何修复 Python 中的 Opencv ValueError?

问题描述

我该如何解决?

import numpy as np
import cv2 as cv
im = cv.imread('good.jpg')
imgray = cv.cvtColor(im, cv.COLOR_BGR2GRAY)
ret, thresh = cv.threshold(imgray, 127, 255, 0)
im2, contours, hierarchy = cv.findContours(thresh, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)

错误

ValueError:没有足够的值来解包(预期 3,得到 2)

标签: pythonopencvimage-processing

解决方案


问题出在你的最后一行。为了更好地理解它,下面是从文档中引用的一段话:

看,函数中有三个参数cv2.findContours(),第一个是源图像,第二个是轮廓检索模式,第三个是轮廓逼近方法。它输出轮廓和层次结构。Contours 是图像中所有轮廓的 Python 列表。每个单独的轮廓都是对象边界点的 (x,y) 坐标的 Numpy 数组。

所以很明显cv2.findContours()只返回两个参数(不是 3 个)。要修复它,只需将最后一行更改为:

contours, hierarchy = cv.findContours(thresh, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)

推荐阅读