iOS 向けオブジェクト検出ガイド

オブジェクト検出タスクを使用すると、複数のオブジェクトの存在と場所を検出できます。 オブジェクトのクラスです。たとえば、オブジェクト検出機能は、 説明します。以下では、iOS でオブジェクト検出タスクを使用する方法について説明します。「 この手順で説明するコードサンプルは GitHub で入手できます。

このタスクの動作を確認するには、こちらのウェブ デモをご覧ください。対象 Google Cloud インフラストラクチャの機能、モデル、構成オプションについて 詳細については、 概要

サンプルコード

MediaPipe Tasks のサンプルコードは、オブジェクトの基本的な実装です。 iOS 用検出機能アプリ。この例では、物理的な iOS デバイスのカメラを使用して、 オブジェクトを継続的に検出し、デバイスから画像と動画を使用して 静的にオブジェクトを検出することもできます。

独自の iOS アプリの出発点としてアプリを使用することも、アプリ自体に言及することもできます。 変更する際の注意点があります。オブジェクト検出のサンプルコードは次の場所でホストされています: GitHub

コードをダウンロードする

次の手順では、サンプルのローカルコピーを作成する方法を示します。 git コマンドライン ツールを使用してコードを実行します。

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

サンプルコードをダウンロードするには:

  1. 次のコマンドを使用して Git リポジトリのクローンを作成します。

    git clone https://github.com/google-ai-edge/mediapipe-samples
    
  2. 必要に応じて、スパース チェックアウトを使用するように Git インスタンスを構成し、 Object Detector サンプルアプリのファイルのみを取得します。

    cd mediapipe
    git sparse-checkout init --cone
    git sparse-checkout set examples/object_detection/ios/
    

ローカル バージョンのサンプルコードを作成したら、 MediaPipe タスク ライブラリで、Xcode を使用してプロジェクトを開き、アプリを実行します。対象 手順については、iOS の設定ガイドをご覧ください。

主要コンポーネント

次のファイルには、オブジェクト検出のサンプルで重要なコードが含まれています。 アプリケーション:

  • ObjectDetectorService.swift: 検出機能を初期化し、モデル選択を処理して、入力データに対する推論を実行します。
  • CameraViewController.swift: ライブカメラフィード入力モードの UI を実装して可視化します 確認できます。
  • MediaLibraryViewController.swift: 静止画像ファイルと動画ファイル入力モードの UI を実装します。 検出結果を可視化します。

セットアップ

このセクションでは、開発環境をセットアップする主な手順と Object Detector を使用する方法について説明します。設定に関する一般的な情報については、 MediaPipe タスクを使用するための開発環境(プラットフォーム バージョンを含む) iOS の設定ガイドをご覧ください。

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

依存関係

オブジェクト検出は MediaPipeTasksVision ライブラリを使用します。このライブラリをインストールする必要があります。 構築しましたこのライブラリは Swift アプリと Objective-C アプリの両方と互換性がある 言語固有の追加の設定は不要です

macOS に CocoaPods をインストールする手順については、CocoaPods インストール ガイドをご覧ください。 必要な Pod を使用して Podfile を作成する方法については、 詳しくは、 CocoaPods

次のコードを使用して、Podfile に MediaPipeTasksVision Pod を追加します。

target 'MyObjectDetectorApp' do
  use_frameworks!
  pod 'MediaPipeTasksVision'
end

アプリに単体テスト ターゲットが含まれている場合は、 iOS をご覧ください。 あなたのPodfile

モデル

MediaPipe オブジェクト検出タスクには、互換性のあるトレーニング済みモデルが必要 見ていきましょう。利用可能なトレーニング済みモデルについて詳しくは、 オブジェクト検出機能については、タスクの概要をご覧ください。モデル セクションをご覧ください

モデルを選択してダウンロードし、Xcode を使用してプロジェクト ディレクトリに追加します。 Xcode プロジェクトにファイルを追加する方法については、 Xcode 内のファイルとフォルダ プロジェクトです。

BaseOptions.modelAssetPath プロパティを使用してモデルのパスを指定する 追加できますコード例については、次のセクションをご覧ください。

タスクを作成する

オブジェクト検出タスクを作成するには、そのイニシャライザのいずれかを呼び出します。「 ObjectDetector(options:) イニシャライザが構成オプションの値を設定する ランニングモード、表示名のロケール、結果の最大数、信頼度を含む 拒否リストなどがあります

カスタマイズされた構成でオブジェクト検出を初期化する必要がない場合 ObjectDetector(modelPath:) イニシャライザを使用して、 オブジェクト検出器とデフォルトのオプション。リソースの構成について 構成の概要をご覧ください。

