项目场景:
python3
opencv cv2
问题描述:
执行cv2.drawcontour()函数报错:
… error: (-215:Assertion failed) npoints > 0 in function ‘cv::drawContours’
location = np.array([[10, 10], [50, 10], [50, 50], [10, 50]])
cv2.drawContours(mask, location, -1, 255, -1)
原因分析:
- 首先来看一下drawContours函数的作用
与drawContours() 对应的函数为findContours() ,首先通过findContours() 查找图像的轮廓,再使用drawContours() 将找到的轮廓画出来。
对应到代码中即为以图像mask为背景将location中的所有轮廓以白色 填充。
- 问题点定位
这里其它的参数都没有问题,除了contours为我自己定义的,也就是变量location。
- 对比分析
将location打印出来为:
而findContours() 执行后的轮廓为:
其具体的差别在于findContours() 执行后得到的轮廓为列表格式的narray,而location为narray格式。故具体是由于格式错误导致的断言。
解决方案:
既然问题找到了,解决方案自然很简单,将contours参数改成列表就行了。
cv2.drawContours(mask, [location], -1, 255, -1)
附:
def drawContours(image, contours, contourIdx, color, thickness=None, lineType=None, hierarchy=None, maxLevel=None, offset=None):
image:背景图像 cv读取的map格式
contours:轮廓列表 list格式,下一层结构均为numpy的array类型,且其中对应的点均在图像内
contourIdx:要画的轮廓个数,-1 表示全部
color:轮廓颜色 可以是单通道或三通道
thickness:轮廓线的宽度 ,-1 表示轮廓内填充 (算法应该是内外各一半)