Python 用オブジェクト検出ガイド

MediaPipe オブジェクト検出タスクを使用すると、複数のクラスのオブジェクトの存在と位置を検出できます。ここでは、Python でオブジェクト検出タスクを使用する方法について説明します。この手順で説明されているコードサンプルは、GitHub で入手できます。

このタスクの実際の動作は、ウェブデモでご覧いただけます。このタスクの機能、モデル、構成オプションの詳細については、概要をご覧ください。

サンプルコード

Object Detector のサンプルコードでは、参考までにこのタスクの完全な実装を Python で提供しています。このコードは、このタスクをテストし、独自のテキスト分類アプリの作成を開始するのに役立ちます。ウェブブラウザだけで、オブジェクト検出ツールのサンプルコードを表示、実行、編集できます。

Raspberry Pi 用のオブジェクト検出機能を実装する場合は、Raspberry Pi サンプルアプリをご覧ください。

セットアップ

このセクションでは、オブジェクト検出機能を使用するように開発環境とコード プロジェクトを設定する際の主な手順について説明します。プラットフォームのバージョン要件など、MediaPipe タスクを使用するための開発環境の設定に関する一般的な情報については、Python の設定ガイドをご覧ください。

パッケージ

オブジェクト検出タスクには mediapipe pip パッケージが必要です。必要なパッケージは、次のコマンドを使用してインストールできます。

$ python -m pip install mediapipe

インポート

Object Detector のタスク関数にアクセスするには、次のクラスをインポートします。

import mediapipe as mp
from mediapipe.tasks import python
from mediapipe.tasks.python import vision

モデル

MediaPipe オブジェクト検出タスクには、このタスクと互換性のあるトレーニング済みモデルが必要です。Object Detector で利用可能なトレーニング済みモデルの詳細については、タスクの概要のモデル セクションをご覧ください。

モデルを選択してダウンロードし、ローカル ディレクトリに保存します。

model_path = '/absolute/path/to/lite-model_efficientdet_lite0_detection_metadata_1.tflite'

BaseOptions オブジェクトの model_asset_path パラメータを使用して、使用するモデルのパスを指定します。コード例については、次のセクションをご覧ください。

タスクを作成する

create_from_options 関数を使用してタスクを作成します。create_from_options 関数は、実行モード、表示名のロケール、最大結果数、信頼度のしきい値、カテゴリの許可リスト、拒否リストなどの構成オプションを受け入れます。構成オプションを設定しない場合、タスクではデフォルト値が使用されます。構成オプションの詳細については、構成オプションのセクションをご覧ください。

オブジェクト検出タスクは、静止画像、動画ファイル、ライブ動画ストリームなど、複数の入力データ型をサポートしています。入力データ型に対応するタブを選択して、タスクを作成して推論を実行する方法を確認します。

画像

import mediapipe as mp

BaseOptions = mp.tasks.BaseOptions
ObjectDetector = mp.tasks.vision.ObjectDetector
ObjectDetectorOptions = mp.tasks.vision.ObjectDetectorOptions
VisionRunningMode = mp.tasks.vision.RunningMode

options = ObjectDetectorOptions(
    base_options=BaseOptions(model_asset_path='/path/to/model.tflite'),
    max_results=5,
    running_mode=VisionRunningMode.IMAGE)

with ObjectDetector.create_from_options(options) as detector:
  # The detector is initialized. Use it here.
  # ...
    

動画

import mediapipe as mp

BaseOptions = mp.tasks.BaseOptions
ObjectDetector = mp.tasks.vision.ObjectDetector
ObjectDetectorOptions = mp.tasks.vision.ObjectDetectorOptions
VisionRunningMode = mp.tasks.vision.RunningMode

options = ObjectDetectorOptions(
    base_options=BaseOptions(model_asset_path='/path/to/model.tflite'),
    max_results=5,
    running_mode=VisionRunningMode.VIDEO)

with ObjectDetector.create_from_options(options) as detector:
  # The detector is initialized. Use it here.
  # ...
    

ライブ配信

import mediapipe as mp

BaseOptions = mp.tasks.BaseOptions
DetectionResult = mp.tasks.components.containers.detections.DetectionResult
ObjectDetector = mp.tasks.vision.ObjectDetector
ObjectDetectorOptions = mp.tasks.vision.ObjectDetectorOptions
VisionRunningMode = mp.tasks.vision.RunningMode

def print_result(result: DetectionResult, output_image: mp.Image, timestamp_ms: int):
    print('detection result: {}'.format(result))

