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

ML Kit には、自撮り写真のセグメンテーション用に最適化された SDK が用意されています。Selfie Segmenter アセットは、ビルド時にアプリに静的にリンクされます。これにより、アプリのサイズが最大 24 MB 増加し、API レイテンシは入力画像のサイズに応じて 7 ms ~ 12 ms 程度変動します(iPhone X で測定)。

試してみる

始める前に

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

    pod 'GoogleMLKit/SegmentationSelfie', '7.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 など)は入力画像サイズよりも小さくなります。

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

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

SwiftObjective-C
let options = SelfieSegmenterOptions()
options.segmenterMode = .singleImage
options.shouldEnableRawSizeMask = true
MLKSelfieSegmenterOptions *options = [[MLKSelfieSegmenterOptions alloc] init];
options.segmenterMode = MLKSegmenterModeSingleImage;
options.shouldEnableRawSizeMask = YES;

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

SwiftObjective-C
let segmenter = Segmenter.segmenter(options: options)
MLKSegmenter *segmenter = [MLKSegmenter segmenterWithOptions:options];

2. 入力画像を準備する

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

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. 画像を処理する

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

自撮り写真のセグメンテーションを同期的に実行するには:

SwiftObjective-C
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.
NSError *error;
MLKSegmentationMask *mask =
    [segmenter resultsInImage:image error:&error];
if (error != nil) {
  // Error.
  return;
}

// Success. Get a segmentation mask here.

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

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

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

セグメンテーションの結果は、次のようにして取得できます。

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

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

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