我是计算机视觉的新手,还没有真正学习过任何关于阈值处理、模糊处理或其他过滤器的教程。我正在使用下面的两段代码来找出图像中的轮廓。一方面,该方法有效,但另一方面却无效。我需要帮助来理解发生这种情况的原因,以便说服自己在后台发生的事情。
工作代码片段:
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, inim2, 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
仅返回 2 个值:轮廓和层次结构。之前,在 3.x 版本中,它返回 3 个值。您可以使用 documentation比较不同的版本。
当您将代码更改为:
时,第二个代码片段应该可以工作:
# find contours
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
无法根据给定的信息确定为什么第一个代码片段选择了不同的 openCV 版本。
我是一名优秀的程序员,十分优秀!