AutoML でトレーニングされたモデルを使用して画像にラベルを付ける(iOS)

AutoML Vision Edge を使用して独自のモデルをトレーニングしたら、そのモデルをアプリで使用して画像にラベルを付けることができます。

AutoML Vision Edge からトレーニングされたモデルを統合するには、モデルのファイルを Xcode プロジェクトにコピーしてバンドルする方法と、Firebase から動的にダウンロードする方法があります。

モデルのバンドル オプション
アプリにバンドルする
  • モデルがバンドルの一部
  • このモデルは、iOS デバイスがオフラインのときでもすぐに利用できます。
  • Firebase プロジェクトは不要
Firebase でホストする
  • モデルを Firebase Machine Learning にアップロードしてホストする
  • アプリバンドルのサイズを小さくする
  • モデルがオンデマンドでダウンロードされる
  • アプリを再公開することなくモデルの更新を push できる
  • Firebase Remote Config による簡単な A/B テスト
  • Firebase プロジェクトが必要

試してみる

始める前に

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

モデルをアプリにバンドルする場合:
    pod 'GoogleMLKit/ImageLabelingAutoML'
    
Firebase からモデルを動的にダウンロードするには、LinkFirebase 依存関係を追加します。
    pod 'GoogleMLKit/ImageLabelingAutoML'
    pod 'GoogleMLKit/LinkFirebase'
    
2. プロジェクトの Pod をインストールまたは更新した後に、.xcworkspacecode> を使用して Xcode プロジェクトを開きます。ML Kit は Xcode バージョン 13.2.1 以降でサポートされています。3. モデルをダウンロードする場合は、Firebase を iOS プロジェクトに追加します(まだ行っていない場合)。これは、モデルをバンドルする場合には必要ありません。

1. モデルを読み込む

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

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

1. Firebase コンソールからダウンロードした zip アーカイブからモデルとそのメタデータをフォルダに抽出します。
    your_model_directory
      |____dict.txt
      |____manifest.json
      |____model.tflite
    
3 つのファイルすべてを同じフォルダに配置する必要があります。ダウンロードしたファイルは修正せずにそのまま使用することをおすすめします(ファイル名を含めて)。

2. フォルダを Xcode プロジェクトにコピーします。その際、[Create folder references] を選択するように注意してください。モデルファイルとメタデータはアプリバンドルに含まれ、ML Kit で利用できます。

3. モデル マニフェスト ファイルへのパスを指定して AutoMLImageLabelerLocalModel オブジェクトを作成します。
SwiftObjective-C
guard let manifestPath = Bundle.main.path(
    forResource: "manifest",
    ofType: "json",
    inDirectory: "your_model_directory"
) else { return }
let localModel = AutoMLImageLabelerLocalModel(manifestPath: manifestPath)
NSString *manifestPath =
    [NSBundle.mainBundle pathForResource:@"manifest"
                                  ofType:@"json"
                             inDirectory:@"your_model_directory"];
MLKAutoMLImageLabelerLocalModel *localModel =
    [[MLKAutoMLImageLabelerLocalModel alloc] initWithManifestPath:manifestPath];

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

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

SwiftObjective-C
let remoteModel = AutoMLImageLabelerRemoteModel(
    name: "your_remote_model"  // The name you assigned in
                               // the Firebase console.
)
MLKAutoMLImageLabelerRemoteModel *remoteModel =
    [[MLKAutoMLImageLabelerRemoteModel alloc]
        initWithName:@"your_remote_model"];  // The name you assigned in
                                             // the Firebase console.

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

SwiftObjective-C
let downloadConditions = ModelDownloadConditions(
  allowsCellularAccess: true,
  allowsBackgroundDownloading: true
)

let downloadProgress = ModelManager.modelManager().download(
  remoteModel,
  conditions: downloadConditions
)
MLKModelDownloadConditions *downloadConditions =
    [[MLKModelDownloadConditions alloc] initWithAllowsCellularAccess:YES
                                         allowsBackgroundDownloading:YES];

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

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

モデルから画像ラベラーを作成する

モデルソースを構成したら、そのソースのいずれか 1 つから ImageLabeler オブジェクトを作成します。

ローカル バンドルモデルのみがある場合は、AutoMLImageLabelerLocalModel オブジェクトからラベラーを作成し、必要な信頼スコアのしきい値を構成するだけで済みます(モードを評価するを参照)。

SwiftObjective-C
let options = AutoMLImageLabelerOptions(localModel: localModel)
options.confidenceThreshold = NSNumber(value: 0.0)  // Evaluate your model in the Firebase console
                                                    // to determine an appropriate value.
