pythonimageopencvcontourimutils

Contours tuple must have length 2 or 3, otherwise OpenCV changed their cv2.findContours return signature yet again- find contour in a specific area


cnts,_ = cv2.findContours(cv.rectangle(img3.copy(), (0,200) , (5000, 1150), (255,0,0), 2) ,cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(rgb_img, cnts, -1, (0,255,0), 2)


conts = imutils.grab_contours(cnts)
c = max(conts, key=cv2.contourArea)

I'm trying to find the contours of two irregular edges in between the image. Else the rectangular actual edge of the image is being detected as contour max area. So i thought of using a rectangular area where I want it to exactly detect the edges.


Solution

  • You are using imutils.grab_contours wrong.

    You did already do the destructuring yourself, with

    (cnts, *_) = cv.findContours(...)
    

    In that case, you don't need imutils at all.

    If you want to use imutils anyway, you need to pass it the entire tuple (2-tuple or 3-tuple) returned by cv.findContours, like so: cnts = imutils.grab_contours(cv.findContours(...))


    OpenCV 4.x (also 2.x I think)'s findContours returns a tuple of (contours, hierarchy).

    OpenCV 3.x had an additional return value in the tuple that was an accident of implementation. The signature was (image, contours, hierarchy). The image passed into the call isn't touched. It was accidentally returned in the tuple.

    imutils.grab_contours is supposed to unify this. You're supposed to pass the entire tuple to it. It will then return just the contours, regardless of which variant it received.