0

Sometimes when I use this function, it does not detect the edges of an image, that is because I would like to know how to exit the function, in case it does not find any contour, with an if loop for example.

def sort_contours(cnts,reverse = False):
    i = 0
    boundingBoxes = [cv2.boundingRect(c) for c in cnts]
    #if cnts==0:
      #quit()
    (cnts, boundingBoxes) = zip(*sorted(zip(cnts, boundingBoxes),
                                        key=lambda b: b[1][i], reverse=reverse))
    return cnts

With this output in failure case:

      7     (cnts, boundingBoxes) = zip(*sorted(zip(cnts, boundingBoxes),
----> 8                                         key=lambda b: b[1][i], reverse=reverse))
      9     return cnts
     10 

ValueError: not enough values to unpack (expected 2, got 0)

Before I made this

#if cnts==0:
  #quit()

Which does not work, any ideas?

Sebastián
  • 437
  • 5
  • 19
  • Your code doesn't make any sense alongside a `cnts==0` test, since `cnts` is some kind of sequence. Probably you want `len(cnts) == 0` or just `not cnts`. As for how to exit, you'll either need to `return` something, or `raise` an exception of some type. How do you expect the code that calls `sort_contours` to handle the invalid case you're dealing with here? – Blckknght Jun 05 '20 at 20:25
  • Actually, is this all of the code for this function (not an excerpt)? If so, you might be able to work around the issue by making the `boundingRect` part of the `key` function you're sorting with. That would eliminate the need for the `zip` and unpacking that's raising an exception when cnts is empty. Try: `cnts = sorted(cnts, key=lambda c: cv2.boundingRect(c)[i], reverse=reverse)` – Blckknght Jun 05 '20 at 20:31
  • Thanks for the reply Blckknght, I solved using exceptions, Tried your advise and also worked, thanks again! – Sebastián Jun 05 '20 at 20:39

0 Answers0