OpenCV 3.1 drawContours'( - 215)npoints> 0'

问题描述 投票:5回答:4

我正在尝试从轮廓创建一个掩码,但我得到一个C ++错误。

使用OS X Yosemite,Python 2.7.10,OpenCV 3.1.0。

def create_mask(img, cnt):
    '''Create a mask of the same size as the image
       based on the interior of the contour.'''
    mask = np.zeros((img.shape[0], img.shape[1]), np.uint8)
    print("create_mask, cnt=%s" % cnt)
    cv2.drawContours(mask, [cnt], 0, (0, 255, 0), -1)
    return mask

print("Creating mask from contour %s, on raw shape %s" % (page_contour, raw.shape))
page_mask = create_mask(raw, page_contour)

输出(参见底部的错误):

Creating mask from contour [[ 1626.   360.]
 [ 1776.  3108.]
 [  126.  3048.]
 [  330.   486.]], on raw shape (3840, 2160, 3)
create_mask, cnt=[[ 1626.   360.]
 [ 1776.  3108.]
 [  126.  3048.]
 [  330.   486.]]
OpenCV Error: Assertion failed (npoints > 0) in drawContours, file /tmp/opencv320160309-92782-1efch74/opencv-3.1.0/modules/imgproc/src/drawing.cpp, line 2380
Traceback (most recent call last):
  File "./books.py", line 209, in <module>
    page_mask = create_mask(raw, page_contour)
  File "./books.py", line 123, in create_mask
    cv2.drawContours(mask, [cnt], 0, (0, 255, 0), -1)
cv2.error: /tmp/opencv320160309-92782-1efch74/opencv-3.1.0/modules/imgproc/src/drawing.cpp:2380: error: (-215) npoints > 0 in function drawContours

docs说它应该得到一个数组阵列,这似乎是我给它的。那有什么不对?

代码从OpenCV 2.x移植。

python c++ opencv
4个回答
17
投票

我认为你应该在[]周围添加额外的cnt

cv2.drawContours(mask, cnt, 0, (0, 255, 0), -1)

因为cnt已经是数组的数组但是[cnt]是数组数组的数组,它们不起作用


更新上面的代码

你应该首先将轮廓转换为numpy数组

ctr = numpy.array(cnt).reshape((-1,1,2)).astype(numpy.int32)
cv2.drawContours(mask, [ctr], 0, (0, 255, 0), -1)

检查文档here

contours是图像中所有轮廓的Python列表。每个单独的轮廓是对象的边界点的(x,y)坐标的Numpy阵列。


7
投票

对我来说这很有效。但我不确定为什么。

cv2.drawContours(mask, [cnt.astype(int)], 0, (0, 255, 0), -1)

当你从findContours获得一个圆形浮点数组时,drawContours不会抱怨。但是当我自己构建一个类似的(4,2)浮动数组时,它会抱怨。


2
投票

你可能在找到轮廓时犯了错误。正如findContours()所说,轮廓是docs函数返回的第二个值

im2, contours, hierarchy = cv.findContours(thresh, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)

所以下面的代码不起作用

cnt = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

这可能会解决您的问题。


0
投票

如果您只是使用它,它将工作...

ctr = np.array(cnt).reshape((-1,1,2)).astype(np.int32)
cv2.drawContours(mask, [ctr], -1, 255, -1)
© www.soinside.com 2019 - 2024. All rights reserved.