ML Kit を使用した自撮り写真のセグメンテーション(iOS)

ML Kit には、自撮り写真のセグメンテーション用に最適化された SDK が用意されています。Selfie Segmenter アセットは、ビルド時にアプリに静的にリンクされます。これにより、アプリのサイズが最大 24 MB 増加し、iPhone X で測定したところ、入力画像のサイズに応じて API レイテンシが約 7 ミリ秒から約 12 ミリ秒に変化する可能性があります。

試してみる

始める前に

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

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

1. Segmenter のインスタンスを作成する

自撮り画像でセグメンテーションを実行するには、まず SelfieSegmenterOptions を使用して Segmenter のインスタンスを作成し、必要に応じてセグメンテーション設定を指定します。

セグメンターのオプション

セグメント ビルダー モード

Segmenter は 2 つのモードで動作します。ユースケースに一致するものを選択してください。

STREAM_MODE (default)

このモードは、動画やカメラからフレームをストリーミングするように設計されています。このモードでは、セグメンターは前のフレームの結果を利用して、よりスムーズなセグメンテーション結果を返します。

SINGLE_IMAGE_MODE (default)

このモードは、関連性のない単一の画像用に設計されています。このモードでは、セグメンターは各画像を個別に処理し、フレーム間のスムージングは行いません。

生のサイズマスクを有効にする

モデルの出力サイズと一致する未加工のサイズマスクを返すようセグメンターに要求します。

通常、生マスクのサイズ(256x256 など)は入力画像のサイズよりも小さくなります。

このオプションを指定しない場合、セグメンターは入力画像のサイズに合わせて未加工のマスクをリスケールします。カスタマイズされたリスケーリング ロジックを適用する場合や、ユースケースでリスケーリングが必要ない場合は、このオプションの使用を検討してください。

セグメンター オプションを指定します。

Swift

let options = SelfieSegmenterOptions()
options.segmenterMode = .singleImage
options.shouldEnableRawSizeMask = true

Objective-C

MLKSelfieSegmenterOptions *options = [[MLKSelfieSegmenterOptions alloc] init];
options.segmenterMode = MLKSegmenterModeSingleImage;
options.shouldEnableRawSizeMask = YES;

最後に、Segmenter のインスタンスを取得します。指定したオプションを渡します。

Swift

let segmenter = Segmenter.segmenter(options: options)

Objective-C

MLKSegmenter *segmenter = [MLKSegmenter segmenterWithOptions:options];

2. 入力画像を準備する

自撮り画像をセグメント化するには、各画像または動画フレームに対して次の操作を行います。ストリーム モードを有効にした場合は、CMSampleBuffer から VisionImage オブジェクトを作成する必要があります。

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];

3. 画像を処理する

VisionImage オブジェクトを Segmenter のいずれかの画像処理メソッドに渡します。非同期 process(image:) メソッドまたは同期 results(in:) メソッドを使用できます。

自撮り画像に対して同期的にセグメンテーションを実行するには:

Swift

var mask: [SegmentationMask]
do {
  mask = try segmenter.results(in: image)
} catch let error {
  print("Failed to perform segmentation with error: \(error.localizedDescription).")
  return
}

// Success. Get a segmentation mask here.

Objective-C

NSError *error;
MLKSegmentationMask *mask =
    [segmenter resultsInImage:image error:&error];
if (error != nil) {
  // Error.
  return;
}

// Success. Get a segmentation mask here.

自撮り画像に対して非同期でセグメンテーションを行うには:

Swift

segmenter.process(image) { mask, error in
  guard error == nil else {
    // Error.
    return
  }
  // Success. Get a segmentation mask here.

Objective-C

[segmenter processImage:image
             completion:^(MLKSegmentationMask * _Nullable mask,
                          NSError * _Nullable error) {
               if (error != nil) {
                 // Error.
                 return;
               }
               // Success. Get a segmentation mask here.
             }];

4. セグメンテーション マスクを取得する

セグメンテーションの結果は次の方法で取得できます。

Swift

let maskWidth = CVPixelBufferGetWidth(mask.buffer)
let maskHeight = CVPixelBufferGetHeight(mask.buffer)

CVPixelBufferLockBaseAddress(mask.buffer, CVPixelBufferLockFlags.readOnly)
let maskBytesPerRow = CVPixelBufferGetBytesPerRow(mask.buffer)
var maskAddress =
    CVPixelBufferGetBaseAddress(mask.buffer)!.bindMemory(
        to: Float32.self, capacity: maskBytesPerRow * maskHeight)

for _ in 0...(maskHeight - 1) {
  for col in 0...(maskWidth - 1) {
    // Gets the confidence of the pixel in the mask being in the foreground.
    let foregroundConfidence: Float32 = maskAddress[col]
  }
  maskAddress += maskBytesPerRow / MemoryLayout<Float32>.size
}

Objective-C

size_t width = CVPixelBufferGetWidth(mask.buffer);
size_t height = CVPixelBufferGetHeight(mask.buffer);

CVPixelBufferLockBaseAddress(mask.buffer, kCVPixelBufferLock_ReadOnly);
size_t maskBytesPerRow = CVPixelBufferGetBytesPerRow(mask.buffer);
float *maskAddress = (float *)CVPixelBufferGetBaseAddress(mask.buffer);

for (int row = 0; row < height; ++row) {
  for (int col = 0; col < width; ++col) {
    // Gets the confidence of the pixel in the mask being in the foreground.
    float foregroundConfidence = maskAddress[col];
  }
  maskAddress += maskBytesPerRow / sizeof(float);
}

セグメンテーション結果の使用方法の完全な例については、ML Kit クイックスタート サンプルをご覧ください。

パフォーマンスを向上させるためのヒント

結果の品質は、入力画像の品質によって異なります。

  • ML Kit で正確なセグメンテーション結果を得るには、画像のサイズが 256x256 ピクセル以上である必要があります。
  • リアルタイム アプリケーションで自撮り写真のセグメンテーションを行う場合は、入力画像の全体サイズも考慮する必要があります。サイズが小さいほど処理は高速になるため、レイテンシを短くするには画像を低い解像度でキャプチャしますが、上記の解像度要件に留意し、対象が画像のできるだけ多くの部分を占めるようにします。
  • 画像がぼやけていると、認識精度が低下する可能性があります。満足のいく結果が得られない場合は、ユーザーに画像をキャプチャし直すよう求めてください。

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

  • stream セグメンター モードを使用します。
  • より低い解像度で画像をキャプチャすることを検討してください。ただし、この API の画像サイズに関する要件にも留意してください。
  • 動画フレームの処理には、セグメンターの results(in:) 同期 API を使用します。このメソッドは、AVCaptureVideoDataOutputSampleBufferDelegatecaptureOutput(_, didOutput:from:) 関数から呼び出し、指定された動画フレームから結果を同期的に取得します。AVCaptureVideoDataOutputalwaysDiscardsLateVideoFrames を true のままにして、セグメンターへの呼び出しをスロットリングします。セグメンターの実行中に新しい動画フレームが使用可能になった場合は、そのフレームはドロップされます。
  • セグメンターの出力を使用して入力画像の上にグラフィックスをオーバーレイする場合は、まず ML Kit から検出結果を取得し、画像とオーバーレイを 1 つのステップでレンダリングします。これにより、ディスプレイ サーフェスへのレンダリングは処理された入力フレームごとに 1 回で済みます。例については、ML Kit クイックスタート サンプルpreviewOverlayView クラスと CameraViewController クラスをご覧ください。