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

Yolov5转TFLite模型及目标检测报错求助

解决YOLOv5 TFLite推理时的输入类型不匹配问题

问题根源

你导出的yolov5m-fp16.tflite模型输入要求为FLOAT32类型,但推理代码直接传入了UINT8类型的图像数组,导致类型不匹配报错。YOLOv5模型训练和推理的输入是归一化到0-1区间的浮点数张量,而非原始0-255范围的整数像素值。

修正步骤

1. 修复代码语法错误

你的代码中input_tensor = np.expand_dims(input_tensor, axis=0)缺少闭合括号,需先补全这一语法问题。

2. 转换输入张量类型并归一化

将UINT8类型的图像数组转换为FLOAT32,同时除以255.0完成归一化,匹配模型的输入要求。

修正后的完整推理代码

import numpy as np
from PIL import Image, ImageDraw, ImageFont
import tensorflow as tf
import time

# 加载模型
model_path = '/content/yolov5/yolov5m-fp16.tflite'
interpreter = tf.lite.Interpreter(model_path=model_path)
interpreter.allocate_tensors()

input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()

# 处理输入图像
image = Image.open('/content/picture1.jpg').resize((640, 640))
input_tensor = np.array(image, dtype=np.float32)  # 转换为模型要求的FLOAT32类型
input_tensor = input_tensor / 255.0  # 将像素值归一化到0-1区间
input_tensor = np.expand_dims(input_tensor, axis=0)  # 补全batch维度(修复语法错误)

# 执行推理
interpreter.set_tensor(input_details[0]['index'], input_tensor)
interpreter.invoke()

# 获取输出并处理(示例)
output_data = interpreter.get_tensor(output_details[0]['index'])
# 后续可添加结果解析、绘制检测框等逻辑

额外验证建议

可以打印input_details查看模型的输入要求,确认类型和归一化规则:

print(input_details[0])

输出会包含dtype(显示tf.float32)和quantization参数(非量化模型通常为(0.0, 1.0),代表直接输入0-1浮点数即可)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 10:08:06