Search code examples
pythonopencvartificial-intelligenceobject-detection

IndexError: list index out of range python - opencv


from xml.parsers.expat import model
from ultralytics import YOLO
import cv2
import cvzone
import math


cap = cv2.VideoCapture(0)
cap.set(3, 2560)
cap.set(4, 1400)

model = YOLO('../Yolo-Weights/yolov8n.pt')

classNames = ["person", "bicycle", "car", "pencil", "pen", "plate", "plane", "suitcase", 
              "gun", "cake", "dog", "copybook", "book", "pizza", "cup", "soup", "chair", "windows", "wall"]

while True:
    success,  img = cap.read()
    results = model(img, stream=True)
    for r in results:
        boxes = r.boxes
        for box in boxes:

            # Bounding box
            x1, y1, x2, y2 = box.xyxy[0]
            x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2)
            # cv2.rectangle(img, (x1, y1), (x2, y2), (255, 0 , 255), 3)


        w, h = x2 - x1, y2 - y1
        cvzone.cornerRect(img, (x1, y1, w, h))
        # Confidence
        conf = math.ceil((box.conf[0] * 100))/100 
        # Class Name
        cls = int(box.cls[0])


        cvzone.putTextRect(img, f'{classNames[cls]} {conf}', (max(0, x1), max(35, y1)),scale=0.7, thickness=1)

    cv2.imshow('Image', img)
    cv2.waitKey(1)


    key = cv2.waitKey(1)
    if key == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

I just wrote detector and everything work properly before I try to give classNames and caught an error

`cvzone.putTextRect(img, f'{classNames[cls]} {conf}', (max(0, x1), max(35, y1)),scale=0.7, thickness=1)
                               ~~~~~~~~~~^^^^^
IndexError: list index out of range`

I caught this error and I don't know how to fix that I searched materials on Internet but I didn't find anything. Please help me


Solution

  • Looks like cls has a value that is larger than the number of classes defined in classNames (hence the indexError). To check that, you can add a try...except:

    # Class index
    cls = int(box.cls[0])
    
    try:
        classname = classNames[cls]
    except IndexError:
        classname = 'another_undefined_class'
        print(f"error, index:{cls}")
    
    
    cvzone.putTextRect(img, f'{classname} {conf}', (max(0, x1), max(35, y1)),scale=0.7, thickness=1)