オブジェクト検出タスクは、静止画像と動画ファイルの 3 つの入力データタイプをサポートします。 ストリーミング動画にも対応していますデフォルトでは、ObjectDetector(modelPath:) は 行います。動画を処理するためにタスクを初期化する場合は、 ファイルまたはライブ動画ストリームの場合は、ObjectDetector(options:) を使用して動画を指定します 配信モードを選択できますライブ配信モードでは、 objectDetectorLiveStreamDelegate 構成オプションを使用すると、 オブジェクト検出: 検知結果を委任に非同期で配信します。

ランニングモードに対応するタブを選択すると、タスクの作成方法を確認できます 推論を実行できます

Swift

画像

import MediaPipeTasksVision

let modelPath = Bundle.main.path(forResource: "model",
                                      ofType: "tflite")

let options = ObjectDetectorOptions()
options.baseOptions.modelAssetPath = modelPath
options.runningMode = .image
options.maxResults = 5

let objectDetector = try ObjectDetector(options: options)
    

動画

import MediaPipeTasksVision

let modelPath = Bundle.main.path(forResource: "model",
                                      ofType: "tflite")

let options = ObjectDetectorOptions()
options.baseOptions.modelAssetPath = modelPath
options.runningMode = .video
options.maxResults = 5

let objectDetector = try ObjectDetector(options: options)
    

ライブ配信

import MediaPipeTasksVision

// Class that conforms to the `ObjectDetectorLiveStreamDelegate` protocol and
// implements the method that the object detector calls once it
// finishes performing detection on each input frame.
class ObjectDetectorResultProcessor: NSObject, ObjectDetectorLiveStreamDelegate {

  func objectDetector(
    _ objectDetector: ObjectDetector,
    didFinishDetection objectDetectionResult: ObjectDetectorResult?,
    timestampInMilliseconds: Int,
    error: Error?) {
    // Process the detection result or errors here.
  }
}

let modelPath = Bundle.main.path(forResource: "model",
                                      ofType: "tflite")

let options = ObjectDetectorOptions()
options.baseOptions.modelAssetPath = modelPath
options.runningMode = .liveStream
options.maxResults = 5

// Assign an object of the class to the `objectDetectorLiveStreamDelegate`
// property.
let processor = ObjectDetectorResultProcessor()
options.objectDetectorLiveStreamDelegate = processor

let objectDetector = try ObjectDetector(options: options)
    

Objective-C

画像

@import MediaPipeTasksVision;

NSString *modelPath = [[NSBundle mainBundle] pathForResource:@"model"
                                                      ofType:@"tflite"];

MPPObjectDetectorOptions *options = [[MPPObjectDetectorOptions alloc] init];
options.baseOptions.modelAssetPath = modelPath;
options.runningMode = MPPRunningModeImage;
options.maxResults = 5;

MPPObjectDetector *objectDetector =
      [[MPPObjectDetector alloc] initWithOptions:options error:nil];
    

動画

@import MediaPipeTasksVision;

NSString *modelPath = [[NSBundle mainBundle] pathForResource:@"model"
                                                      ofType:@"tflite"];

MPPObjectDetectorOptions *options = [[MPPObjectDetectorOptions alloc] init];
options.baseOptions.modelAssetPath = modelPath;
options.runningMode = MPPRunningModeVideo;
options.maxResults = 5;

MPPObjectDetector *objectDetector =
      [[MPPObjectDetector alloc] initWithOptions:options error:nil];
    

ライブ配信

@import MediaPipeTasksVision;

// Class that conforms to the `ObjectDetectorLiveStreamDelegate` protocol and
// implements the method that the object detector calls once it
// finishes performing detection on each input frame.

@interface APPObjectDetectorResultProcessor : NSObject 

@end

@implementation MPPObjectDetectorResultProcessor

-   (void)objectDetector:(MPPObjectDetector *)objectDetector
    didFinishDetectionWithResult:(MPPObjectDetectorResult *)ObjectDetectorResult
         timestampInMilliseconds:(NSInteger)timestampInMilliseconds
                           error:(NSError *)error {

    // Process the detection result or errors here.

}

@end

NSString *modelPath = [[NSBundle mainBundle] pathForResource:@"model"
                                                      ofType:@"tflite"];

MPPObjectDetectorOptions *options = [[MPPObjectDetectorOptions alloc] init];
options.baseOptions.modelAssetPath = modelPath;
options.runningMode = MPPRunningModeLiveStream;
options.maxResults = 5;

// Assign an object of the class to the `objectDetectorLiveStreamDelegate`
// property.
APPObjectDetectorResultProcessor *processor = [APPObjectDetectorResultProcessor new];
options.objectDetectorLiveStreamDelegate = processor;

