opencv + python:findcontours时断言失败

时间:2016-05-07 05:34:13

标签: python opencv

我正在开展图像处理项目。

我使用的是opencv 2.4.11 + python 2.7

代码很简单

def preprocessing(src):
    src = cv2.resize(src, (0,0), fx=6, fy=6)
    kernel = np.ones((5,5), np.uint8)

    dilate = cv2.dilate(src, kernel, iterations = 1)
    erode = cv2.erode(dilate, kernel, iterations = 1)

    cv2.imshow("dilate", dilate)
    cv2.imshow("erode", erode)

    th, thresh = cv2.threshold(erode, 200, 255, cv2.THRESH_BINARY)
    cv2.imshow("thresh", thresh)

    contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
    cv2.drawContours(src,contours,-1,(0,255,0),3)

    cv2.imshow("src", src)
    cv2.waitKey()


print "==== start image processing ====="
im2 = cv2.imread("training1.png",cv2.CV_LOAD_IMAGE_GRAYSCALE)
preprocessing(im2)

但是findcontours返回断言失败

输出

OpenCV Error: Assertion failed (step[dims-1] == (size_t)CV_ELEM_SIZE(flags)) in create, file /tmp/opencv20160107-29960-t5glvv/opencv-2.4.12/modules/core/src/matrix.cpp, line 236
Traceback (most recent call last):
  File "process.py", line 55, in <module>
preprocessing(im2)
  File "process.py", line 44, in preprocessing
contours, hierarchy =  cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
cv2.error: /tmp/opencv20160107-29960-t5glvv/opencv-2.4.12/modules/core/src/matrix.cpp:236: error: (-215) step[dims-1] == (size_t)CV_ELEM_SIZE(flags) in function create

有人可以帮忙吗?非常感谢你

3 个答案:

答案 0 :(得分:1)

代码工作正常。原因是图像文件丢失了。

答案 1 :(得分:1)

解决方案

  1. 取消brew中的opencv。

  2. 下载Anaconda软件包:http://continuum.io/downloads#all并安装。

  3. 安装openCV:“conda install opencv”,版本为2.4.8。

  4. 如果anaconda与瓶颈冲突,请删除引用并通过conda install命令再次安装。

    我仍然不知道为什么opencv 2.4.12抛出这样的异常,我猜这是因为numpy与opencv冲突。

答案 2 :(得分:0)

您需要将图像转换为灰度,然后尝试轮廓。它对我有用