【发布时间】: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/… -
谢谢大家!由于我在代码中使用了较旧的示例,因此层次结构被颠倒了。