Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

findContours and drawContours errors in opencv 3 beta/python

Tags:

python

opencv

I try to run an example from here.

import numpy as np
import cv2
img = cv2.imread('final.jpg')
imgray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(imgray,127,255,0)
contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(img, contours, -1, (0,255,0), 3)

The error is

 Traceback (most recent call last):
   File "E:\PC\opencv3Try\findCExample.py", line 7, in <module>
contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
 ValueError: too many values to unpack (expected 2)

If I delete "hierarchy" the error arises in drawContours:

TypeError: contours is not a numpy array, neither a scalar

If I use contours[0] in drawContours

cv2.error: E:\opencv\opencv\sources\modules\imgproc\src\drawing.cpp:2171: error: (-215) npoints > 0 in function cv::drawContours

What problems could be here?

like image 259
Dmitriy Kozlov Avatar asked Jan 23 '15 15:01

Dmitriy Kozlov


3 Answers

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:
    ...
like image 84
nathancy Avatar answered Oct 24 '22 10:10

nathancy


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

cv2.findContours(image, mode, method[, contours[, hierarchy[, offset]]]) → image, contours, hierarchy
like image 12
berak Avatar answered Oct 24 '22 10:10

berak


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:]
like image 12
Ulrich Stern Avatar answered Oct 24 '22 11:10

Ulrich Stern