Raspberry Piで TensorFlow Liteを動かす方法をご紹介します。
対象環境
- Raspberry Pi 4 (他モデルでも問題なし)
- Raspberry Pi OS Bookworm(最新版)
- 64bit OS
- インターネット接続環境
- ターミナル操作ができること(SSH または HDMI 接続)
- Raspberry Piのセットアップが完了していること
手順の全体像
- 必要パッケージのインストール
- 仮想環境の準備
- サンプルモデルを取得(MobileNet v1 量子化版)
- 画像1枚で動作確認(推論)
- まとめ
1. 必要パッケージのインストール
sudo apt update
sudo apt install -y python3-pip python3-venv python3-numpy wget unzip
2. 仮想環境の準備
python3 -m venv ~/tflite-venv
source ~/tflite-venv/bin/activate
pip install -U pip setuptools wheel
追加パッケージのインストール
pip install pillow
pip install "numpy==1.26.4"
pip install --no-cache-dir https://github.com/PINTO0309/TensorflowLite-bin/releases/download/v2.16.1/tflite_runtime-2.16.1-cp311-none-linux_aarch64.whl
3. サンプルモデルを取得(MobileNet v1 量子化版)
mkdir -p ~/tflite_sample && cd ~/tflite_sample
curl -L -o mobilenet_v1_1.0_224_quant.tflite https://github.com/tflite-soc/tensorflow-models/raw/master/mobilenet-v1/mobilenet_v1_1.0_224_quant.tflite
wget -O labels.txt https://storage.googleapis.com/download.tensorflow.org/data/imagenet_class_index.json
4. 画像1枚で動作確認(推論)
任意の画像 image.jpg を用意してください(無ければサンプル画像をDL)。
wget -O image.jpg https://storage.googleapis.com/download.tensorflow.org/example_images/grace_hopper.jpg
プログラムを用意します。run_once.py
# run_once.py
import numpy as np
from PIL import Image
from tflite_runtime.interpreter import Interpreter
MODEL="mobilenet_v1_1.0_224_quant.tflite"
IMG="image.jpg"
# 画像読み込み&前処理
img = Image.open(IMG).convert("RGB").resize((224,224))
x = np.asarray(img, dtype=np.uint8) # INT8量子化モデルは uint8 入力
x = np.expand_dims(x, 0)
# Interpreter 準備
interpreter = Interpreter(model_path=MODEL, num_threads=4)
interpreter.allocate_tensors()
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
# 入力テンソルへコピー
interpreter.set_tensor(input_details[0]['index'], x)
# 実行
interpreter.invoke()
# 出力取得&上位5件を表示
y = interpreter.get_tensor(output_details[0]['index']).squeeze()
top5 = y.argsort()[-5:][::-1]
print("TOP-5 indices:", top5)
print("scores:", y[top5])
保存して実行します。
python3 run_once.py
INFO: Created TensorFlow Lite XNNPACK delegate for CPU.
TOP-5 indices: [653 907 466 458 668]
scores: [225 10 3 2 2]
5. まとめ
Raspberry PiでTensorFlow Liteを動かすことができました。
よろしければ、いいね、ストック、コメントいただけますと幸いです。