iOS でカスタム分類モデルを使用してオブジェクトを検出、追跡、分類する

ML Kit を使用すると、連続する動画フレームのオブジェクトを検出して追跡できます。

ML Kit に画像を渡すと、画像内の最大 5 個のオブジェクトと、画像内の各オブジェクトの位置が検出されます。動画ストリームでオブジェクトを検出する場合、各オブジェクトには一意の ID が割り当てられます。この ID を使用して、オブジェクトをフレーム間でトラッキングできます。

カスタム画像分類モデルを使用して、検出されたオブジェクトを分類できます。モデルの互換性要件、事前トレーニング済みモデルの場所、独自のモデルをトレーニングする方法については、ML Kit によるカスタムモデルをご覧ください。

カスタムモデルを統合するには、2 つの方法があります。モデルは、アプリのアセット フォルダ内に配置してバンドルすることも、Firebase から動的にダウンロードすることもできます。次の表は、2 つのオプションを比較したものです。

バンドルモデル ホストされているモデル
このモデルはアプリの .ipa ファイルの一部であるため、サイズが大きくなります。 このモデルはアプリの .ipa ファイルには含まれません。これは、Firebase Machine Learning にアップロードすることでホストされます。
Android デバイスがオフラインの場合でも、モデルをすぐに利用できます モデルがオンデマンドでダウンロードされる
Firebase プロジェクトは不要 Firebase プロジェクトが必要
モデルを更新するにはアプリを再公開する必要があります アプリを再公開することなくモデルの更新を push できる
組み込みの A/B テストなし Firebase Remote Config による簡単な A/B テスト

試してみる

始める前に

  1. Podfile に ML Kit ライブラリを含めます。

    モデルをアプリにバンドルする場合:

    pod 'GoogleMLKit/ObjectDetectionCustom', '3.2.0'
    

    Firebase からモデルを動的にダウンロードするには、LinkFirebase 依存関係を追加します。

    pod 'GoogleMLKit/ObjectDetectionCustom', '3.2.0'
    pod 'GoogleMLKit/LinkFirebase', '3.2.0'
    
  2. プロジェクトの Pod をインストールまたは更新したら、.xcworkspace を使用して Xcode プロジェクトを開きます。ML Kit は Xcode バージョン 13.2.1 以降でサポートされています。

  3. モデルをダウンロードする場合は、Firebase を iOS プロジェクトに追加します(まだ行っていない場合)。これは、モデルをバンドルする場合には必要ありません。

1. モデルを読み込む

ローカル モデルソースを構成する

モデルをアプリにバンドルするには:

  1. モデルファイル(拡張子は通常 .tflite または .lite)を Xcode プロジェクトにコピーします。その際、Copy bundle resources を選択してください。モデルファイルは App Bundle に含まれ、ML Kit から使用できます。

  2. モデルファイルへのパスを指定して LocalModel オブジェクトを作成します。

    Swift

    let localModel = LocalModel(path: localModelFilePath)

    Objective-C

    MLKLocalModel *localModel =
        [[MLKLocalModel alloc] initWithPath:localModelFilePath];

Firebase によってホストされるモデルソースを構成する

リモートでホストされるモデルを使用するには、CustomRemoteModel オブジェクトを作成します。その際に、モデルを公開したときに割り当てた名前を指定します。

Swift

let firebaseModelSource = FirebaseModelSource(
    name: "your_remote_model") // The name you assigned in
                               // the Firebase console.
let remoteModel = CustomRemoteModel(remoteModelSource: firebaseModelSource)

Objective-C

MLKFirebaseModelSource *firebaseModelSource =
    [[MLKFirebaseModelSource alloc]
        initWithName:@"your_remote_model"]; // The name you assigned in
                                            // the Firebase console.
MLKCustomRemoteModel *remoteModel =
    [[MLKCustomRemoteModel alloc]
        initWithRemoteModelSource:firebaseModelSource];

次に、ダウンロードを許可する条件を指定してモデルのダウンロード タスクを開始します。モデルがデバイスにない場合、または新しいバージョンのモデルが使用可能な場合、このタスクは Firebase から非同期でモデルをダウンロードします。

Swift

let downloadConditions = ModelDownloadConditions(
  allowsCellularAccess: true,
  allowsBackgroundDownloading: true
)

