我正在尝试使用以下代码实现轮廓。
im = cv2.imread('C:UsersPrashantDesktopT.jpg')
imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(imgray,127,255,0)
image, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
img = cv2.drawContour(im, contours, -1, (0,255,0), 3)
cv2.imshow('Image1',img)
但是我不断收到以下错误。
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:Python27libsite-packagesspyderlibwidgetsexternalshellsitecustomize.py", line 540, in runfile
execfile(filename, namespace)
File "C:/Users/Prashant/.spyder2/.temp.py", line 17, in <module>
image, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
ValueError: need more than 2 values to unpack
函数 findContours 需要更多参数吗?我可以做些什么来纠正它。
在 OpenCV 2 中,findContours
只返回两个值,contours
和 hierarchy
。 当 python 尝试将这两个值分配给此语句左侧给出的三个名称时,会发生此错误:
image, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
它现在返回三个值:
findContours(image, mode, method[, contours[, hierarchy[, offset]]])
返回图像、轮廓、层次结构
findContours 在 opencv3 中只返回三个值 image、contour 和 hierarchy
image, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
截至2019年,我们有三个版本的OpenCV(OpenCV2,OpenCV3和OpenCV4)。
OpenCV4 和 OpenCV2 具有类似的行为(从 cv2.findContours
返回两个值)。而 OpenCV3 返回三个值。
if cv2.getVersionMajor() in [2, 4]:
# OpenCV 2, OpenCV 4 case
contour, hier = cv2.findContours(
thresh.copy(), cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE)
else:
# OpenCV 3 case
image, contour, hier = cv2.findContours(
thresh.copy(), cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE)
- findContours 只返回两个值。 所以只使用,
所以使用
contours, hierarchy=cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
这应该有帮助:
image, contours, hierarchy = cv2.findContours(thresh.copy(),
cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
根据OpenCV版本,cv2.findContours()
有不同的返回签名。在 OpenCV 3.4.X 中,cv2.findContours()
返回 3 个项目。在 OpenCV 2.X 和 4.1.X 中,cv2.findContours()
返回 2 个项目
无论版本如何,您都可以轻松获得轮廓,如下所示:
cnts = cv2.findContours(image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
v2.7.14:84471935ed, Sep 16 2017, 20:25:58) [MSC v.1500 64 位 (AMD64)]
数字版本:1.16.1
参数解析版本:1.1
CV2版本:4.0.0
Traceback (most recent call last):
File "omr.py", line 254, in <module>
main()
File "omr.py", line 237, in main
answers, im = get_answers(args.input)
File "omr.py", line 188, in get_answers
contours = get_contours(im)
File "omr.py", line 26, in get_contours
im2, contours, hierarchy =cv2.findContours(image_gray,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
ValueError: need more than 2 values to unpack
这可以通过从第 26 行中删除"im2"来解决。 在 OpenCv 3.0 或更高版本中,函数 'findContours' 仅返回 2 个值。 所以语句应该是
contours, hierarchy =cv2.findContours(image_gray,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
并升级您的 OpenCv 版本
根据当前的Opencv版本cv2.findContours返回2个值,即Contours和heirachy。等高线可以简单地解释为连接所有连续点(沿边界)的曲线,具有相同的颜色或强度。轮廓是形状分析以及物体检测和识别的有用工具。