findContours and drawContours errors in opencv 3 beta/python

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

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

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

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

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

You can easily obtain the contours regardless of the version like this:

cnts = cv2.findContours(image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    ...

opencv 3 has a slightly changed syntax here, the return values differ:

cv2.findContours(image, mode, method[, contours[, hierarchy[, offset]]]) → image, contours, hierarchy

I encounter same problem before and i use this code to fix it. Im using 3.1 anyway.

(_,contours,_) = cv2.findContours(
  thresh.copy(),
  cv2.RETR_LIST,
  cv2.CHAIN_APPROX_SIMPLE
)

Following on berak's answer, just adding [-2:] to findContours() calls makes them work for both OpenCV 2.4 and 3.0:

contours, hierarchy = cv2.findContours(...)[-2:]

Tags:

Python

Opencv