Python 错误:(-215:断言失败)npoints>;使用OpenCV处理等高线时为0

Python 错误:(-215:断言失败)npoints>;使用OpenCV处理等高线时为0,python,opencv,contour,Python,Opencv,Contour,当我运行此代码时: import cv2 image = cv2.imread('screenshoot10.jpg') cv2.imshow('input image', image) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) edged = cv2.Canny(gray, 30, 200) cv2.imshow('canny edges', edged) _, contours = cv2.findContours(edged, c

当我运行此代码时:

import cv2

image = cv2.imread('screenshoot10.jpg')
cv2.imshow('input image', image)

gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

edged = cv2.Canny(gray, 30, 200)
cv2.imshow('canny edges', edged)

_, contours = cv2.findContours(edged, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
cv2.imshow('canny edges after contouring', edged)

print(contours)
print('Numbers of contours found=', len(contours))

cv2.drawContours(image, contours, -1, (0, 255, 0), 3)
cv2.imshow('contours', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
我得到这个错误:

OpenCV(4.1.1) C:\projects\opencv python\opencv\modules\imgproc\src\drawing.cpp:2509: 错误:(-215:断言失败)函数中的npoints>0 “cv::drawContours”

我做错了什么?

根据for findContours,该方法返回(轮廓、层次),因此我认为代码应该是:

轮廓,u=cv2.找到的轮廓(边缘,cv2.外部翻新,cv2.链约无)
而不是

\u等高线=cv2.找到的轮廓(边缘,cv2.外部翻新,cv2.链约无)

根据OpenCV版本,
cv2.findContours()
具有不同的返回签名。在
v3.4.X
中,返回三项。在
v2.X
v4.1.X
中,返回两项。您可以很容易地获得轮廓,而不必考虑像这样的版本

cnts = cv2.findContours(image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    ...

由于在使用OpenCV处理等高线时,在查找
错误(-215:断言失败)npoints>0时,此问题会显示在顶部,因此我想指出另一个可能的原因,说明为什么会出现此错误:

在做了
minareact
之后,我使用了
BoxPoints
函数来获得一个围绕轮廓旋转的矩形。在将其传递给drawContours之前,我没有对其输出执行
np.int0
(将返回的数组转换为整数值)。这修正了它:

rect=cv2.minareact(cnt)
box=cv2.cv.BoxPoints(矩形)
box=np.int0(box)#转换为整数值
cv2.等高线图(im,[box],0,(0,0255),2)

这两条打印语句的输出是什么?你发现了多少轮廓?当调用一个错误版本-4.1.1时,它是如何工作的?我的错,不需要假设这个版本,因为它在问题中正确地陈述了。但是,我认为它不会改变答案,因为我已经阅读了4.1.1的文档,它返回一个元组(countours,hierarchy)。