首页 > 解决方案 > 为什么在一个代码中 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)

让我知道是否还需要任何其他信息。

标签: pythonopencvcomputer-visionimage-thresholding

解决方案


这是由于 openCV 发生了变化。由于 4.0 版findContours只返回 2 个值:轮廓和层次结构。之前,在 3.x 版本中,它返回 3 个值。您可以使用文档来比较不同的版本。

当您将代码更改为:

# find contours
    contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

为什么第一个片段选择不同的 openCV 版本无法从给定的信息中确定。


推荐阅读