You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

程序返回‘list index out of range’错误排查求助

MobileNetSSD目标检测“list index out of range”错误排查方案

以下是针对该索引越界问题的具体排查和解决步骤:

  • 先确认class_index的实际取值
    在报错代码行前添加打印语句,直接定位问题根源:

    print(f"class_index: {class_index}, classes列表长度: {len(classes)}")
    prediction_text = f"{classes[class_index]}: {confidence:.2f}%"
    

    运行后查看输出,如果class_index大于等于len(classes),说明确实超出了列表索引范围。

  • 核对classes列表与模型的类别映射
    MobileNetSSD官方预训练模型为21类(包含背景类),你的classes列表必须严格匹配这个数量和顺序,正确的列表如下:

    classes = [
        "background", "aeroplane", "bicycle", "bird", "boat",
        "bottle", "bus", "car", "cat", "chair",
        "cow", "diningtable", "dog", "horse", "motorbike",
        "person", "pottedplant", "sheep", "sofa", "train", "tvmonitor"
    ]
    

    若列表长度不为21或顺序错误,都会导致索引匹配失效。

  • 检查模型文件是否匹配
    确保加载的是官方21类的MobileNetSSD模型文件(MobileNetSSD_deploy.prototxt.txt和MobileNetSSD_deploy.caffemodel),如果加载了其他类别数的变种模型,输出的class_index自然会超出你的classes列表范围。

  • 添加索引安全校验(兜底方案)
    给代码加一层边界判断,避免直接报错同时输出警告信息:

    if 0 <= class_index < len(classes):
        prediction_text = f"{classes[class_index]}: {confidence:.2f}%"
    else:
        prediction_text = f"未知类别(索引{class_index}): {confidence:.2f}%"
        print(f"警告:class_index {class_index} 超出classes列表范围,列表长度为{len(classes)}")
    

内容的提问来源于stack exchange,提问作者DoofenSquid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 15:48:30