let downloadProgress = ModelManager.modelManager().download(
  remoteModel,
  conditions: downloadConditions
)

Objective-C

MLKModelDownloadConditions *downloadConditions =
    [[MLKModelDownloadConditions alloc] initWithAllowsCellularAccess:YES
                                         allowsBackgroundDownloading:YES];

NSProgress *downloadProgress =
    [[MLKModelManager modelManager] downloadModel:remoteModel
                                       conditions:downloadConditions];

多くのアプリは、初期化コードでモデルのダウンロード タスクを開始しますが、モデルを使用する前に開始することもできます。

2. オブジェクト検出を構成する

モデルソースを構成したら、CustomObjectDetectorOptions オブジェクトを使用して、ユースケースのオブジェクト検出を構成します。次の設定を変更できます。

オブジェクト検出の設定
検出モード STREAM_MODE(デフォルト)| SINGLE_IMAGE_MODE

STREAM_MODE(デフォルト)では、オブジェクト検出は低レイテンシで実行されますが、最初の数回の検出の呼び出しで不完全な結果(未指定の境界ボックスやカテゴリラベルなど)が生成される可能性があります。また、STREAM_MODE では検出機能がオブジェクトにトラッキング ID を割り当てます。これにより、フレームをまたいでオブジェクトを追跡できます。このモードは、オブジェクトをトラッキングする場合、または動画ストリームをリアルタイムで処理する場合など、低レイテンシが重要な場合に使用します。

SINGLE_IMAGE_MODE では、オブジェクトの境界ボックスが決定された後に、オブジェクト検出の結果が返されます。分類も有効にすると、境界ボックスとカテゴリラベルの両方が使用可能になったときに結果が返されます。その結果、検出のレイテンシが増加する可能性があります。また、SINGLE_IMAGE_MODE ではトラッキング ID が割り当てられません。レイテンシが重要ではなく、部分的な結果を処理しない場合は、このモードを使用します。

複数のオブジェクトを検出して追跡する false(デフォルト)| true

最大 5 つのオブジェクトを検出して追跡するか、最も視認性の高いオブジェクトのみを追跡するか(デフォルト)。

オブジェクトを分類する false(デフォルト)| true

指定されたカスタム分類器モデルを使用して、検出されたオブジェクトを分類するかどうか。カスタム分類モデルを使用するには、これを true に設定する必要があります。

分類の信頼度のしきい値

検出されたラベルの最小信頼スコア。設定されていない場合は、モデルのメタデータで指定された分類子のしきい値が使用されます。 モデルにメタデータが含まれていない場合、またはメタデータで分類器のしきい値が指定されていない場合は、デフォルトのしきい値 0.0 が使用されます。

オブジェクトあたりの最大ラベル数

検出機能が返すオブジェクトごとのラベルの最大数。設定しない場合は、デフォルト値の 10 が使用されます。

ローカル バンドルモデルのみがある場合は、LocalModel オブジェクトからオブジェクト検出機能を作成するだけで済みます。

Swift

let options = CustomObjectDetectorOptions(localModel: localModel)
options.detectorMode = .singleImage
options.shouldEnableClassification = true
options.shouldEnableMultipleObjects = true
options.classificationConfidenceThreshold = NSNumber(value: 0.5)
options.maxPerObjectLabelCount = 3

Objective-C

MLKCustomObjectDetectorOptions *options =
    [[MLKCustomObjectDetectorOptions alloc] initWithLocalModel:localModel];
options.detectorMode = MLKObjectDetectorModeSingleImage;
options.shouldEnableClassification = YES;
options.shouldEnableMultipleObjects = YES;
options.classificationConfidenceThreshold = @(0.5);
options.maxPerObjectLabelCount = 3;

リモートでホストされるモデルがある場合は、実行する前にモデルがダウンロードされていることを確認する必要があります。モデルのダウンロード タスクのステータスは、モデル マネージャーの isModelDownloaded(remoteModel:) メソッドを使用して確認できます。

この点はオブジェクト検出を実行する前に確認するだけで済みますが、リモートでホストされるモデルとローカル バンドル モデルの両方がある場合は、ObjectDetector をインスタンス化するときにこの確認を行うことをおすすめします。検出器はダウンロード済みの場合はリモートモデルから作成し、それ以外の場合はローカルモデルから作成します。

Swift

