cv2.findContours 功能在两个版本中均无效

cv2.findContours function is not working in both versions

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

工作代码片段:

    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 (most recent call last): File "convexhull.py", line 27, in im2, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) ValueError: not enough values to unpack (expected 3, got 2)

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

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

当您将代码更改为:

时,第二个代码片段应该可以工作
# find contours
    contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

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

无论您 system/environment 中安装的 OpenCV 版本如何,以下代码片段都可以正常工作,并且还会将所有元组存储在单独的变量中,以便稍后在代码中使用。

存储安装的 OpenCV 主要版本:

import cv2
major_version = cv2.__version__[0]

根据版本,将执行以下两个语句之一并填充相应的变量:

if major_version == '4':
    contours, hierarchy = cv2.findContours(image_binary, cv2.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)

elif major_version == '3':
    image, contours, hierarchy = cv2.findContours(image_binary, cv2.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)

在任一情况下从函数返回的轮廓将存储在 contours