cvlib causing IndexError: invalid index to scalar variable

Viewed 1364

I am trying to follow a simple object detection tutorial using cvlib, but i am consistently running into an IndexError and cannot find anyone else struggling with this issue. Below is the full code i basically copy and pasted from tutorials and the output. Any help is appreciated!

Code:

import cv2
import numpy as np
import matplotlib.pyplot as plt
import cvlib as cv
from cvlib.object_detection import draw_bbox, detect_common_objects
from numpy.lib.polynomial import poly

input = cv2.imread('cars1.jpg')

image = cv2.cvtColor(input,cv2.COLOR_BGR2RGB)

plt.axis('off')

box, label, count = cv.detect_common_objects(image)

output = draw_bbox(image, box, label, count)

plt.imshow(output)

plt.show()

Output

Traceback (most recent call last):   
File "/Users/zechariahtay/Desktop/ttt.py", 
line 19, in <module>
    box, label, count = cv.detect_common_objects(image)   
File "/usr/local/lib/python3.9/site-packages/cvlib/object_detection.py",
line 135, in detect_common_objects
    outs = net.forward(get_output_layers(net))   
File "/usr/local/lib/python3.9/site-packages/cvlib/object_detection.py",
line 29, in get_output_layers
    output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]   
File
"/usr/local/lib/python3.9/site-packages/cvlib/object_detection.py",
line 29, in <listcomp>
    output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()] 
IndexError: invalid index to scalar variable
2 Answers

If you are using OpenCV > 4.5.3 it may be related to this bug introduced in v4.5.4. I had the same error and it was fixed when I downgraded (pip3 install opencv-python==4.5.3.56).

There is no need to downgrade your OpenCV version. The later versions return a 1D array containing the indices of each layer. Just avoid indexing ([0]) as shown in the following:

output_layers = [layer_names[i - 1] for i in net.getUnconnectedOutLayers()]

Related