options = ObjectDetectorOptions(
    base_options=BaseOptions(model_asset_path='/path/to/model.tflite'),
    running_mode=VisionRunningMode.LIVE_STREAM,
    max_results=5,
    result_callback=print_result)

with ObjectDetector.create_from_options(options) as detector:
  # The detector is initialized. Use it here.
  # ...
    

画像で使用する Object Detector の作成の詳細な例については、コードサンプルをご覧ください。

構成オプション

このタスクには、Python アプリケーション用に次の構成オプションがあります。

オプション名 説明 値の範囲 デフォルト値
running_mode タスクの実行モードを設定します。モードは 3 つあります。

IMAGE: 単一の画像入力のモード。

VIDEO: 動画のデコードされたフレームのモード。

LIVE_STREAM: カメラからのデータなど、入力データのライブストリームのモード。このモードでは、resultListener を呼び出して、結果を非同期で受け取るリスナーをセットアップする必要があります。
{IMAGE, VIDEO, LIVE_STREAM} IMAGE
display_names タスクのモデルのメタデータで提供される表示名に使用するラベルの言語を設定します(利用可能な場合)。英語の場合、デフォルトは en です。TensorFlow Lite Metadata Writer API を使用して、カスタムモデルのメタデータにローカライズされたラベルを追加できます。 言語 / 地域コード en
max_results 返されるトップスコアの検出結果の最大数を設定します(省略可)。 任意の正の数 -1(すべての結果が返されます)
score_threshold モデル メタデータ(存在する場合)で指定された値をオーバーライドする予測スコアのしきい値を設定します。この値を下回る結果は拒否されます。 任意の浮動小数点数 未設定
category_allowlist 許可されるカテゴリ名のオプション リストを設定します。空でない場合、カテゴリ名がこのセットにない検出結果は除外されます。重複するカテゴリ名や不明なカテゴリ名は無視されます。 このオプションは category_denylist と相互に排他的であり、両方を使用するとエラーが発生します。 任意の文字列 未設定
category_denylist 使用できないカテゴリ名のオプション リストを設定します。空でない場合、カテゴリ名がこのセットに含まれる検出結果は除外されます。重複するカテゴリ名や不明なカテゴリ名は無視されます。このオプションは category_allowlist と相互に排他的であり、両方を使用するとエラーになります。 任意の文字列 未設定

データの準備

入力を画像ファイルまたは 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)
    

タスクを実行する

検出関数の 1 つを呼び出して、推論をトリガーできます。オブジェクト検出タスクは、入力画像またはフレーム内で検出されたオブジェクトを返します。

画像

# Perform object detection on the provided single image.
detection_result = detector.detect(mp_image)
    

動画

# Calculate the timestamp of the current frame
frame_timestamp_ms = 1000 * frame_index / video_file_fps

# Perform object detection on the video frame.
detection_result = detector.detect_for_video(mp_image, frame_timestamp_ms)
    

ライブ配信


# Send the latest frame to perform object detection.
# Results are sent to the `result_callback` provided in the `ObjectDetectorOptions`.
detector.detect_async(mp_image, frame_timestamp_ms)
    

画像に対してオブジェクト検出機能を実行する詳細な例については、コードサンプルをご覧ください。

次の点にご留意ください。

  • 動画モードまたはライブ ストリーム モードで実行する場合は、オブジェクト検出タスクに入力フレームのタイムスタンプも指定する必要があります。
  • 画像モデルまたは動画モデルで実行されている場合、オブジェクト検出タスクは入力画像または入力フレームの処理を完了するまで現在のスレッドをブロックします。
  • ライブ ストリーム モードで実行する場合、オブジェクト検出タスクは現在のスレッドをブロックせず、すぐに結果を返します。入力フレームの処理が完了するたびに、検出結果とともに結果リスナーを呼び出します。オブジェクト検出タスクが別のフレームの処理でビジー状態のときに検出関数が呼び出された場合、新しい入力フレームは無視されます。

結果を処理して表示する

推論を実行すると、オブジェクト検出タスクは、入力画像で検出されたオブジェクトを記述する ObjectDetectionResult オブジェクトを返します。

このタスクからの出力データの例を次に示します。

ObjectDetectorResult:
 Detection #0:
  Box: (x: 355, y: 133, w: 190, h: 206)
  Categories:
   index       : 17
   score       : 0.73828
   class name  : dog
 Detection #1:
  Box: (x: 103, y: 15, w: 138, h: 369)
  Categories:
   index       : 17
   score       : 0.73047
   class name  : dog

次の図は、タスク出力を可視化したものです。

オブジェクト検出サンプルコードは、タスクから返された検出結果を表示する方法を示しています。詳細については、コードサンプルをご覧ください。