问题
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:
What is
(2,2)
? The fourth positional argument forfindContours()
is the outputcontours
array. But you're not passing it a valid format for thecontours
array (which is an array of points). If it's supposed to be theoffset
and you don't want to provide the additional positional arguments, you need to call it by keyword likeoffset=(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.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 dox, 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 likecontours = 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