var options: CustomObjectDetectorOptions!
if (ModelManager.modelManager().isModelDownloaded(remoteModel)) {
  options = CustomObjectDetectorOptions(remoteModel: remoteModel)
} else {
  options = CustomObjectDetectorOptions(localModel: localModel)
}
options.detectorMode = .singleImage
options.shouldEnableClassification = true
options.shouldEnableMultipleObjects = true
options.classificationConfidenceThreshold = NSNumber(value: 0.5)
options.maxPerObjectLabelCount = 3

Objective-C

MLKCustomObjectDetectorOptions *options;
if ([[MLKModelManager modelManager] isModelDownloaded:remoteModel]) {
  options = [[MLKCustomObjectDetectorOptions alloc] initWithRemoteModel:remoteModel];
} else {
  options = [[MLKCustomObjectDetectorOptions alloc] initWithLocalModel:localModel];
}
options.detectorMode = MLKObjectDetectorModeSingleImage;
options.shouldEnableClassification = YES;
options.shouldEnableMultipleObjects = YES;
options.classificationConfidenceThreshold = @(0.5);
options.maxPerObjectLabelCount = 3;

リモートでホストされるモデルのみがある場合は、モデルがダウンロード済みであることを確認するまで、モデルに関連する機能を無効にする必要があります(UI の一部をグレー表示または非表示にするなど)。

モデルのダウンロード ステータスを取得するには、オブザーバーをデフォルトの通知センターに接続します。ダウンロードに時間がかかり、ダウンロードが完了するまでに元のオブジェクトが解放される可能性があります。そのため、Observer ブロックでは self への弱い参照を使用してください。例:

Swift

NotificationCenter.default.addObserver(
    forName: .mlkitModelDownloadDidSucceed,
    object: nil,
    queue: nil
) { [weak self] notification in
    guard let strongSelf = self,
        let userInfo = notification.userInfo,
        let model = userInfo[ModelDownloadUserInfoKey.remoteModel.rawValue]
            as? RemoteModel,
        model.name == "your_remote_model"
        else { return }
    // The model was downloaded and is available on the device
}

NotificationCenter.default.addObserver(
    forName: .mlkitModelDownloadDidFail,
    object: nil,
    queue: nil
) { [weak self] notification in
    guard let strongSelf = self,
        let userInfo = notification.userInfo,
        let model = userInfo[ModelDownloadUserInfoKey.remoteModel.rawValue]
            as? RemoteModel
        else { return }
    let error = userInfo[ModelDownloadUserInfoKey.error.rawValue]
    // ...
}

Objective-C

__weak typeof(self) weakSelf = self;

[NSNotificationCenter.defaultCenter
    addObserverForName:MLKModelDownloadDidSucceedNotification
                object:nil
                 queue:nil
            usingBlock:^(NSNotification *_Nonnull note) {
              if (weakSelf == nil | note.userInfo == nil) {
                return;
              }
              __strong typeof(self) strongSelf = weakSelf;

              MLKRemoteModel *model = note.userInfo[MLKModelDownloadUserInfoKeyRemoteModel];
              if ([model.name isEqualToString:@"your_remote_model"]) {
                // The model was downloaded and is available on the device
              }
            }];

[NSNotificationCenter.defaultCenter
    addObserverForName:MLKModelDownloadDidFailNotification
                object:nil
                 queue:nil
            usingBlock:^(NSNotification *_Nonnull note) {
              if (weakSelf == nil | note.userInfo == nil) {
                return;
              }
              __strong typeof(self) strongSelf = weakSelf;

              NSError *error = note.userInfo[MLKModelDownloadUserInfoKeyError];
            }];

オブジェクト検出とトラッキングの API は、次の 2 つの主要なユースケース向けに最適化されています。

  • カメラのビューファインダー内で最も目立つオブジェクトのライブ検出とトラッキング。
  • 静止画像からの複数のオブジェクトの検出。

このようなユースケース向けに API を構成するには:

Swift

// Live detection and tracking
let options = CustomObjectDetectorOptions(localModel: localModel)
options.shouldEnableClassification = true
options.maxPerObjectLabelCount = 3

// Multiple object detection in static images
let options = CustomObjectDetectorOptions(localModel: localModel)
options.detectorMode = .singleImage
options.shouldEnableMultipleObjects = true
options.shouldEnableClassification = true
options.maxPerObjectLabelCount = 3

