错误:(-215:断言失败)使用OpenCV处理轮廓时,npoints> 0

时间:2019-10-08 16:09:08

标签: 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,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)
cv2.imshow('canny edges after contouring', edged)

print(contours)
print('Numbers of contours found=' + str(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'

我在做什么错了?

3 个答案:

答案 0 :(得分:1)

取决于OpenCV版本,cv2.findContours()具有不同的返回签名。在v3.4.X中,返回三个项目。在v2.Xv4.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:
    ...

答案 1 :(得分:0)

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

contours, _ = cv2.findContours(edged,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)

代替

_, contours = cv2.findContours(edged,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)

答案 2 :(得分:0)

由于此问题在寻找Error: (-215:Assertion failed) npoints > 0 while working with contours using OpenCV时显示在顶部,因此我想指出另一个可能导致此错误的原因:

在执行BoxPoints之后,我使用了minAreaRect函数来获得围绕轮廓的旋转矩形。在将其传递给drawContours之前,我尚未完成np.int0的输出(将返回的数组转换为整数值)。这样就解决了:

rect = cv2.minAreaRect(cnt)
box = cv2.cv.BoxPoints(rect) 
box = np.int0(box) # convert to integer values
cv2.drawContours(im,[box],0,(0,0,255),2)