IndexError: list index out of range Python

0

I'm getting the following error:

IndexError: list index out of range

My code:

conts = conts[0] if imutils.is_cv2() else conts[1]

How can I fix this error?

Full Code

    
asked by anonymous 12.09.2018 / 20:02

1 answer

0

This is a problem because of the change from OpenCV 2.4 to OpenCV 3, so some forms are used to work around this problem, giving compatibility between versions. In your code, this is being done the wrong way.

Keep conts = conts[0] if imutils.is_cv2() else conts[1]

Change this line:

_, conts, _ = cv2.findContours(maskFinal.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)

To:

conts = cv2.findContours(maskFinal.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)

Since conts = conts[0] if imutils.is_cv2() else conts[1] is used to get the appropriate tuple value according to the version of OpenCV (2.x or 3.x).

Remove% with%

Another option is to check the version of OpenCV and get output conts = conts[0] if imutils.is_cv2() else conts[1] of type OutputArrayOfArrays:

Instead of:

_, conts, _ = cv2.findContours(maskFinal.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)
conts = conts[0] if imutils.is_cv2() else conts[1]

Use:

if imutils.is_cv2():
    (conts, _) = cv2.findContours(maskFinal.copy(), cv2.RETR_EXTERNAL,
                                 cv2.CHAIN_APPROX_NONE)

# verifica se está utilizando OpenCV 3.X
elif imutils.is_cv3():
    (_, conts, _) = cv2.findContours(maskFinal.copy(), cv2.RETR_EXTERNAL,
                                    cv2.CHAIN_APPROX_NONE)
    
12.09.2018 / 20:36