python - 为什么在一个代码中 cv2.findContours 函数有效,但在另一个代码中无效?
问题描述
我是计算机视觉的新手,还没有真正完成任何关于阈值或模糊或其他过滤器的教程。我正在使用以下两个代码来找出图像中的轮廓。一方面该方法有效,但另一方面却无效。我需要帮助来理解发生这种情况的原因,以便说服自己在后台发生的事情。
工作代码片段:
img=cv2.imread('path.jpg')
imgBlurred = cv2.GaussianBlur(img, (5, 5), 0)
gray = cv2.cvtColor(imgBlurred, cv2.COLOR_BGR2GRAY)
sobelx = cv2.Sobel(gray, cv2.CV_8U, 1, 0, ksize=3)
cv2.imshow("Sobel",sobelx)
cv2.waitKey(0)
ret2, threshold_img = cv2.threshold(sobelx, 120, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
im2, contours, hierarchy = cv2.findContours(threshold_img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
不工作的代码片段
# read image
src = cv2.imread(file_path, 1)
# show source image
cv2.imshow("Source", src)
# convert image to gray scale
gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
# blur the image
blur = cv2.blur(gray, (3, 3))
# binary thresholding of the image
ret, thresh = cv2.threshold(blur, 200, 255, cv2.THRESH_BINARY)
# find contours
im2, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
如果有人能找出这里发生的错误的原因,我将不胜感激。
我面临的错误是:
Traceback(最近一次调用最后一次):文件“convexhull.py”,第 27 行,在 im2、contours、hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) ValueError: no enough values to unpack (expected 3,得到 2)
让我知道是否还需要任何其他信息。
解决方案
这是由于 openCV 发生了变化。由于 4.0 版findContours
只返回 2 个值:轮廓和层次结构。之前,在 3.x 版本中,它返回 3 个值。您可以使用文档来比较不同的版本。
当您将代码更改为:
# find contours
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
为什么第一个片段选择不同的 openCV 版本无法从给定的信息中确定。
推荐阅读
- javascript - java - 如何仅使用for循环、if语句和while循环在Javasctipt中对数组的升序进行排序?
- python - 有没有一种有效的方法来比较两个 DataFrame 或 Series 之间的每一列的值?
- javascript - 动态点击按钮 - 访问动态内容
- python - 无法使用 python-telegram-bot 创建电报机器人菜单
- jestjs - 如何使用 jest 和酶测试 useRef 的电流?
- javascript - cy.wait 的赛普拉斯良好实践
- npm - 为什么在使用 npm install 时出现权限错误以及如何解决?
- ansible - 通过在 Jinja2/ansible 之间添加一个字符串来合并 2 个列表
- android - OPEN_APP_FEATURE 操作无法通过语音命令运行 [通过应用程序操作测试工具完美运行]
- python - Python tkinter filedialog在mac上禁用菜单