IndexError:list index out of range python - opencv

7nbnzgx9  于 2023-08-06  发布在  Python
关注(0)|答案(1)|浏览(106)
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()

字符串
我只是写了探测器和一切工作正常之前,我试图给予classNames和捕捉到一个错误

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


我抓住了这个错误,我不知道如何解决,我在互联网上搜索材料,但我没有找到任何东西。请帮帮我

xytpbqjk

xytpbqjk1#

看起来cls的值大于classNames中定义的类的数量(因此出现了indexError)。要检查这一点,您可以添加一个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)

字符串

相关问题