Objective-C

// Live detection and tracking
MLKCustomObjectDetectorOptions *options =
    [[MLKCustomObjectDetectorOptions alloc] initWithLocalModel:localModel];
options.shouldEnableClassification = YES;
options.maxPerObjectLabelCount = 3;

// Multiple object detection in static images
MLKCustomObjectDetectorOptions *options =
    [[MLKCustomObjectDetectorOptions alloc] initWithLocalModel:localModel];
options.detectorMode = MLKObjectDetectorModeSingleImage;
options.shouldEnableMultipleObjects = YES;
options.shouldEnableClassification = YES;
options.maxPerObjectLabelCount = 3;

3. 入力画像を準備する

UIImage または CMSampleBuffer を使用して VisionImage オブジェクトを作成します。

UIImage を使用する場合は、次の操作を行います。

  • UIImage を使用して VisionImage オブジェクトを作成します。正しい .orientation を指定してください。

    Swift

    let image = VisionImage(image: UIImage)
    visionImage.orientation = image.imageOrientation

    Objective-C

    MLKVisionImage *visionImage = [[MLKVisionImage alloc] initWithImage:image];
    visionImage.orientation = image.imageOrientation;

CMSampleBuffer を使用する場合は、次の操作を行います。

  • CMSampleBuffer に含まれる画像データの向きを指定します。

    画像の向きを取得するには:

    Swift

    func imageOrientation(
      deviceOrientation: UIDeviceOrientation,
      cameraPosition: AVCaptureDevice.Position
    ) -> UIImage.Orientation {
      switch deviceOrientation {
      case .portrait:
        return cameraPosition == .front ? .leftMirrored : .right
      case .landscapeLeft:
        return cameraPosition == .front ? .downMirrored : .up
      case .portraitUpsideDown:
        return cameraPosition == .front ? .rightMirrored : .left
      case .landscapeRight:
        return cameraPosition == .front ? .upMirrored : .down
      case .faceDown, .faceUp, .unknown:
        return .up
      }
    }
          

    Objective-C

    - (UIImageOrientation)
      imageOrientationFromDeviceOrientation:(UIDeviceOrientation)deviceOrientation
                             cameraPosition:(AVCaptureDevicePosition)cameraPosition {
      switch (deviceOrientation) {
        case UIDeviceOrientationPortrait:
          return cameraPosition == AVCaptureDevicePositionFront ? UIImageOrientationLeftMirrored
                                                                : UIImageOrientationRight;
    
        case UIDeviceOrientationLandscapeLeft:
          return cameraPosition == AVCaptureDevicePositionFront ? UIImageOrientationDownMirrored
                                                                : UIImageOrientationUp;
        case UIDeviceOrientationPortraitUpsideDown:
          return cameraPosition == AVCaptureDevicePositionFront ? UIImageOrientationRightMirrored
                                                                : UIImageOrientationLeft;
        case UIDeviceOrientationLandscapeRight:
          return cameraPosition == AVCaptureDevicePositionFront ? UIImageOrientationUpMirrored
                                                                : UIImageOrientationDown;
        case UIDeviceOrientationUnknown:
        case UIDeviceOrientationFaceUp:
        case UIDeviceOrientationFaceDown:
          return UIImageOrientationUp;
      }
    }
          
  • CMSampleBuffer オブジェクトと画面の向きを使用して、VisionImage オブジェクトを作成します。

    Swift

    let image = VisionImage(buffer: sampleBuffer)
    image.orientation = imageOrientation(
      deviceOrientation: UIDevice.current.orientation,
      cameraPosition: cameraPosition)

    Objective-C

     MLKVisionImage *image = [[MLKVisionImage alloc] initWithBuffer:sampleBuffer];
     image.orientation =
       [self imageOrientationFromDeviceOrientation:UIDevice.currentDevice.orientation
                                    cameraPosition:cameraPosition];

