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

MediaPipe Object Detector タスクを使用すると、複数のオブジェクトの存在と場所を検出できます。 オブジェクトのクラスです。ここでは、オブジェクト検出機能を使用して、 実行します。この手順で説明するコードサンプルは、 GitHub

このタスクの実例は、ウェブデモで確認できます。機能、モデル、サービスについて詳しくは、 構成オプションの詳細については、概要をご覧ください。

サンプルコード

オブジェクト検出機能のサンプルコードは、このオブジェクト検出機能の完全な実装を示しています。 タスクを示しています。このコードは、このタスクをテストして、 独自のテキスト分類アプリの構築に着手しました。特定のリソースを表示、実行、 オブジェクト検出のサンプルコードを編集します。 できます。

Raspberry Pi 用のオブジェクト検出機能を実装する場合は、 Raspberry Pi の例 アプリ

セットアップ

このセクションでは、開発環境をセットアップする主な手順と Object Detector を使用するための特別なコード プロジェクトがあります。一般的な情報については、 MediaPipe タスクを使用するための開発環境の設定 プラットフォーム バージョンの要件については、 Python のセットアップ ガイド

<ph type="x-smartling-placeholder">

パッケージ

オブジェクト検出タスクには、mediapipe pip パッケージが必要です。kubectl の「get pods」 必要なパッケージを次のコマンドで置き換えます。

$ python -m pip install mediapipe

インポート

次のクラスをインポートして、オブジェクト検出のタスク関数にアクセスします。

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.
  # ...
    

画像で使用するオブジェクト検出の作成の詳細な例については、 コードサンプルをご覧ください。

構成オプション

このタスクには、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 オブジェクトに変換します。入力が動画ファイルの場合 ライブ ストリームで配信する場合、 入力フレームを numpy として読み込むための OpenCV あります

次の例は、処理するデータを準備する方法について説明します。 各データタイプについて

画像

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

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

オブジェクト検出サンプルコードは、検出機能を表示する方法を示しています。 結果については、 コードサンプル をご覧ください。