python - OpenCV 3.1 绘制轮廓 '(-215) npoints > 0'

标签 python c++ opencv

我正在尝试从轮廓创建 mask ,但出现 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 移植过来的。

最佳答案

我认为您在 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 is a Python list of all the contours in the image. Each individual contour is a Numpy array of (x,y) coordinates of boundary points of the object.

关于python - OpenCV 3.1 绘制轮廓 '(-215) npoints > 0',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35902139/

相关文章:

python - 如何将生成器用作具有多处理映射函数的可迭代对象

c++ - 为什么以下代码不会产生段错误?

C++ : initialize input programmatically

c++ - 通过傅里叶变换的振荡和频谱

c# - 是否可以从单元测试中显示 Windows 窗体?

python - 如何在使用python检测边缘后将图像裁剪成碎片

c++ - 在 OpenCV 中使用时间进行帧处理和其他任务

python - 将 html 兄弟作为单独的项目抓取?

python - 删除列表中的不同实例

python - 我的dicts of dicts是否适用于这个Dijkstra算法?