在 iOS 上使用 ML Kit 偵測臉部

你可以使用 ML Kit 偵測圖片和影片中的臉孔。

立即試用

事前準備

  1. 在 Podfile 中加入下列 ML Kit Pod:
    pod 'GoogleMLKit/FaceDetection', '3.2.0'
    
  2. 安裝或更新專案的 Pod 後,請使用 .xcworkspace。Xcode 12.4 以上版本支援 ML Kit。

輸入圖片規範

如要使用臉部辨識功能,圖片尺寸應至少設為 480x360 像素。 為了讓 ML Kit 準確偵測臉孔,輸入圖片必須包含臉孔 以充足的像素資料表示基本上, 至少需要 100x100 像素如要偵測 臉部輪廓線,則 ML Kit 需要較高的解析度輸入: 至少應為 200 x 200 像素。

如果您在即時應用程式中偵測到臉孔,您可能還需要 將輸入圖片的整體尺寸納入考量較小的圖片 加快處理速度,因此為了縮短延遲時間,擷取解析度較低的圖片 著重於上述準確率規定,並確保 拍攝主體的臉孔會盡量佔滿圖片。另請參閱 即時效能改善訣竅

圖像對焦品質不佳也可能會影響準確度。如果沒有接受 結果,請要求使用者重新擷取圖片。

臉部與相機相對的方向也會影響臉部表情 ML Kit 偵測到的特徵詳情請見 臉部偵測概念

1. 設定臉部偵測工具

為圖像套用臉部偵測功能之前,如果想變更 臉部偵測器的預設設定,請用 FaceDetectorOptions 物件。您可以 以下設定:

設定
performanceMode fast (預設) |accurate

改善偵測臉孔的速度或精確度。

landmarkMode none (預設) |all

是否要嘗試偵測臉部「地標」—對 偵測到的臉孔、鼻子、臉頰、嘴巴。

contourMode none (預設) |all

是否偵測臉部特徵的輪廓。輪廓線是 只會偵測到圖片中最醒目的臉孔。

classificationMode none (預設) |all

是否將臉孔分類 (例如「微笑」) 和「睜開雙眼」

minFaceSize CGFloat (預設:0.1)

設定所需的最小臉孔尺寸,以 標題與圖片寬度的寬度

isTrackingEnabled false (預設) |true

是否要指派臉孔 ID,以用於追蹤 圖像中的人物臉孔。

請注意,啟用輪廓偵測功能後,只有一張臉孔 因此臉部追蹤功能無法產生實用的結果。為此 原因及加快偵測速度,請勿同時啟用兩個輪廓線 偵測及臉部追蹤

例如,建構 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. 準備輸入圖片

如要偵測圖片中的臉孔,請將圖片以 UIImageCMSampleBufferRefFaceDetector process(_:completion:)results(in:) 方法:

使用 UIImageVisionImage 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 captureOutput(_, didOutput:from:) 函式,以同步方式取得指定影片的結果 相框。保留 AVCaptureVideoDataOutput alwaysDiscardsLateVideoFrames 做為 true,以限制對偵測工具的呼叫。如果是 影格的畫面,就會遭到捨棄。
  • 如果使用偵測工具的輸出內容將圖像重疊 先從 ML Kit 取得結果,然後算繪圖片 並疊加單一步驟這麼一來,您的應用程式就會算繪到顯示途徑 每個處理的輸入影格只會產生一次請參閱 updatePreviewOverlayViewWithLastFrame 也可以查看一個範例