Indexerror: list index out of range Python

Asked

Viewed 548 times

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 correct this mistake?

Complete code

1 answer

1

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

Keep up 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)

for:

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

Since conts = conts[0] if imutils.is_cv2() else conts[1] serves to get the value of the appropriate list according to the Opencv version (2.x or 3.x).

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

Another option is to check which version of Opencv and get the output contours of the 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]

Utilize:

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)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.