aku*_*tri 2 python opencv python-2.7
我是一个蟒蛇初学者.我试图运行此代码:
#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)
Run Code Online (Sandbox Code Playgroud)
当我召唤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
Run Code Online (Sandbox Code Playgroud)
这段代码有什么问题?
在编写用于2.x分支的代码时,您似乎正在使用OpenCV 3.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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
这意味着在脚本中findContours使用OpenCV 3.x时调用的正确方法就是这样的
(_, cnts, _) = cv2.findContours(closed.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
Run Code Online (Sandbox Code Playgroud)
更新(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.
Run Code Online (Sandbox Code Playgroud)