TFLite加载SSD-MobileNet_V2报输入张量维度不匹配错误求助
TFLite动态尺寸模型输入维度不匹配问题解决方案
问题根源
你使用的是支持动态输入分辨率的TFLite目标检测模型,模型加载后默认使用初始化的输入shape [1,1,1,3],你没有在分配张量前显式指定实际使用的输入尺寸,直接传入(1,320,320,3)的张量就会触发维度不匹配报错。
另外你的预处理代码存在逻辑bug:归一化操作后的结果没有被后续代码使用,实际传入模型的是未做归一化的原始图像数组,即使解决尺寸问题也无法得到正确推理结果。
修复步骤
- 加载模型获取输入输出详情后,不要立刻调用
allocate_tensors(),先调用resize_tensor_input接口将输入张量的尺寸设置为你实际使用的(1, 320, 320, 3),再执行张量内存分配。 - 修正预处理逻辑,确保归一化到[-1,1]区间的图像数据被正确传入模型,不要覆盖预处理结果。
修正后完整代码
import numpy as np import tensorflow as tf from PIL import Image # 初始化解释器 interpreter = tf.lite.Interpreter(model_path='lite-model_ssd_mobilenet_v2_fpn_100_fp32_default_1.tflite') input_details = interpreter.get_input_details() output_details = interpreter.get_output_details() # 核心:动态模型必须先指定实际输入尺寸,再分配张量 INPUT_SHAPE = (320, 320) interpreter.resize_tensor_input( input_details[0]['index'], (1, INPUT_SHAPE[0], INPUT_SHAPE[1], 3) ) interpreter.allocate_tensors() # 图像读取与预处理 img = Image.open('table.jpeg').resize(INPUT_SHAPE) # 修正预处理赋值错误,确保像素值归一化到[-1, 1]区间 input_data = (np.float32(img) - 127.5) / 127.5 input_data = np.expand_dims(input_data, axis=0).astype(np.float32) # 推理执行 interpreter.set_tensor(input_details[0]['index'], input_data) interpreter.invoke() # 读取检测结果 detection_boxes = interpreter.get_tensor(output_details[0]['index']) detection_classes = interpreter.get_tensor(output_details[1]['index']) detection_scores = interpreter.get_tensor(output_details[2]['index']) num_detections = interpreter.get_tensor(output_details[3]['index'])
注意事项
- 输入属性中
shape_signature里的-1标记代表对应维度为动态可变维度,这类动态shape模型不会自动适配传入的张量尺寸,必须手动调用resize接口声明实际使用的维度值,否则会始终以模型内置的默认初始shape做输入校验。 - 如果后续需要切换其他输入分辨率(比如416416、640640),只需要修改
INPUT_SHAPE参数即可,不需要重新转换模型。
内容的提问来源于stack exchange,提问作者yzhuad
相关产品推荐
相关产品推荐

