compatibility issue with contourArea in openCV 3

29,461

Solution 1

In Opencv 3 API version the cv2.findContours() returns 3 objects

  • image
  • contours
  • hierarchy

So you need to rewrite your statement as:

image, contours, hierarchy = cv2.findContours(im_bw.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

Solution 2

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]

Solution 3

This problem is caused by the different return value of cv2.findContours in different OpenCV versions.

In OpenCV 4.0.0, this error may looks like cv2.error: OpenCV(4.0.0) C:\projects\opencv-python\opencv\modules\imgproc\src\convhull.cpp:137: error: (-215:Assertion failed) total >= 0 && (depth == CV_32F || depth == CV_32S) in function 'cv::convexHull'

You can find a detailed explanation and solutions here: How to use `cv2.findContours` in different OpenCV versions?

Solution 4

Thanks for @ZdaR; By the way, you can do the following in OpenCV 4.1:

contours, hierarchy = cv2.findContours(im_bw.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
Share:
29,461

Related videos on Youtube

YNWA
Author by

YNWA

Updated on November 02, 2020

Comments

  • YNWA
    YNWA over 3 years

    I am trying to do a simple area calculation of contours I get from findContours. My openCv version is 3.1.0

    My code is:

    cc = cv2.findContours(im_bw.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    cv2.contourArea(cc[0])
    
    error: 'C:\\builds\\master_PackSlaveAddon-win32-vc12-static\\opencv\\modules\\imgproc\\src\\shapedescr.cp...: error: (-215) npoints >= 0 && (depth == CV_32F || depth == CV_32S) in function cv::contourArea\n'
    

    Cant seem to solve it, I have a feeling its just typecasting altough I expect the findContours result to match the type of contourArea

    Thanks :)

    EDIT: turns out I need to take the 2nd argument of findContours

     im2, cc, hierarchy = cv2.findContours(im_bw.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    
    • Martin Beckett
      Martin Beckett almost 8 years
      have you checked if cc[0] is empty ?
    • YNWA
      YNWA almost 8 years
      found it after digging more, turns out I need to get the 2nd argument of findContours
  • Pedro Lobito
    Pedro Lobito about 7 years
    Saved my night, tks!