4. オブジェクト検出を作成して実行する

  1. 新しいオブジェクト検出を作成します。

    Swift

    let objectDetector = ObjectDetector.objectDetector(options: options)

    Objective-C

    MLKObjectDetector *objectDetector = [MLKObjectDetector objectDetectorWithOptions:options];
  2. 次に、検出機能を使用します。

    非同期:

    Swift

    objectDetector.process(image) { objects, error in
        guard error == nil, let objects = objects, !objects.isEmpty else {
            // Handle the error.
            return
        }
        // Show results.
    }

    Objective-C

    [objectDetector
        processImage:image
          completion:^(NSArray *_Nullable objects,
                       NSError *_Nullable error) {
            if (objects.count == 0) {
                // Handle the error.
                return;
            }
            // Show results.
         }];

    同期:

    Swift

    var objects: [Object]
    do {
        objects = try objectDetector.results(in: image)
    } catch let error {
        // Handle the error.
        return
    }
    // Show results.

    Objective-C

    NSError *error;
    NSArray *objects =
        [objectDetector resultsInImage:image error:&error];
    // Show results or handle the error.

5. ラベル付きオブジェクトに関する情報を取得する

画像プロセッサの呼び出しが成功すると、非同期メソッドと同期メソッドのどちらを呼び出したかに応じて、Object のリストが完了ハンドラに渡されるか、リストが返されます。

Object には次のプロパティが含まれています。

frame 画像内のオブジェクトの位置を示す CGRect
trackingID 複数のイメージでオブジェクトを識別する整数。SINGLE_IMAGE_MODE の場合は「nil」。
labels
label.text ラベルのテキストの説明。TensorFlow Lite モデルのメタデータにラベルの説明が含まれている場合にのみ返されます。
label.index 分類器でサポートされているすべてのラベルの中でのラベルのインデックス。
label.confidence オブジェクト分類の信頼値。

Swift

// objects contains one item if multiple object detection wasn't enabled.
for object in objects {
  let frame = object.frame
  let trackingID = object.trackingID
  let description = object.labels.enumerated().map { (index, label) in
    "Label \(index): \(label.text), \(label.confidence), \(label.index)"
  }.joined(separator: "\n")
}

Objective-C

// The list of detected objects contains one item if multiple object detection
// wasn't enabled.
for (MLKObject *object in objects) {
  CGRect frame = object.frame;
  NSNumber *trackingID = object.trackingID;
  for (MLKObjectLabel *label in object.labels) {
    NSString *labelString =
        [NSString stringWithFormat:@"%@, %f, %lu",
                                   label.text,
                                   label.confidence,
                                   (unsigned long)label.index];
  }
}

優れたユーザー エクスペリエンスの確保

最適なユーザー エクスペリエンスを実現するには、アプリで次のガイドラインを遵守してください。

  • オブジェクト検出が成功するかどうかは、オブジェクトの視覚的な複雑さによって異なります。これが検出されるには、視覚的特徴が少ないオブジェクトが画像の大部分を占めている必要があります。検出するオブジェクトの種類に適した入力をキャプチャするためのガイダンスをユーザーに提供する必要があります。
  • 分類を使用するときに、サポートされているカテゴリに分類されないオブジェクトを検出するには、未知のオブジェクトに対する特別な処理を実装します。

また、[ML Kit マテリアル デザイン ショーケース アプリ][showcase-link]{: .external } とマテリアル デザインの ML を活用した機能のためのパターンのコレクションもご覧ください。

パフォーマンスの向上

リアルタイムのアプリケーションでオブジェクト検出を使用する場合は、最適なフレームレートを得るために次のガイドラインに従ってください。

  • リアルタイム アプリでストリーミング モードを使用する場合は、複数オブジェクト検出を使用しないでください。ほとんどのデバイスは十分なフレームレートを生成できないためです。

  • 動画フレームの処理には、検出機能の results(in:) 同期 API を使用します。このメソッドを AVCaptureVideoDataOutputSampleBufferDelegate captureOutput(_, didOutput:from:) 関数から呼び出して、指定された動画フレームから同期的に結果を取得します。 AVCaptureVideoDataOutput alwaysDiscardsLateVideoFramestrue のままにして、検出機能の呼び出しをスロットリングします。検出機能の実行中に新しい動画フレームが使用可能になると、そのフレームは破棄されます。
  • 検出機能の出力を使用して入力画像にグラフィックをオーバーレイする場合は、まず ML Kit から結果を取得してから、画像とオーバーレイを 1 つのステップでレンダリングします。これにより、ディスプレイ サーフェスへのレンダリングは、処理された入力フレームごとに 1 回だけ行います。例については、ML Kit クイックスタート サンプルの updatePreviewOverlayViewWithLastFrame をご覧ください。