MediaPipe Image Embedder タスクを使用すると、画像データを数値表現に変換して、2 つの画像の類似性の比較など、ML 関連の画像処理タスクを実行できます。次の手順では、Python で Image Embedder を使用する方法について説明します。
このタスクの機能、モデル、構成オプションの詳細については、概要をご覧ください。
サンプルコード
Image Embedder のサンプルコードには、このタスクの Python での完全な実装が記載されています。このコードは、このタスクをテストし、独自の画像埋め込みツールの作成を開始するのに役立ちます。画像埋め込みツールのサンプルコードは、Google Colab でウェブブラウザのみを使用して表示、実行、編集できます。この例のソースコードは GitHub で確認できます。
セットアップ
このセクションでは、Image Embedder を使用するように開発環境とコード プロジェクトを設定する主な手順について説明します。プラットフォーム バージョンの要件など、MediaPipe タスクを使用する開発環境の設定に関する一般的な情報については、Python の設定ガイドをご覧ください。
パッケージ
Image Embedder タスクは、mediapipe pip パッケージをタスクします。依存関係は次のようにインストールできます。
$ python -m pip install mediapipe
インポート
次のクラスをインポートして、Image Embedder タスク関数にアクセスします。
import mediapipe as mp
from mediapipe.tasks import python
from mediapipe.tasks.python import vision
モデル
MediaPipe Image Embedder タスクには、このタスクに対応したトレーニング済みモデルが必要です。Image Embedder で使用可能なトレーニング済みモデルの詳細については、タスクの概要のモデルのセクションをご覧ください。
モデルを選択してダウンロードし、ローカル ディレクトリに保存します。推奨される MobileNetV3 モデルを使用できます。
model_path = '/absolute/path/to/mobilenet_v3_small_075_224_embedder.tflite'
次のように、model_asset_path
パラメータ内にモデルのパスを指定します。
base_options = BaseOptions(model_asset_path=model_path)
タスクを作成する
タスクを作成するには、create_from_options
関数を使用します。create_from_options
関数は、埋め込みオプションを設定するための構成オプションを受け入れます。構成オプションの詳細については、構成の概要をご覧ください。
Image Embedder タスクは、静止画像、動画ファイル、ライブ動画ストリーミングの 3 つの入力データ型をサポートしています。入力データ型に対応するタブを選択して、タスクを作成し推論を実行する方法を確認します。
画像
import mediapipe as mp BaseOptions = mp.tasks.BaseOptions ImageEmbedder = mp.tasks.vision.ImageEmbedder ImageEmbedderOptions = mp.tasks.vision.ImageEmbedderOptions VisionRunningMode = mp.tasks.vision.RunningMode options = ImageEmbedderOptions( base_options=BaseOptions(model_asset_path='/path/to/model.tflite'), quantize=True, running_mode=VisionRunningMode.IMAGE) with ImageEmbedder.create_from_options(options) as embedder: # The embedder is initialized. Use it here. # ...
動画
import mediapipe as mp BaseOptions = mp.tasks.BaseOptions ImageEmbedder = mp.tasks.vision.ImageEmbedder ImageEmbedderOptions = mp.tasks.vision.ImageEmbedderOptions VisionRunningMode = mp.tasks.vision.RunningMode options = ImageEmbedderOptions( base_options=BaseOptions(model_asset_path='/path/to/model.tflite'), quantize=True, running_mode=VisionRunningMode.VIDEO) with ImageEmbedder.create_from_options(options) as embedder: # The embedder is initialized. Use it here. # ...
ライブ配信
import mediapipe as mp BaseOptions = mp.tasks.BaseOptions ImageEmbedderResult = mp.tasks.vision.ImageEmbedder.ImageEmbedderResult ImageEmbedder = mp.tasks.vision.ImageEmbedder ImageEmbedderOptions = mp.tasks.vision.ImageEmbedderOptions VisionRunningMode = mp.tasks.vision.RunningMode def print_result(result: ImageEmbedderResult, output_image: mp.Image, timestamp_ms: int): print('ImageEmbedderResult result: {}'.format(result)) options = ImageEmbedderOptions( base_options=BaseOptions(model_asset_path='/path/to/model.tflite'), running_mode=VisionRunningMode.LIVE_STREAM, quantize=True, result_callback=print_result) with ImageEmbedder.create_from_options(options) as embedder: # The embedder is initialized. Use it here. # ...
設定オプション
このタスクには、Python アプリケーション用の次の構成オプションがあります。
オプション名 | 説明 | 値の範囲 | デフォルト値 |
---|---|---|---|
running_mode |
タスクの実行モードを設定します。モードは次の 3 つです。 IMAGE: 単一画像入力のモード。 動画: 動画のデコードされたフレームのモード。 LIVE_STREAM: カメラなどからの入力データのライブ配信モード。このモードでは、resultListener を呼び出して、結果を非同期で受信するリスナーを設定する必要があります。 |
{IMAGE, VIDEO, LIVE_STREAM } |
IMAGE |
l2_normalize |
返された特徴ベクトルを L2 ノルムで正規化するかどうか。このオプションは、モデルにネイティブの L2_NORMALIZATION TFLite オペレーションがまだ含まれていない場合にのみ使用します。ほとんどの場合、すでにこの状態であるため、TFLite 推論によって L2 正規化が実現され、このオプションは必要ありません。 | Boolean |
False |
quantize |
返されたエンベディングをスカラー量子化でバイトに量子化するかどうか。エンベディングは暗黙的に単位正規化されていると見なされるため、すべてのディメンションの値は [-1.0、1.0] の範囲内にあることが保証されます。そうでない場合は、l2_normalize オプションを使用します。 | Boolean |
False |
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 Embedder API は、入力画像またはフレームのエンベディング ベクトルを返します。
画像
# Perform image embedding on the provided single image. embedding_result = embedder.embed(mp_image)
動画
# Calculate the timestamp of the current frame frame_timestamp_ms = 1000 * frame_index / video_file_fps # Perform image embedding on the video frame. embedding_result = embedder.embed_for_video(mp_image, frame_timestamp_ms)
ライブ配信
# Send the latest frame to perform image embedding. # Results are sent to the `result_callback` provided in the `ImageEmbedderOptions`. embedder.embed_async(mp_image, frame_timestamp_ms)
次の点にご注意ください。
- 動画モードまたはライブ配信モードで実行する場合は、Image Embedder タスクに入力フレームのタイムスタンプも指定する必要があります。
- 画像モデルまたは動画モデルで実行する場合、Image Embedder タスクは、入力画像またはフレームの処理が完了するまで現在のスレッドをブロックします。
- ライブ配信モードで実行する場合、画像埋め込みタスクは現在のスレッドをブロックせず、すぐに返されます。入力フレームの処理が完了するたびに、エンベディング結果を使用して結果リスナーが呼び出されます。Image Embedder タスクが別のフレームの処理でビジー状態になっているときに
embedAsync
関数が呼び出されると、タスクは新しい入力フレームを無視します。
結果を処理して表示する
推論を実行すると、Image Embedder タスクは、入力画像またはフレーム内のオブジェクトの候補カテゴリのリストを含む ImageEmbedderResult
オブジェクトを返します。
このタスクの出力データの例を次に示します。
ImageEmbedderResult:
Embedding #0 (sole embedding head):
float_embedding: {0.0, 0.0, ..., 0.0, 1.0, 0.0, 0.0, 2.0}
head_index: 0
この結果は、次の画像をエンベディングすることで得られました。
2 つのエンベディングの類似性を比較するには、ImageEmbedder.cosine_similarity
関数を使用します。例については、次のコードをご覧ください。
# Compute cosine similarity.
similarity = ImageEmbedder.cosine_similarity(
embedding_result.embeddings[0],
other_embedding_result.embeddings[0])