Search code examples
pythonopencvobject-detection

IndexError: list index out of range (Object Detection)


import cv2
thres = 0.45 

cap = cv2.VideoCapture(0)   
cap.set(3,1280)
cap.set(4,720)
cap.set(10,70)

classNames= []
classFile = 'coco.names'

with open(classFile,'rt') as f:
    classNames = f.read().rstrip('n').split('n')

configPath = 'ssd_mobilenet_v3_large_coco_2020_01_14.pbtxt'
weightsPath = 'frozen_inference_graph.pb'

net = cv2.dnn_DetectionModel(weightsPath,configPath)

net.setInputSize(320,320)
net.setInputScale(1.0/ 127.5)
net.setInputMean((127.5, 127.5, 127.5))
net.setInputSwapRB(True)

while True:
    success,img = cap.read()
    classIds, confs, bbox = net.detect(img,confThreshold=thres)
    print(classIds,bbox)

    if len(classIds) != 0:
        for classId, confidence,box in zip(classIds.flatten(),confs.flatten(),bbox):
            cv2.rectangle(img,box,color=(0,255,0),thickness=2)
            cv2.putText(img,classNames[classId-1].upper(),(box[0]+10,box[1]+30),
                        cv2.FONT_HERSHEY_COMPLEX,1,(0,255,0),2)
            cv2.putText(img,str(round(confidence*100,2)),(box[0]+200,box[1]+30),
                        cv2.FONT_HERSHEY_COMPLEX,1,(0,255,0),2)

    cv2.imshow("Output",img)
    cv2.waitKey(1)

The error message:

line 31, in <module>
    cv2.putText(img,classNames[classId-1].upper(),(box[0]+10,box[1]+30),
IndexError: list index out of range
[ WARN:1] global C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-wvn_it83\opencv\modules\videoio\src\cap_msmf.cpp (434) `anonymous-namespace'::SourceReaderCB::~SourceReaderCB terminating async callback

Why is this list index out of range and what can I do to fix it?

'coco.names' , 'ssd_mobilenet_v3_large_coco_2020_01_14.pbtxt' and 'frozen_inference_graph.pb' are including in the following link: https://mega.nz/file/UIlQ1L7Y#ePLIQMSlhwo6ab46f1GgYli9nNw6EFIE6mb33-GZnHs


Solution

  • your classNames were not getting build properly that is why you were getting index out of range.

    for example, you got class id as 47(which is a cup) but an entry for 46(classid -1) was not present in classNames.

    so the fix would be:

    with open(classFile,'rt') as f:
        classNames=[line.rstrip() for line in f]
    

    below is a demonstration before and after the above fix: enter image description here