我正在尝试从轮廓创建一个掩码,但我得到一个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)
Run Code Online (Sandbox Code Playgroud)
输出(参见底部的错误):
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
Run Code Online (Sandbox Code Playgroud)
该文件说,它应该得到一个数组的数组,这似乎是什么,我给它.那有什么不对?
代码从OpenCV 2.x移植.
The*_*ane 17
我想你增加额外的[]周围cnt
应该是
cv2.drawContours(mask, cnt, 0, (0, 255, 0), -1)
Run Code Online (Sandbox Code Playgroud)
as cnt已经[cnt]是数组的数组,但是数组数组的数组不起作用
更新上面的代码
你应该首先将轮廓转换为numpy数组
ctr = numpy.array(cnt).reshape((-1,1,2)).astype(numpy.int32)
cv2.drawContours(mask, [ctr], 0, (0, 255, 0), -1)
Run Code Online (Sandbox Code Playgroud)
在这里查看文档
contours是图像中所有轮廓的Python列表.每个单独的轮廓是对象的边界点的(x,y)坐标的Numpy阵列.
对我来说,这很有效。但是我不确定为什么。
cv2.drawContours(mask, [cnt.astype(int)], 0, (0, 255, 0), -1)
当您从findContours获取圆形舍入数组时,drawContours不会抱怨。但是,当我自己构造一个类似的(4,2)浮点数组时,就会抱怨。
您可能在查找轮廓时犯了错误。Contour 是findContours()函数返回的第二个值,如文档所说
im2, contours, hierarchy = cv.findContours(thresh, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
Run Code Online (Sandbox Code Playgroud)
所以下面的代码将不起作用
cnt = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
Run Code Online (Sandbox Code Playgroud)
这可能会解决您的问题。