如何加载tflite模型并通过单张图片完成推理测试
单张图片测试TFLite跌倒检测模型实现步骤
- 首先安装依赖库:
常规PC端测试直接安装全量依赖:pip install tensorflow opencv-python numpy
边缘端轻量化测试可安装tflite-runtime替代全量TensorFlow。
实现代码
1. 导入依赖
import cv2 import numpy as np import tensorflow as tf # 若使用tflite-runtime,替换上方import语句为: # import tflite_runtime.interpreter as tflite
2. 加载模型与标签
提前确认你导出的文件包含:模型文件xxx.tflite、标签文件labels.txt(标签顺序和训练时输出的类别顺序完全一致,一般为未跌倒、跌倒两类)
# 加载TFLite模型并分配张量 interpreter = tf.lite.Interpreter(model_path="替换为你的tflite模型路径") interpreter.allocate_tensors() # 自动读取模型输入输出参数,无需手动填写输入尺寸 input_details = interpreter.get_input_details() output_details = interpreter.get_output_details() input_height = input_details[0]['shape'][1] input_width = input_details[0]['shape'][2] # 加载标签列表 with open("替换为你的labels.txt路径", "r") as f: labels = [line.strip() for line in f.readlines()]
3. 预处理单张测试图片
预处理逻辑必须和训练时保持完全一致,否则会出现结果偏差
# 读取测试图片 img = cv2.imread("替换为你的单张测试图片路径") # OpenCV默认读取格式为BGR,需转为模型训练使用的RGB格式 img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # 调整尺寸匹配模型输入要求 img_resized = cv2.resize(img_rgb, (input_width, input_height)) # 按模型输入类型做归一化处理 input_dtype = input_details[0]['dtype'] if input_dtype == np.float32: # 浮点模型默认归一化到0~1区间,和TFLite Model Maker训练逻辑对齐 input_data = np.expand_dims(img_resized / 255.0, axis=0).astype(input_dtype) else: # 量化模型为uint8输入,无需归一化 input_data = np.expand_dims(img_resized, axis=0).astype(input_dtype)
4. 执行推理并输出结果
# 输入数据并运行推理 interpreter.set_tensor(input_details[0]['index'], input_data) interpreter.invoke() # 解析输出结果 output_data = interpreter.get_tensor(output_details[0]['index'])[0] max_conf_idx = np.argmax(output_data) print(f"预测类别:{labels[max_conf_idx]},置信度:{output_data[max_conf_idx]:.2f}")
注意事项
- 上述代码适配整图分类场景(即单张图仅判断整体是否存在跌倒情况),如果你训练的是目标检测模型,输出解析逻辑需要调整,按检测框的输出格式解析坐标、类别和置信度即可。
- 如果测试结果偏差较大,优先排查三个点:是否做了BGR转RGB、resize尺寸是否匹配模型要求、归一化逻辑是否和训练时对齐。
内容的提问来源于stack exchange,提问作者Mayank Babariya
相关产品推荐
相关产品推荐

