ML Kit を使用して顔を検出する(iOS)

ML Kit を使用すると、画像や動画内の顔を検出できます。

試してみる

始める前に

  1. Podfile に次の ML Kit Pod を追加します。
    pod 'GoogleMLKit/FaceDetection', '3.2.0'
    
  2. プロジェクトの Pod をインストールまたは更新したら、Xcode プロジェクトを開きます。 .xcworkspace。ML Kit は Xcode バージョン 12.4 以降でサポートされています。

入力画像のガイドライン

顔認証では、サイズが 480x360 ピクセル以上の画像を使用する必要があります。 ML Kit で顔を正確に検出するには、入力画像に顔が含まれている必要があります 十分なピクセルデータで表現されます。一般に、それぞれの顔に 100 x 100 ピクセル以上である必要があります特定の脅威や ML Kit では、顔の輪郭に高精細な入力が求められるため、 200×200 ピクセル以上にします

リアルタイム アプリで顔を検出した場合は、 入力画像の全体的なサイズを考慮します。より小さな画像は 処理が速くなるため、レイテンシを短縮するために低解像度で画像をキャプチャしますが、 上記の精度要件に留意し、 被写体の顔が画像の大部分を占めるようにします。関連項目 リアルタイムのパフォーマンスを改善するためのヒントをご覧ください。

画像のピントが悪い場合も精度に影響することがあります。承認されない場合 ユーザーに画像をキャプチャし直すよう求めます。

カメラに対する顔の向きも、顔の向きや 検出する方法を説明します詳しくは、 顔検出のコンセプト

1. 顔検出機能を構成する

画像に顔検出を適用する前に、 顔検出機能のデフォルト設定を使用する場合は、 FaceDetectorOptions オブジェクト。変更可能 次の設定を行います。

設定
performanceMode fast(デフォルト)|accurate

顔検出の速度と精度を優先します。

landmarkMode none(デフォルト)|all

顔の「ランドマーク」の検出を試みるかどうか 顔、鼻、胸、口など、顔の特徴的な画像情報です。

contourMode none(デフォルト)|all

顔の特徴の輪郭を検出するかどうか。等高線: 検出されたのは最も目立つ顔だけです。

classificationMode none(デフォルト)|all

顔を「笑顔」などのカテゴリに分類するかどうか 「目を開けて」などです。

minFaceSize CGFloat(デフォルト: 0.1

望ましい最小の顔サイズを設定します。これは、顔のサイズの比率で表します。 横のサイズになります。

isTrackingEnabled false(デフォルト)|true

追跡に使用できる ID を顔に割り当てるかどうか 分析できます

なお、輪郭検出が有効になっている場合は、1 つの顔のみが 顔追跡は有用な結果を生成しません。今回 検出速度を上げるには、Contour 両方の 顔認証、顔追跡などの機能です。

たとえば、FaceDetectorOptions を作成します。 オブジェクトを使用します。

Swift

// High-accuracy landmark detection and face classification
let options = FaceDetectorOptions()
options.performanceMode = .accurate
options.landmarkMode = .all
options.classificationMode = .all

// Real-time contour detection of multiple faces
// options.contourMode = .all

Objective-C

// High-accuracy landmark detection and face classification
MLKFaceDetectorOptions *options = [[MLKFaceDetectorOptions alloc] init];
options.performanceMode = MLKFaceDetectorPerformanceModeAccurate;
options.landmarkMode = MLKFaceDetectorLandmarkModeAll;
options.classificationMode = MLKFaceDetectorClassificationModeAll;

// Real-time contour detection of multiple faces
// options.contourMode = MLKFaceDetectorContourModeAll;

2. 入力画像を準備する

画像内の顔を検出するには、画像を UIImage または CMSampleBufferRefFaceDetector にマッピングするには、 process(_:completion:) または results(in:) メソッド:

VisionImageオブジェクトを作成するには、UIImage または CMSampleBuffer

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;
      }
    }
          
  • 次のコマンドを使用して、VisionImage オブジェクトを作成します。 CMSampleBuffer オブジェクトと向き:

    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. FaceDetector のインスタンスを取得する

FaceDetector のインスタンスを取得します。

Swift

let faceDetector = FaceDetector.faceDetector(options: options)

Objective-C

MLKFaceDetector *faceDetector = [MLKFaceDetector faceDetectorWithOptions:options];
      

4. 画像を処理する

次に、画像を process() メソッドに渡します。

Swift

weak var weakSelf = self
faceDetector.process(visionImage) { faces, error in
  guard let strongSelf = weakSelf else {
    print("Self is nil!")
    return
  }
  guard error == nil, let faces = faces, !faces.isEmpty else {
    // ...
    return
  }

  // Faces detected
  // ...
}

Objective-C

