Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Contours tuple must have length 2 or 3, otherwise opencv changed their cv.findcontours signature yet again

After running my code I get the error message contours tuple must have length 2 or 3, otherwise opencv changed their return signature yet again. I am currently running ver 3.4.3.18 of opencv. The issue occurs when I grab the contours running imutils ver 0.5.2

The code finds the countours and returns the contours found after doing some edge detection. The algorithm then uses imutils to grab the contours. Is this the right way of going about it or is there some up to date way of getting the contours instead of using imutils?

Please see an example below:

image, contours, hier = cv.findContours(edged.copy(), cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)


cnts = imutils.grab_contours(contours)

cnts = sorted(contours, key = cv.contourArea, reverse = True)[:5]
like image 919
James Phelps Avatar asked Nov 07 '22 17:11

James Phelps


1 Answers

Depending on the OpenCV version, findContours() has varying return signatures.

In OpenCV 3.4.X, findContours() returns 3 items

image, contours, hierarchy = cv.findContours(image, mode, method[, contours[, hierarchy[, offset]]])

In OpenCV 4.1.X, findContours() returns 2 items

contours, hierarchy = cv.findContours(image, mode, method[, contours[, hierarchy[, offset]]])

To manually get contours without using imutils, you can check the amount of items in the returned tuple

items = cv.findContours(edged.copy(), cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
contours = items[0] if len(items) == 2 else items[1]
like image 120
nathancy Avatar answered Nov 13 '22 15:11

nathancy