MPPObjectDetector *objectDetector =
      [[MPPObjectDetector alloc] initWithOptions:options error:nil];
    

構成オプション

このタスクには、iOS アプリの場合、次の構成オプションがあります。

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

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

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

LIVE_STREAM: 入力のライブ配信のモード カメラからのデータなどです。このモードでは、resultListener は 結果を受け取るリスナーを設定するために呼び出されます。 使用できます。
{RunningMode.image, RunningMode.video, RunningMode.liveStream} RunningMode.image
displayNamesLocales 指定された表示名に使うラベルの言語を設定します。 タスクのモデルのメタデータ(利用可能な場合)。デフォルトは en です。 英語。カスタムモデルのメタデータにローカライズされたラベルを追加できます。 TensorFlow Lite Metadata Writer API を使用 言語 / 地域コード en
maxResults オプションの高スコアの検出結果の最大数を設定します。 戻ります。 正の数 -1(すべての結果が返されます)
scoreThreshold 予測スコアのしきい値を設定します。このしきい値は、 モデル メタデータ(存在する場合)この値を下回る結果は拒否されます。 任意の浮動小数点数 未設定
categoryAllowlist 許可するカテゴリ名のオプション リストを設定します。空でない場合、 カテゴリ名がこのセットに含まれていない検出結果は、 フィルタで除外されます重複または不明なカテゴリ名は無視されます。 このオプションは categoryDenylist とは相互に排他的であり、 どちらの結果もエラーになります 任意の文字列 未設定
categoryDenylist 許可されていないカテゴリ名のオプション リストを設定します。条件 空ではない場合、このセット内にカテゴリ名が含まれる検出結果がフィルタされます。 できます。重複または不明なカテゴリ名は無視されます。このオプションは categoryAllowlist と排他的であり、両方を使用するとエラーになります。 任意の文字列 未設定

ライブ配信の設定

実行モードがライブ ストリームに設定されている場合、オブジェクト検出機能は 追加の objectDetectorLiveStreamDelegate 構成オプションがあり、 有効にすると、検出機能が非同期で検出結果を取得できます。委譲 実装する objectDetector(_objectDetector:didFinishDetection:timestampInMilliseconds:error:) メソッドを呼び出します。これは、オブジェクトの検出結果を処理した後に、オブジェクト検出によって呼び出されます。 表示されます。

オプション名 説明 値の範囲 デフォルト値
objectDetectorLiveStreamDelegate オブジェクト検出機能で検出結果を非同期で受信できるようにします。 ライブ配信のライブ ストリーム モードです。インスタンスがこのプロパティに設定されているクラスは、 実装する objectDetector(_:didFinishDetection:timestampInMilliseconds:error:) メソッドを呼び出します。 該当なし 未設定

データの準備

事前に入力画像またはフレームを MPImage オブジェクトに変換する必要があります。 オブジェクト検出器に渡します。MPImage はさまざまな種類の iOS 画像をサポートしています 形式があり、任意の実行モードで推論に使用できます。詳細 MPImage の詳細については、 MPImage API

ユースケースと実行モードに基づいて、iOS 画像形式を選択してください MPImage は、UIImageCVPixelBuffer、および CMSampleBuffer 件の iOS 画像形式。

UIImage

UIImage 形式は、次の実行モードに適しています。

  • 画像: App Bundle、ユーザー ギャラリー、ファイル システムの UIImage の画像は MPImage オブジェクトに変換できます。

  • 動画: AVAssetImageGenerator を使用 動画フレームを抽出して CGImage UIImage の画像に変換します。

Swift

// Load an image on the user's device as an iOS `UIImage` object.

// Convert the `UIImage` object to a MediaPipe's Image object having the default
// orientation `UIImage.Orientation.up`.
let image = try MPImage(uiImage: image)
    

Objective-C

// Load an image on the user's device as an iOS `UIImage` object.

// Convert the `UIImage` object to a MediaPipe's Image object having the default
// orientation `UIImageOrientationUp`.
MPImage *image = [[MPPImage alloc] initWithUIImage:image error:nil];
    

この例では、MPImage をデフォルトの UIImage.Orientation.Up 方向です。MPImage は、サポートされているいずれかの方法で初期化できます。 UIImage.Orientation 使用できます。オブジェクト検出は、.upMirrored などの反転した向きをサポートしていません。 .downMirrored.leftMirrored.rightMirrored

UIImage の詳細については、UIImage Apple Developer をご覧ください。 ドキュメントをご覧ください。

CVPixelBuffer

CVPixelBuffer 形式はフレームを生成するアプリに適している iOS の CoreImage を使用してください。 処理するためのフレームワークです。

