コンテンツにスキップ

Raspberry PiでのIoTデプロイ

Raspberry PiでのONNX Runtime IoTデプロイ

Section titled “Raspberry PiでのONNX Runtime IoTデプロイ”

ONNX RuntimeとRaspberry Piを使用してエッジで画像分類を実行し、デバイスのカメラから入力を受け取り、分類結果をターミナルに送信する方法を学びます。

Raspberry Piを構成したことがない場合は、Raspberry Piドキュメントを参照してデバイスをセットアップしてください。

エッジデバイスにモデルをデプロイすることには多くの利点とユースケースがあります。IoTチュートリアルのホームページのリストを確認してください。

Raspberry Piとカメラの画像。
  • Raspberry Pi 3 Bボード
  • Raspberry Pi ImagerのDebianでイメージングされたSDカード
  • Raspberry Pi カメラモジュールまたはその他の互換性のあるカメラ。
  • リモートアクセス用のVNC Viewer。オプションで、ボードをモニターに接続することもできます。
  • このチュートリアルでは、Raspberry Piのイメージングとセットアップについては説明しません。Raspberry PiでPythonを使用して構成およびプログラミングする方法の基本的な理解が期待されます。

ソースコード、MLモデルのダウンロード、パッケージのインストール

Section titled “ソースコード、MLモデルのダウンロード、パッケージのインストール”

Raspberry Piをイメージングし、使用できるように構成したら、デバイスに接続してソースコードをダウンロードします。

  • Raspberry Piデバイスに接続します

このチュートリアルでは、VNC Viewerを使用してリモートで接続します。VNC Viewerを使用する場合は、これらのセットアップ手順に従って接続を確立してください。 Raspberry PiでVNCを有効にし、コンピューターにVNC Viewerアプリをダウンロードしたら、デバイスにリモートで接続できます。

VNC Viewerの画像
  • Raspberry Piにソースをダウンロードします。ソースコードには、モデルズーmobilenet ONNXモデルやimagenet_classes.txtクラスなど、推論の実行に必要なものがすべて含まれています。

    Terminal window
    git clone https://github.com/cassiebreviu/onnxruntime-raspberrypi.git
  • onnxruntime-raspberrypiのダウンロード場所に移動し、次のコマンドでrequirements.txtからパッケージをインストールします。

    Terminal window
    cd onnxruntime-raspberrypi
    pip install -r requirements.txt

このチュートリアルでは、Raspberry Pi カメラモジュールを使用しています。提供されているcameratest.pyスクリプトでカメラをテストします。カメラの動作に問題がある場合は、sudo apt update sudo apt upgradeを実行してボードとファームウェアを更新してください。

  • 以下のコマンドを実行してカメラを構成およびテストします。これにより、現在のディレクトリにtest.jpgという名前の画像キャプチャが作成され、カメラ出力のライブビデオストリームが開きます。ライブビデオ出力をキャンセルするにはESCキーを押します。

    Terminal window
    python cameratest.py
  • 参考までに、cameratest.pyスクリプトを以下に示します。

    import numpy as np
    import cv2
    # opencvを使用してテスト画像を作成します。
    cap = cv2.VideoCapture(0)
    cap.set(3,640) # 幅を設定
    cap.set(4,480) # 高さを設定
    ret, frame = cap.read()
    frame = cv2.flip(frame, -1) # カメラを垂直に反転
    cv2.imwrite('test.jpg', frame)
    # `ESC`キーを押して終了するまでライブビデオフィードを開始します。
    while(True):
    ret, frame = cap.read()
    frame = cv2.flip(frame, -1) # カメラを垂直に反転
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    cv2.imshow('frame', frame)
    cv2.imshow('gray', gray)
    k = cv2.waitKey(30) & 0xff
    if k == 27: # 'ESC'を押して終了
    break
    cap.release()
    cv2.destroyAllWindows()

inference_mobilenet.pyスクリプトを使用してRaspberry Piで推論を実行する

Section titled “inference_mobilenet.pyスクリプトを使用してRaspberry Piで推論を実行する”

カメラが接続され、Raspberry Piで動作していることを確認したので、ソースで提供されているONNXモデルを推論します。モデルは、1000クラスの画像分類を実行するMobileNetモデルです。

  • 以下のコマンドで推論スクリプトを実行します。

    python inference_mobilenet.py
  • ターミナル出力:

    VNC Viewerの画像
  • Raspberry Piで推論された画像:

    VNC Viewerの画像
  • 参考までに、inference_mobilenet.pyスクリプトを以下に示します。

    # パッケージをインポートします。
    from PIL import Image
    import numpy as np
    import onnxruntime
    import torch
    import cv2
    def preprocess_image(image_path, height, width, channels=3):
    image = Image.open(image_path)
    image = image.resize((width, height), Image.LANCZOS)
    image_data = np.asarray(image).astype(np.float32)
    image_data = image_data.transpose([2, 0, 1]) # CHWに転置
    mean = np.array([0.079, 0.05, 0]) + 0.406
    std = np.array([0.005, 0, 0.001]) + 0.224
    for channel in range(image_data.shape[0]):
    image_data[channel, :, :] = (image_data[channel, :, :] / 255 - mean[channel]) / std[channel]
    image_data = np.expand_dims(image_data, 0)
    return image_data
    def softmax(x):
    """xの各スコアセットのsoftmax値を計算します。"""
    e_x = np.exp(x - np.max(x))
    return e_x / e_x.sum()
    def run_sample(session, image_file, categories):
    output = session.run([], {'input':preprocess_image(image_file, 224, 224)})[0]
    output = output.flatten()
    output = softmax(output) # これはオプションです
    top5_catid = np.argsort(-output)[:5]
    for catid in top5_catid:
    print(categories[catid], output[catid])
    # 結果をファイルに書き込みます。
    with open("result.txt", "w") as f:
    for catid in top5_catid:
    f.write(categories[catid] + " " + str(output[catid]) + " \r")
    # 推論を実行するためのメイン関数を作成します。
    if __name__ == "__main__":
    # クラスファイルからカテゴリを読み取ります。
    with open("imagenet_classes.txt", "r") as f:
    categories = [s.strip() for s in f.readlines()]
    # 推論セッションを作成します
    session = onnxruntime.InferenceSession("mobilenet_v2_float.onnx")
    # カメラから画像を取得します。
    cap = cv2.VideoCapture(0)
    cap.set(3,640) # 幅を設定
    cap.set(4,480) # 高さを設定
    ret, frame = cap.read()
    frame = cv2.flip(frame, -1) # カメラを垂直に反転
    cv2.imwrite('capture.jpg', frame)
    cap.release()
    cv2.destroyAllWindows()
    # 推論を実行します
    run_sample(session, 'capture.jpg', categories)

Raspberry Piで推論を正常に実行したので、同じコードを使用して、ONNX Runtimeをサポートする任意のデバイスで推論を実行できます。また、同じコードを使用して、別のモデルでRaspberry Piで推論を実行することもできます。ONNXモデルズーの他のモデルを確認してください。