OpenCV3.3.0 findContours error

℡╲_俬逩灬. 提交于 2020-01-16 09:05:07

问题


I reinstall opencv today, and run my code I've written before. I got the error:

OpenCV Error: Assertion failed (_contours.empty() || (_contours.channels() == 2 && _contours.depth() == CV_32S)) in findContours, file /tmp/opencv-20170916-87764-1y5vj25/opencv-3.3.0/modules/imgproc/src/contours.cpp, line 1894 Traceback (most recent call last): File "pokedex.py", line 12, in (cnts, _) = cv2.findContours(gray, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE, (2,2)) cv2.error: /tmp/opencv-20170916-87764-1y5vj25/opencv-3.3.0/modules/imgproc/src/contours.cpp:1894: error: (-215) _contours.empty() || (_contours.channels() == 2 &&_contours.depth() == CV_32S) in function findContours

The code works fine with opencv2.4.13.3.

code:

image = cv2.imread("test.jpg")

gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)    // `len(gray.shape)` is 2.

(cnts, _) = cv2.findContours(gray, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE, (2,2))

version info: opencv 3.3.0, python 2.7.13, macOS 10.13


回答1:


  1. What is (2,2)? The fourth positional argument for findContours() is the output contours array. But you're not passing it a valid format for the contours array (which is an array of points). If it's supposed to be the offset and you don't want to provide the additional positional arguments, you need to call it by keyword like offset=(2,2). This is the reason for the actual error. I'm not sure why this worked in the previous version, as it accepted the same arguments in the same order, and Python has been like this forever; if the arguments are optional, you need to provide enough positional arguments up to the argument, or provide it a keyword.

  2. findContours() returns three values in OpenCV 3 (in OpenCV 2 it was just two values), contours is the second return value; should be

    _, contours, _ = findContours(...) 
    

    Also you don't have to wrap into a tuple in python for assignment, you can just do x, y, z = fun(), no need to do (x, y, z) = fun(). Additionally you could just ask for the second return value by indexing the result like

    contours = cv2.findContours(...)[1]
    

So this should clear you up:

cnts = cv2.findContours(gray, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE, offset=(2,2))[1]

These docs for OpenCV 3 have the Python syntax, so you can browse there if any of your other prior code breaks, and see if the syntax has changed.



来源:https://stackoverflow.com/questions/46462198/opencv3-3-0-findcontours-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!