【问题标题】:cv2.contourArea will always return an errorcv2.contourArea 总是会返回错误
【发布时间】:2022-06-20 10:23:43
【问题描述】:

无论我尝试什么,我似乎都无法让 cv2.contourArea 正常工作,它总是会返回错误:

(-215:Assertion failed) npoints >= 0 && (depth == CV_32F || depth == CV_32S) in function 'contourArea'

我的代码正在尝试找到图像中最大的轮廓,并使用以下代码删除其余部分:

def find_biggest_contour(image):

# Copy to prevent modification
image = image.copy()

_,contours  = cv2.findContours(image, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)

#get contour sizes and return the biggest contour
max_area = -1
for i in range(len(contours)):
    area = cv2.contourArea(contours[i])
    if area>max_area:
        biggest_contour = contours[i]
        max_area = area

#create an empty mask
mask = np.zeros(image.shape, np.uint8)

#draw the biggest contour on it
cv2.drawContours(mask, [biggest_contour], -1, 255, -1)

return mask

【问题讨论】:

  • 你真的有轮廓吗?您需要二值图像来获取轮廓,并且区域必须是白色的。我没有看到任何阈值。你的len(contours)是什么@
  • 请参阅下面来自@vscv 的答案。我认为你的轮廓和层次结构的顺序被交换了。但返回值的顺序和数量取决于版本。您使用的是什么版本的 OpenCV。例如,在 4.1.1 中,它在 docs.opencv.org/4.1.1/d3/dc0/… 中进行了描述。因此,您提供的 contourArea 层次结构不是该索引的轮廓。
  • 欢迎。请查看How to Ask。你应该调试你的代码。在这里,您应该已经查看了该变量的值(实际上都是由 findContours 返回的)并考虑这是否有意义。
  • cv2.findContours() 的返回值数量随时间而变化。见stackoverflow.com/questions/55854810/…
  • 谢谢大家!由于我在代码中使用了较旧的示例,因此层次结构被颠倒了。

标签: python opencv contour


【解决方案1】:

也许只是返回值顺序颠倒了。

contours, hierarchy = cv2.findContours()

ps。这项工作适用于 cv 4.x、5.x。

4.x https://docs.opencv.org/4.x/d3/dc0/group__imgproc__shape.html#gadf1ad6a0b82947fa1fe3c3d497f260e0

5.x https://docs.opencv.org/5.x/d3/dc0/group__imgproc__shape.html#gadf1ad6a0b82947fa1fe3c3d497f260e0

【讨论】:

  • 可能,但数量和顺序取决于版本。
  • 不过,这似乎是个问题,因为蛇没有抱怨ValueError: too many values to unpack (expected 2)
  • 这就是问题所在,事实证明,这个函数的大多数文档都已经过时了,并且会告诉你情况正好相反。
猜你喜欢
  • 2013-07-30
  • 2014-03-14
  • 2018-07-16
  • 2018-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-29
相关资源
最近更新 更多