您可以使用機器學習套件偵測圖片和影片中的臉孔。
立即體驗
事前準備
- 在 Podfile 中加入下列機器學習套件 Pod:
pod 'GoogleMLKit/FaceDetection', '3.2.0'
- 安裝或更新專案的 Pod 後,使用
.xcworkspace
開啟 Xcode 專案。Xcode 12.4 以上版本支援機器學習套件。
輸入圖片規範
辨識臉部時,請使用大小至少為 480x360 像素的圖片。 為了讓機器學習套件準確偵測臉部,輸入圖片必須包含以足夠像素資料呈現的臉孔。一般而言,您想要在圖片中偵測的臉孔大小至少須為 100x100 像素。如要偵測臉部的輪廓,機器學習套件需提供高解析度的輸入值:每個臉孔至少須為 200x200 像素。
如果在即時應用程式中偵測臉孔,建議您考慮輸入圖片的整體尺寸。較小的圖片處理速度較快,因此能縮短延遲時間、以較低解析度擷取圖片,但請留意上述的準確率要求,並盡量讓拍攝主體的臉孔佔滿圖片。另請參閱改善即時效能的訣竅。
圖片品質不佳也可能會影響準確率。如果未收到可接受的結果,請要求使用者擷取圖片。
臉部相對於臉部的方向也可能影響機器學習套件偵測到的臉部特徵。請參閱臉部偵測概念一文。
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. 準備輸入圖片
如要偵測圖片中的臉孔,請使用process(_:completion:)
或 results(in:)
方法,將圖片以 UIImage
或 CMSampleBufferRef
的形式傳送至 FaceDetector
:
使用 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. 取得 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 取得結果,然後透過單一步驟算繪圖像和疊加層。如此一來,每個處理的輸入影格只會轉譯一次到顯示途徑一次。如需範例,請參閱 ML Kit 快速入門導覽課程範例中的 updatePreviewOverlayViewWithLastFrame。