[faceDetector processImage:image
                completion:^(NSArray<MLKFace *> *faces,
                             NSError *error) {
  if (error != nil) {
    return;
  }
  if (faces.count > 0) {
    // Recognized faces
  }
}];

5. 検出された顔に関する情報を取得する

顔検出オペレーションが成功すると、顔検出器は配列を渡して Face オブジェクトを完了ハンドラに渡します。各 Face オブジェクトは、画像内で検出された顔を表します。対象 入力画像の境界座標を取得できます。また、顔の 顔検出器で検出するように設定したその他の情報。例:

Swift

for face in faces {
  let frame = face.frame
  if face.hasHeadEulerAngleX {
    let rotX = face.headEulerAngleX  // Head is rotated to the uptoward rotX degrees
  }
  if face.hasHeadEulerAngleY {
    let rotY = face.headEulerAngleY  // Head is rotated to the right rotY degrees
  }
  if face.hasHeadEulerAngleZ {
    let rotZ = face.headEulerAngleZ  // Head is tilted sideways rotZ degrees
  }

  // If landmark detection was enabled (mouth, ears, eyes, cheeks, and
  // nose available):
  if let leftEye = face.landmark(ofType: .leftEye) {
    let leftEyePosition = leftEye.position
  }

  // If contour detection was enabled:
  if let leftEyeContour = face.contour(ofType: .leftEye) {
    let leftEyePoints = leftEyeContour.points
  }
  if let upperLipBottomContour = face.contour(ofType: .upperLipBottom) {
    let upperLipBottomPoints = upperLipBottomContour.points
  }

  // If classification was enabled:
  if face.hasSmilingProbability {
    let smileProb = face.smilingProbability
  }
  if face.hasRightEyeOpenProbability {
    let rightEyeOpenProb = face.rightEyeOpenProbability
  }

  // If face tracking was enabled:
  if face.hasTrackingID {
    let trackingId = face.trackingID
  }
}

Objective-C

for (MLKFace *face in faces) {
  // Boundaries of face in image
  CGRect frame = face.frame;
  if (face.hasHeadEulerAngleX) {
    CGFloat rotX = face.headEulerAngleX;  // Head is rotated to the upward rotX degrees
  }
  if (face.hasHeadEulerAngleY) {
    CGFloat rotY = face.headEulerAngleY;  // Head is rotated to the right rotY degrees
  }
  if (face.hasHeadEulerAngleZ) {
    CGFloat rotZ = face.headEulerAngleZ;  // Head is tilted sideways rotZ degrees
  }

  // If landmark detection was enabled (mouth, ears, eyes, cheeks, and
  // nose available):
  MLKFaceLandmark *leftEar = [face landmarkOfType:FIRFaceLandmarkTypeLeftEar];
  if (leftEar != nil) {
    MLKVisionPoint *leftEarPosition = leftEar.position;
  }

  // If contour detection was enabled:
  MLKFaceContour *upperLipBottomContour = [face contourOfType:FIRFaceContourTypeUpperLipBottom];
  if (upperLipBottomContour != nil) {
    NSArray<MLKVisionPoint *> *upperLipBottomPoints = upperLipBottomContour.points;
    if (upperLipBottomPoints.count > 0) {
      NSLog("Detected the bottom contour of the subject's upper lip.")
    }
  }

  // If classification was enabled:
  if (face.hasSmilingProbability) {
    CGFloat smileProb = face.smilingProbability;
  }
  if (face.hasRightEyeOpenProbability) {
    CGFloat rightEyeOpenProb = face.rightEyeOpenProbability;
  }

  // If face tracking was enabled:
  if (face.hasTrackingID) {
    NSInteger trackingID = face.trackingID;
  }
}

顔の輪郭の例

顔の輪郭検出を有効にすると、顔の輪郭検出に使用されている 検出された顔の特徴を表します。これらの点は、データポイントの形状を 機能。[顔 検出のコンセプトをご覧ください。 表現されます。

次の図は、これらのポイントが顔にどのようにマッピングされるかを示しています。 拡大表示します。

検出された顔の輪郭メッシュの例

リアルタイムの顔検出

リアルタイム アプリケーションで顔検出を使用する場合は、 実現するためのガイドラインは次のとおりです。

  • 次のいずれかを使用するように顔検出器を構成する 顔の輪郭検出または分類とランドマーク検出のどちらか一方のみ:

    輪郭検出
    ランドマーク検出
    分類
    ランドマークの検出と分類
    輪郭検出とランドマーク検出
    輪郭検出と分類
    輪郭検出、ランドマーク検出、分類

  • fast モードを有効にします(デフォルトで有効)。

  • 解像度を下げて画像をキャプチャすることを検討してください。ただし この API の画像サイズの要件。

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