想要找到等高线->值错误:没有足够的值来解包(需要3,得到2),这将出现

2024-04-28 20:53:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我的简单python代码是

import cv2

img=cv2.imread('Materials/shapes.png')

blur=cv2.GaussianBlur(img,(3,3),0)
gray=cv2.cvtColor(blur,cv2.COLOR_BGR2GRAY)
returns,thresh=cv2.threshold(gray,80,255,cv2.THRESH_BINARY)

ret,contours,hierachy=cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

for cnt in contours:

    area=cv2.contourArea(cnt) #contour area

    if (area>1220):
        cv2.drawContours(img,[cnt],-1,(0,255,0),2)
        cv2.imshow('RGB',img)
        cv2.waitKey(1000)
        print(len(cnt))

import numpy as np

contours=np.array(contours)

print(contours)

这很管用。但最近连我都没做任何改变。这是给我的

ret,contours,hierachy=cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

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

帮帮我伙计们。

谢谢。


Tags: importtreechainimgareacv2retcnt
2条回答

函数cv2.findContours()已更改为只返回轮廓和层次结构,而不返回

您应该将其更改为:

contours,hierachy=cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

thispython代码示例中解释得很好,证明代码版本的最佳方法是使用以下语法:

# check OpenCV version
major = cv2.__version__.split('.')[0]
if major == '3':
    ret, contours, hierarchy = cv2.findContours(im.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
else:
    contours, hierarchy = cv2.findContours(im.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

这为您提供了一个可以在上一个或更早版本的OpenCV上运行的代码。

相关问题 更多 >