【问题标题】:cv2.findContours function is not working in both versions为什么在一个代码中 cv2.findContours 函数有效,但在另一个代码中无效?
【发布时间】:2019-09-27 14:58:41
【问题描述】:

我是计算机视觉的新手,还没有真正学习过任何关于阈值、模糊或其他过滤器的教程。 我正在使用以下两个代码来找出图像中的轮廓。一方面该方法有效,但另一方面却无效。我需要帮助来了解发生这种情况的原因,以便说服自己在后台发生了什么。

工作代码sn-p:

    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)

不工作的代码 sn-p

# 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, 轮廓, 层次结构 = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) ValueError: 没有足够的值来解压 (预期 3 个,得到 2 个)

如果还需要任何其他信息,请告诉我。

【问题讨论】:

    标签: python opencv computer-vision image-thresholding


    【解决方案1】:

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

    当您将代码更改为时,第二个代码 sn-p 应该可以工作:

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

    从给出的信息无法确定为什么第一个 sn-p 选择不同的 openCV 版本。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-25
      • 2019-04-16
      • 1970-01-01
      • 2020-08-09
      相关资源
      最近更新 更多