TensorFlow Lite(2026 年已改名 LiteRT)是 TensorFlow 的【精简推理版】——把训练好模型里只剩【跑】这一件事,装进一个约 5MB 的运行时里,专为树莓派这类小设备而生;本节用官方预训练的 detect.tflite 认 COCO 80 类,输入输出全靠手搓张量——这是本课第一个【不套封装】、直接面对模型裸接口的实验。
11-5 的 YOLO 是【ultralytics 包全托管】;本节的 LiteRT 反过来——加载、填输入、调用、读输出四步全要自己写。为什么还要学?因为 MediaPipe/CVZone/ultralytics 内部全是这套四步舞的变体;学会了裸接口,以后碰到任何【给个 .tflite 就要部署】的场景(Edge TPU 加速棒、嵌入式板)都不慌。上一节的 CVZone 是【积木】,本节是【乐高说明书】。
一、先改名字:TensorFlow Lite 现在叫 LiteRT
Google 把 TensorFlow Lite 升格为独立项目并改名 LiteRT(2024 年起的官方动作)。对用户的实际影响:
- 老名字还活着:
tflite-runtime这个 pip 包照常能装能用,网上教程写 TensorFlow Lite 也都不算错 - 新包叫
ai-edge-litert:官方建议的新装法,from ai_edge_litert.interpreter import Interpreter——导入路径换了,其余 API 一模一样 - 模型文件不变:还是
.tflite后缀,老模型直接能跑
本课取态:树莓派上用最省事的 tflite-runtime(老名字、文档最多、和教程一致),但要知道它就是 LiteRT——看到新资料写 LiteRT 不会懵。
二、只装引擎,不装工厂
完整 TensorFlow 包 500MB+(训练、建图、优化器全在里面),树莓派上用不上——我们只推理:
cd ~/ai && source venv/bin/activate
pip install tflite-runtime # 约 5MB,只有 Interpreter 一个核心类
pip install opencv-python numpy pillow
pip install tensorflow装到天亮:老教程让人在 Pi 上装完整版——PyTorch 上 GB 的教训(11-5)在这重演且更大,树莓派推理永远只装 runtime。- apt 包
python3-tflite-runtime已停更(停在 TF 2.5)——别再走 apt,进 venv 用 pip。 - 32 位系统的 wheel 找不到:pip 装不上时先确认系统是 64 位(
uname -m出aarch64)。
三、Interpreter 四步舞(裸接口的核心)
所有 .tflite 推理都是同一套四步,背下来比背语法重要:
# ① 载模型 → ② 分配张量 → ③ 填输入、invoke → ④ 读输出
interpreter = Interpreter(model_path="detect.tflite") # ①
interpreter.allocate_tensors() # ②
interpreter.set_tensor(input_index, input_data) # ③ 填
interpreter.invoke() # 跑
output = interpreter.get_tensor(output_index) # ④ 读
输入输出长什么样?问模型自己——get_input_details() / get_output_details() 返回张量的形状、类型、量化参数,每次拿到陌生模型,第一件事就是打印这两个。
四、动手 Demo:detect.tflite 单图推理
官方预训练检测模型(MobileNet SSD 量化版,认 COCO 80 类):
wget https://storage.googleapis.com/download.tensorflow.org/models/tflite/coco_ssd_mobilenet_v1_1.0_quant_2018_06_29.zip
unzip coco_ssd_mobilenet_v1_1.0_quant_2018_06_29.zip
# 解出 detect.tflite 与 coco_labels.txt
# demo12_3_tflite.py —— 裸接口四步舞+结果解析
import numpy as np, cv2
from tflite_runtime.interpreter import Interpreter
interpreter = Interpreter(model_path="detect.tflite")
interpreter.allocate_tensors()
inp = interpreter.get_input_details()[0]
_, ih, iw, _ = inp["shape"] # 输入固定 300x300x3
img = cv2.imread("test.jpg") # 换成任意照片
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
small = cv2.resize(img_rgb, (iw, ih))
data = np.expand_dims(small, axis=0).astype(inp["dtype"]) # 补批次维
interpreter.set_tensor(inp["index"], data)
interpreter.invoke()
boxes = interpreter.get_tensor(interpreter.get_output_details()[0]["index"])[0]
classes = interpreter.get_tensor(interpreter.get_output_details()[1]["index"])[0]
scores = interpreter.get_tensor(interpreter.get_output_details()[2]["index"])[0]
labels = [l.strip() for l in open("coco_labels.txt", encoding="utf-8")]
for i in range(3): # 置信度前三名
if scores[i] > 0.5:
name = labels[int(classes[i]) + 1] # 第 0 行是背景,整体 +1
print(f"{name}: {scores[i]:.2f}")
看到什么算成功(对着一张有狗和沙发的照片):
dog: 0.87
couch: 0.72
potted plant: 0.35
读结果:三个输出张量是平行数组——第 i 个框对应第 i 个类别与第 i 个分数;boxes 是归一化的 [ymin, xmin, ymax, xmax](注意y 在前,11-3 数组的【行在前】是同一件事)。量化模型的 scores 若是 uint8,先除以 255 恢复 0~1(用 get_output_details() 里的 dtype 判断)。Pi 5 上这一帧推理约 35ms,Pi 4 约需 3~4 倍时间。
五、30 秒实验:先问模型要【身份证】
把 Demo 的推理部分先注释掉,只留前两步,追加:
print("输入:", inp["shape"], inp["dtype"])
print("量化:", inp["quantization"])
for od in interpreter.get_output_details():
print("输出:", od["shape"], od["dtype"], od["name"])
看到什么算成功:输入 (1, 300, 300, 3) uint8(1 是批次维);四个输出张量的名字分别是 boxes/classes/scores/num_detections。这一招是万能钥匙:以后拿到任何陌生 .tflite(哪怕是别人手写的模型),先打印身份证再写代码,永远比照抄教程靠谱。
六、常见误区
- 把【TensorFlow Lite】和【TensorFlow】当两个东西学——前者是后者的精简部署版,模型由后者导出;树莓派上永远只需要前者(现在叫 LiteRT)。
- 输入尺寸想当然——这个模型必须 300×300×3,喂 640×480 不报错但结果全错(框架按 shape 静默对不上);resize 是必做步骤,不是可选项。
- 标签序号忘了 +1——
coco_labels.txt第 0 行是【背景】占位,classes从 0 开始却对应第 1 行的 person;少加 1 会导致【狗被标成猫】这类灵异现象。 - 量化模型按浮点直接读——uint8 输出的分数要先按量化参数(简单版:除 255)还原,不还原也能排序,但打印出来会是 221 这种【置信度 221】笑话。
自测三问(点开对答案)
1. TensorFlow Lite 的新名字是什么?为什么树莓派只装 runtime?——LiteRT;因为只做推理不需要训练组件,runtime 约 5MB 对比完整版 500MB+。 2. 裸接口四步舞是哪四步?——载模型 → allocate_tensors → set_tensor+invoke → get_tensor。 3. detect.tflite 的输出为什么是三个平行数组?——每个检测结果各占一个下标:boxes 第 i 项、classes 第 i 项、scores 第 i 项描述同一个目标。- ☐ 下一节(12-4 AI 实验范例:识别剪刀、石头和布的手势)
相关笔记
- CVZone 计算机视觉套件 —— 上一节:封装层省事,本节下到裸接口
- AI 实验范例:OpenCV+YOLO 物体识别 —— 同为 COCO 80 类,YOLO 全托管 vs 本节裸接口
- OpenCV 的基本使用 —— resize/BGR 转 RGB/y 在前:本节全部预处理的出处
- 🍓 树莓派 · 索引 —— 全课路线图