CVPixelBuffer 形式は、次の実行モードに適しています。

  • 画像: なんらかの処理後に CVPixelBuffer の画像を生成するアプリ オブジェクト検出機能に送信すると、CoreImage 構成されます

  • 動画: 動画フレームは CVPixelBuffer 形式に変換できます。 動画モードでオブジェクト検出に送信されます。

  • ライブ ストリーム: iOS カメラを使用してフレームを生成するアプリは、 送信する前に、CVPixelBuffer 形式に変換する ライブ配信モードのオブジェクト検出。

Swift

// Obtain a CVPixelBuffer.

// Convert the `CVPixelBuffer` object to a MediaPipe's Image object having the default
// orientation `UIImage.Orientation.up`.
let image = try MPImage(pixelBuffer: pixelBuffer)
    

Objective-C

// Obtain a CVPixelBuffer.

// Convert the `CVPixelBuffer` object to a MediaPipe's Image object having the
// default orientation `UIImageOrientationUp`.
MPImage *image = [[MPPImage alloc] initWithUIImage:image error:nil];
    

CVPixelBuffer の詳細については、CVPixelBuffer Apple をご覧ください。 デベロッパー ドキュメントをご覧ください。

CMSampleBuffer

CMSampleBuffer 形式では、統一されたメディアタイプのメディア サンプルが保存されます。 ライブ配信の実行モードに適していますiOS カメラのライブフレームは、 iOS によって CMSampleBuffer 形式で非同期に配信されます。 AVCaptureVideoDataOutput.

Swift

// Obtain a CMSampleBuffer.

// Convert the `CMSampleBuffer` object to a MediaPipe's Image object having the default
// orientation `UIImage.Orientation.up`.
let image = try MPImage(sampleBuffer: sampleBuffer)
    

Objective-C

// Obtain a `CMSampleBuffer`.

// Convert the `CMSampleBuffer` object to a MediaPipe's Image object having the
// default orientation `UIImageOrientationUp`.
MPImage *image = [[MPPImage alloc] initWithSampleBuffer:sampleBuffer error:nil];
    

CMSampleBuffer の詳細については、CMSampleBuffer Apple をご覧ください。 デベロッパー ドキュメントをご覧ください。

タスクを実行する

オブジェクト検出を実行するには、割り当てられたオブジェクトに固有の detect() メソッドを使用します。 実行モード:

  • 静止画像: detect(image:)
  • 動画: detect(videoFrame:timestampInMilliseconds:)
  • ライブ配信: detectAsync(image:)

次のコードサンプルは、Google Cloud でオブジェクト検出機能を実行する基本的な例を示しています。 実行モードが 3 つあります

Swift

画像

let objectDetector.detect(image:image)
    

動画

let objectDetector.detect(videoFrame:image)
    

ライブ配信

let objectDetector.detectAsync(image:image)
    

Objective-C

画像

MPPObjectDetectorResult *result = [objectDetector detectInImage:image error:nil];
    

動画

MPPObjectDetectorResult *result = [objectDetector detectInVideoFrame:image          timestampInMilliseconds:timestamp error:nil];
    

ライブ配信

BOOL success = [objectDetector detectAsyncInImage:image
                          timestampInMilliseconds:timestamp
                                            error:nil];
    

オブジェクト検出のコード例は、これらの各モードの実装を示しています。 (詳細)detect(image:)detect(videoFrame:)detectAsync(image:)。このサンプルコードを使用すると、ユーザーは ユースケースでは不要な場合もあります。

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

  • 動画モードまたはライブ配信モードで実行する場合は、 オブジェクト検出タスクへの入力フレームのタイムスタンプ。

  • 画像モードまたは動画モードで実行している場合、オブジェクト検出タスクは、 入力画像やフレームの処理が完了するまで待機しません。宛先 現在のスレッドをブロックせずにバックグラウンドで処理を実行 使用すると、 Dispatch または NSOperation 説明します。

  • ライブストリーム モードで実行すると、オブジェクト検出タスクがすぐに返されます。 現在のスレッドをブロックしません。このメソッドは、 objectDetector(_objectDetector:didFinishDetection:timestampInMilliseconds:error:) メソッドに各入力フレームを処理した後、検出結果とともに返されます。「 オブジェクト検出機能は、専用シリアル ログで非同期にこのメソッドを呼び出します。 ディスパッチキューに格納されます。ユーザー インターフェースに結果を表示するには、 メインキューに送られます。detectAsync 関数は、オブジェクト検出タスクが他のオブジェクトの処理でビジー状態 新しい入力フレームを無視します。

結果の処理と表示

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

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

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

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

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