MediaPipe 画像分類タスクを使用すると、画像の分類を実行できます。このタスクを使用して、トレーニング時に定義された一連のカテゴリの中から画像が何を表しているかを特定できます。以下では、Python で画像分類器を使用する方法について説明します。
このタスクの実例は、ウェブデモで確認できます。このタスクの機能、モデル、構成オプションの詳細については、概要をご覧ください。
サンプルコード
画像分類器のサンプルコードは、参考までに、このタスクの完全な実装を Python で示しています。このコードにより、このタスクをテストして、独自の画像分類器の構築を開始できます。ウェブブラウザだけで、画像分類器のサンプルコードを表示、実行、編集できます。
Raspberry Pi 用の画像分類器を実装する場合は、Raspberry Pi のサンプルアプリをご覧ください。
セットアップ
このセクションでは、特に画像分類器を使用するための開発環境とコード プロジェクトをセットアップするための主な手順について説明します。プラットフォーム バージョンの要件など、MediaPipe タスクを使用するための開発環境の設定に関する一般的な情報については、Python の設定ガイドをご覧ください。
パッケージ
画像分類器が mediapipe pip パッケージにタスクを実行します。この依存関係は、次のコマンドでインストールできます。
$ python -m pip install mediapipe
``` ### Imports
Import the following classes to access the Image Classifier task functions:
```python
import mediapipe as mp
from mediapipe.tasks import python
from mediapipe.tasks.python import vision
モデル
MediaPipe 画像分類タスクには、このタスクと互換性のあるトレーニング済みモデルが必要です。画像分類器で使用可能なトレーニング済みモデルの詳細については、タスクの概要のモデル セクションをご覧ください。
モデルを選択してダウンロードし、ローカル ディレクトリに保存します。推奨される EfficientNet-Lite0 モデルを使用できます。
model_path = '/absolute/path/to/efficientnet_lite0_int8_2.tflite'
次に示すように、Model Name パラメータ内にモデルのパスを指定します。
base_options = BaseOptions(model_asset_path=model_path)
タスクを作成する
create_from_options
関数を使用してタスクを作成します。create_from_options
関数は、実行モード、表示名のロケール、結果の最大数、信頼しきい値、カテゴリの許可リスト、拒否リストなどの構成オプションを受け入れます。構成オプションの詳細については、構成の概要をご覧ください。
画像分類タスクは、静止画像、動画ファイル、ライブ動画ストリームの 3 つの入力データタイプをサポートします。入力データ型に対応するタブを選択して、タスクを作成して推論を実行する方法を確認します。
画像
import mediapipe as mp BaseOptions = mp.tasks.BaseOptions ImageClassifier = mp.tasks.vision.ImageClassifier ImageClassifierOptions = mp.tasks.vision.ImageClassifierOptions VisionRunningMode = mp.tasks.vision.RunningMode options = ImageClassifierOptions( base_options=BaseOptions(model_asset_path='/path/to/model.tflite'), max_results=5, running_mode=VisionRunningMode.IMAGE) with ImageClassifier.create_from_options(options) as classifier: # The classifier is initialized. Use it here. # ...
動画
import mediapipe as mp BaseOptions = mp.tasks.BaseOptions ImageClassifier = mp.tasks.vision.ImageClassifier ImageClassifierOptions = mp.tasks.vision.ImageClassifierOptions VisionRunningMode = mp.tasks.vision.RunningMode options = ImageClassifierOptions( base_options=BaseOptions(model_asset_path='/path/to/model.tflite'), max_results=5, running_mode=VisionRunningMode.VIDEO) with ImageClassifier.create_from_options(options) as classifier: # The classifier is initialized. Use it here. # ...
ライブ配信
import mediapipe as mp BaseOptions = mp.tasks.BaseOptions ImageClassifierResult = mp.tasks.vision.ImageClassifier.ImageClassifierResult ImageClassifier = mp.tasks.vision.ImageClassifier ImageClassifierOptions = mp.tasks.vision.ImageClassifierOptions VisionRunningMode = mp.tasks.vision.RunningMode def print_result(result: ImageClassifierResult, output_image: mp.Image, timestamp_ms: int): print('ImageClassifierResult result: {}'.format(result)) options = ImageClassifierOptions( base_options=BaseOptions(model_asset_path='/path/to/model.tflite'), running_mode=VisionRunningMode.LIVE_STREAM, max_results=5, result_callback=print_result) with ImageClassifier.create_from_options(options) as classifier: # The classifier is initialized. Use it here. # ...
画像で使用する画像分類器の作成の詳細な例については、コード例をご覧ください。
構成オプション
このタスクには、Python アプリケーション用の次の構成オプションがあります。
オプション名 | 説明 | 値の範囲 | デフォルト値 |
---|---|---|---|
running_mode |
タスクの実行モードを設定します。モードには次の 3 つがあります。 IMAGE: 単一画像入力のモード。 VIDEO: 動画のデコードされたフレームのモード。 LIVE_STREAM: カメラなどの入力データのライブ ストリームのモード。このモードでは resultListener を呼び出して、結果を非同期で受け取るリスナーをセットアップする必要があります。 |
{IMAGE, VIDEO, LIVE_STREAM } |
IMAGE |
display_names_locale |
タスクのモデルのメタデータに指定された表示名に使用するラベルの言語を設定します(使用可能な場合)。英語の場合、デフォルトは en です。TensorFlow Lite Metadata Writer API を使用して、カスタムモデルのメタデータにローカライズされたラベルを追加できます。 |
言語 / 地域コード | en |
max_results |
返される上位スコアの分類結果の最大数をオプションで設定します。0 未満の場合、利用可能なすべての結果が返されます。 | 正の数 | -1 |
score_threshold |
モデル メタデータ(存在する場合)で指定された値をオーバーライドする予測スコアのしきい値を設定します。この値を下回る結果は拒否されます。 | 任意の浮動小数点数 | 未設定 |
category_allowlist |
許可するカテゴリ名のオプション リストを設定します。空でない場合、このセットにカテゴリ名がない分類結果は除外されます。重複または不明なカテゴリ名は無視されます。
このオプションは category_denylist と相互に排他的であり、両方を使用するとエラーになります。 |
任意の文字列 | 未設定 |
category_denylist |
許可されていないカテゴリ名のオプション リストを設定します。空でない場合、このセット内にカテゴリ名が含まれる分類結果は除外されます。重複または不明なカテゴリ名は無視されます。このオプションは category_allowlist と相互に排他的であり、両方を使用するとエラーになります。 |
任意の文字列 | 未設定 |
result_callback |
画像分類器がライブ ストリーム モードのときに分類結果を非同期で受信するように結果リスナーを設定します。実行モードが LIVE_STREAM に設定されている場合にのみ使用できます |
なし | 未設定 |
データの準備
入力を画像ファイルまたは numpy 配列として準備し、mediapipe.Image
オブジェクトに変換します。入力がウェブカメラからの動画ファイルやライブ ストリームの場合、OpenCV などの外部ライブラリを使用して入力フレームを numpy 配列として読み込むことができます。
次の例は、使用可能なデータ型ごとに、処理するデータを準備する方法について説明します。
画像
import mediapipe as mp # Load the input image from an image file. mp_image = mp.Image.create_from_file('/path/to/image') # Load the input image from a numpy array. mp_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=numpy_image)
動画
import mediapipe as mp # Use OpenCV’s VideoCapture to load the input video. # Load the frame rate of the video using OpenCV’s CV_CAP_PROP_FPS # You’ll need it to calculate the timestamp for each frame. # Loop through each frame in the video using VideoCapture#read() # Convert the frame received from OpenCV to a MediaPipe’s Image object. mp_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=numpy_frame_from_opencv)
ライブ配信
import mediapipe as mp # Use OpenCV’s VideoCapture to start capturing from the webcam. # Create a loop to read the latest frame from the camera using VideoCapture#read() # Convert the frame received from OpenCV to a MediaPipe’s Image object. mp_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=numpy_frame_from_opencv)
タスクを実行する
実行モードに対応する分類関数を呼び出して、推論をトリガーできます。Image Classifier API は、入力画像またはフレーム内のオブジェクトに該当するカテゴリを返します。
画像
# Perform image classification on the provided single image. classification_result = classifier.classify(mp_image)
動画
# Calculate the timestamp of the current frame frame_timestamp_ms = 1000 * frame_index / video_file_fps # Perform image classification on the video frame. classification_result = classifier.classify_for_video(mp_image, frame_timestamp_ms)
ライブ配信
# Send the latest frame to perform image classification. # Results are sent to the `result_callback` provided in the `ImageClassifierOptions`. classifier.classify_async(mp_image, frame_timestamp_ms)
次の点にご留意ください。
- 動画モードまたはライブ ストリーム モードで実行する場合は、画像分類タスクに入力フレームのタイムスタンプも指定する必要があります。
- 画像モデルまたは動画モデルで実行する場合、画像分類タスクは、入力画像またはフレームの処理が完了するまで現在のスレッドをブロックします。
- ライブ ストリーム モードで実行している場合、画像分類タスクは現在のスレッドをブロックせず、すぐに戻ります。入力フレームの処理が完了するたびに、分類結果とともに結果リスナーを呼び出します。画像分類タスクが別のフレームの処理でビジー状態になっているときに
classifyAsync
関数が呼び出されると、タスクは新しい入力フレームを無視します。
画像で使用する画像分類器の作成の詳細な例については、コード例をご覧ください。
結果の処理と表示
推論を実行すると、画像分類タスクは、入力画像またはフレーム内のオブジェクトの可能なカテゴリのリストを含む ImageClassifierResult
オブジェクトを返します。
このタスクからの出力データの例を次に示します。
ImageClassifierResult:
Classifications #0 (single classification head):
head index: 0
category #0:
category name: "/m/01bwb9"
display name: "Passer domesticus"
score: 0.91406
index: 671
category #1:
category name: "/m/01bwbt"
display name: "Passer montanus"
score: 0.00391
index: 670
この結果は、以下に対して Bird Classifier を実行することで取得されました。
画像分類器のコード例は、タスクから返された分類結果を表示する方法を示しています。詳細については、コード例をご覧ください。