🎯 教學目標
在 Raspberry Pi 5 上達成以下效果:
-
📷 使用 PiCamera2 擷取即時影像
-
🤖 使用 MobileNetV1 TFLite 模型進行即時分類
-
🖼️ 用 OpenCV 顯示即時影像 + 分類結果文字
🧰 安裝與準備環境
✅ 1. 安裝套件
sudo apt update
sudo apt install python3-picamera2 python3-opencv libatlas-base-dev -y
pip install tflite-runtime
✅ 2. 下載模型與標籤
# 模型(量化版,速度快) wget https://github.com/nnsuite/testcases/raw/master/DeepLearningModels/tensorflow-lite/Mobilenet_v1_1.0_224_quant/mobilenet_v1_1.0_224_quant.tflite -O model.tflite # 標籤 wget https://raw.githubusercontent.com/SNXJ/TensorFlowLiteDemo/master/app/src/main/assets/labels_mobilenet_quant_v1_224.txt -O labels.txt
🧪 執行主程式
儲存為 realtime_classify.py:
import numpy as np
import cv2
from picamera2 import Picamera2
from PIL import Image
import tflite_runtime.interpreter as tflite
import time
# 載入模型與標籤
interpreter = tflite.Interpreter(model_path="model.tflite")
interpreter.allocate_tensors()
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
with open("labels.txt", "r") as f:
labels = [line.strip() for line in f.readlines()]
# 初始化相機
picam2 = Picamera2()
picam2.preview_configuration.main.size = (640, 480)
picam2.preview_configuration.main.format = "RGB888"
picam2.start()
print("🚀 開始即時分類中... 按 q 鍵離開")
while True:
frame = picam2.capture_array()
img = cv2.resize(frame, (224, 224))
input_data = np.expand_dims(img.astype(np.uint8), axis=0)
# 推論
interpreter.set_tensor(input_details[0]['index'], input_data)
interpreter.invoke()
output_data = interpreter.get_tensor(output_details[0]['index'])
predictions = np.squeeze(output_data)
top_index = np.argmax(predictions)
label = labels[top_index]
confidence = predictions[top_index] / 255.0
# 顯示結果
text = f"{label} ({confidence:.2f})"
cv2.putText(frame, text, (10, 30),
cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
cv2.imshow("PiCamera2 - TFLite Realtime Classification", frame)
# 離開條件
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# 清理
cv2.destroyAllWindows()
picam2.stop()
▶️ 執行
cd ~/tflite_cam
python3 realtime_classify.py
-
畫面會即時顯示 PiCamera 畫面與預測結果(物品名稱 + 信心度)
-
按下
q鍵退出
💡 小技巧
| 用法 | 指令 |
|---|---|
| 改變輸入解析度 | picam2.preview_configuration.main.size = (1280, 720) |
| 使用 float 模型 | 換成 .tflite 非量化版本,但需要 float32 輸入 |
| 加速 | 選擇較小的模型或改用 Coral USB(Edge TPU) |
文章標籤
全站熱搜
