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

自定义训练ssd_mobilenet_v2转TFLite后运行推理报SetTensor参数不兼容错误

问题原因
  • 核心参数传参错误:interpreter.set_tensor()的第一个入参要求是输入张量的整数索引,但你错误传入了input_details[0]['shape_signature'](数组类型),和接口要求的int类型不匹配,直接触发类型报错。
  • 张量内存分配未执行:你注释了interpreter.allocate_tensors(),这行是TFLite推理前必须执行的步骤,用于给输入输出张量分配内存,缺少这步后续推理也会报错。
  • 输入预处理不符合模型要求:你训练的是ssd_mobilenet_v2_fpnlite_320x320模型,要求输入固定为320×320尺寸的RGB图像,你当前代码直接读入原图reshape,没有做resize操作,且OpenCV默认读入为BGR通道,和模型训练的通道顺序不符。
  • 冗余类型转换:代码中先将图像转为uint32再转回uint8的操作完全冗余,无实际意义还可能引入精度问题。
解决方案

修改后的推理代码如下:

import tensorflow as tf
import cv2
import numpy as np
import pathlib

# 初始化模型解释器
interpreter = tf.lite.Interpreter(model_path="C:/Users/CX/Desktop/model.tflite")
# 必须执行张量内存分配
interpreter.allocate_tensors()

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

# 匹配模型要求的输入尺寸
INPUT_SIZE = (320, 320)
path = r"C:\t3"

for file in pathlib.Path(path).iterdir():
    # 读取本地图片
    img = cv2.imread(str(file.resolve()))
    # OpenCV默认BGR通道,转成模型训练用的RGB通道
    img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    # 缩放至模型要求的320×320尺寸
    img_resized = cv2.resize(img_rgb, INPUT_SIZE)
    # 新增batch维度,转换为输入要求的uint8类型
    input_tensor = np.expand_dims(img_resized, axis=0).astype(np.uint8)
    
    # 第一个参数传入输入张量的整数索引,第二个传入处理好的输入数据
    interpreter.set_tensor(input_details[0]['index'], input_tensor)
    interpreter.invoke()
    
    # 按需读取输出张量完成后处理即可
    # output = interpreter.get_tensor(output_details[你需要的输出下标]['index'])

本次修改核心点:

  1. 将set_tensor第一个入参修改为input_details[0]['index'],匹配接口参数要求
  2. 恢复allocate_tensors()调用,在解释器初始化后立即执行
  3. 补充符合模型要求的预处理逻辑,对齐输入尺寸、通道顺序和数据类型
  4. 删除冗余的无效类型转换步骤

内容的提问来源于stack exchange,提问作者Ayad T.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 05:39:03