let imageLabeler = ImageLabeler.imageLabeler(options: options)
MLKAutoMLImageLabelerOptions *options =
    [[MLKAutoMLImageLabelerOptions alloc] initWithLocalModel:localModel];
options.confidenceThreshold = @(0.0);  // Evaluate your model in the Firebase console
                                       // to determine an appropriate value.
MLKImageLabeler *imageLabeler =
    [MLKImageLabeler imageLabelerWithOptions:options];

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

これはラベラーの実行前に確認するだけで済みますが、リモートでホストされるモデルとローカルにバンドルされたモデルの両方がある場合は、ImageLabeler をインスタンス化時にこのチェックを行うとよいでしょう。ダウンロードされている場合はリモートモデルから、そうでない場合はローカルモデルからラベラーを作成します。

SwiftObjective-C
var options: AutoMLImageLabelerOptions!
if (ModelManager.modelManager().isModelDownloaded(remoteModel)) {
  options = AutoMLImageLabelerOptions(remoteModel: remoteModel)
} else {
  options = AutoMLImageLabelerOptions(localModel: localModel)
}
options.confidenceThreshold = NSNumber(value: 0.0)  // Evaluate your model in the Firebase console
                                                    // to determine an appropriate value.
let imageLabeler = ImageLabeler.imageLabeler(options: options)
MLKAutoMLImageLabelerOptions *options;
if ([[MLKModelManager modelManager] isModelDownloaded:remoteModel]) {
  options = [[MLKAutoMLImageLabelerOptions alloc] initWithRemoteModel:remoteModel];
} else {
  options = [[MLKAutoMLImageLabelerOptions alloc] initWithLocalModel:localModel];
}
options.confidenceThreshold = @(0.0);  // Evaluate your model in the Firebase console
                                       // to determine an appropriate value.
MLKImageLabeler *imageLabeler =
    [MLKImageLabeler imageLabelerWithOptions:options];

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

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

SwiftObjective-C
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]
    // ...
}
__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];
            }];

2. 入力画像を準備する

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

UIImage を使用する場合の手順は次のとおりです。

  • UIImage を使用して VisionImage オブジェクトを作成します。正しい .orientation を指定してください。
    SwiftObjective-C
    let image = VisionImage(image: UIImage)
    visionImage.orientation = image.imageOrientation
    MLKVisionImage *visionImage = [[MLKVisionImage alloc] initWithImage:image];
    visionImage.orientation = image.imageOrientation;

CMSampleBuffer を使用する場合の手順は次のとおりです。

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

    画像の向きは次のように取得します。

    SwiftObjective-C
    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
      }
    }
          
    - (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 オブジェクトを作成します。
    SwiftObjective-C
    let image = VisionImage(buffer: sampleBuffer)
    image.orientation = imageOrientation(
      deviceOrientation: UIDevice.current.orientation,
      cameraPosition: cameraPosition)
     MLKVisionImage *image = [[MLKVisionImage alloc] initWithBuffer:sampleBuffer];
     image.orientation =
       [self imageOrientationFromDeviceOrientation:UIDevice.currentDevice.orientation
                                    cameraPosition:cameraPosition];

3. 画像ラベラーを実行する

非同期:

SwiftObjective-C
imageLabeler.process(image) { labels, error in
    guard error == nil, let labels = labels, !labels.isEmpty else {
        // Handle the error.
        return
    }
    // Show results.
}
[imageLabeler
    processImage:image
      completion:^(NSArray *_Nullable labels,
                   NSError *_Nullable error) {
        if (labels.count == 0) {
            // Handle the error.
            return;
        }
        // Show results.
     }];

同期:

SwiftObjective-C
var labels: [ImageLabel]
do {
    labels = try imageLabeler.results(in: image)
} catch let error {
    // Handle the error.
    return
}
// Show results.
NSError *error;
NSArray *labels =
    [imageLabeler resultsInImage:image error:&error];
// Show results or handle the error.

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

画像のラベル付けオペレーションが成功すると、ImageLabel の配列が返されます。各 ImageLabel は画像内でラベル付けされたものを表します。各ラベルのテキストの説明(TensorFlow Lite モデルファイルのメタデータで使用できる場合)、信頼スコア、インデックスを取得できます。次に例を示します。
SwiftObjective-C
for label in labels {
  let labelText = label.text
  let confidence = label.confidence
  let index = label.index
}
for (MLKImageLabel *label in labels) {
  NSString *labelText = label.text;
  float confidence = label.confidence;
  NSInteger index = label.index;
}

リアルタイムのパフォーマンスを改善するためのヒント

リアルタイムのアプリケーションで画像にラベルを付ける場合は、適切なフレームレートを得るために次のガイドラインに従ってください。

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