在Coral EdgeTPU上运行推理出现IndexError: index 10越界错误
问题复现
尝试使用Coral官方提供的detect_image.py示例脚本,运行由tflite和Coral EdgeTPU编译器生成的int8量化检测模型,执行命令如下:
python3 examples/detect_image.py \ --model test_data/int8_model_edgetpu.tflite \ --labels test_data/tflite_label_map.txt \ --input test_data/parrot.jpg \ --output ${HOME}/parrot.jpg
运行后出现如下报错:
Traceback (most recent call last): File "examples/detect_image.py", line 109, in <module> main() File "examples/detect_image.py", line 88, in main objs = detect.get_objects(interpreter, args.threshold, scale) File "/home/mha/miniconda3/envs/tensorflow2/lib/python3.6/site-packages/pycoral/adapters/detect.py", line 237, in get_objects return [make(i) for i in range(count) if scores[i] >= score_threshold] File "/home/mha/miniconda3/envs/tensorflow2/lib/python3.6/site-packages/pycoral/adapters/detect.py", line 237, in <listcomp> return [make(i) for i in range(count) if scores[i] >= score_threshold] IndexError: index 10 is out of bounds for axis 0 with size 10
错误原因
- 错误本质是数组索引越界:你使用的自定义训练检测模型,输出的得分张量(scores)长度只有10,索引范围是0~9,但pycoral的
detect.get_objects接口读取模型输出的num_detections字段得到的数值大于等于11,遍历的时候访问了索引10的元素,触发越界。 - 常见触发场景:训练模型时设置的最大检测输出数为10,但模型导出、EdgeTPU编译阶段没有对齐相关参数,导致
num_detections返回值和实际scores数组长度不匹配。
解决方案
- 首先验证模型输出维度,确认张量长度是否匹配:
运行如下代码打印模型输出信息:
确认得分张量的第一维是否为10,import tflite_runtime.interpreter as tflite interpreter = tflite.Interpreter(model_path="test_data/int8_model_edgetpu.tflite") interpreter.allocate_tensors() for output_tensor in interpreter.get_output_details(): print(f"张量名:{output_tensor['name']},维度:{output_tensor['shape']}")num_detections张量的输出最大值是否小于等于10。 - 临时修复接口逻辑:
找到pycoral安装路径下的adapters/detect.py文件,修改第237行的遍历范围,将range(count)改为range(min(count, len(scores))),强制限制索引不超过数组长度。 - 永久修复模型导出逻辑:
重新导出tflite模型时,将max_detections、max_classes_per_detection等参数设置为和训练阶段完全一致的数值,保证num_detections的返回值不会超过实际scores数组的长度,再重新用EdgeTPU编译器编译模型即可。
内容的提问来源于stack exchange,提问作者Hasnain
相关产品推荐
相关产品推荐

