「臉部偵測器」工作可讓你偵測圖片或影片中的臉孔。您可以使用這項工作找出影格中的臉孔和臉部特徵。這項工作使用的機器學習 (ML) 模型搭配單一圖片或連續圖片串流。此工作會輸出臉部位置及下列臉部關鍵點:左眼、右眼、鼻子小費、嘴巴、左眼間移動和右眼視角。
您可以前往 GitHub 取得這些操作說明中提及的程式碼範例。如要查看這項工作的實際運作情形,請參閱此網路示範。如要進一步瞭解這項工作的功能、模型和設定選項,請參閱總覽。
程式碼範例
MediaPipe Tasks 範例程式碼是 iOS 版臉部偵測器應用程式的簡易實作方式。這個範例使用 Android 實體裝置的相機,偵測連續影片串流中的臉孔。應用程式也可以從裝置圖片庫偵測圖片和影片中的臉孔。
您可以將該應用程式做為開發 iOS 應用程式的起點,也可以在修改現有應用程式時參照。臉部偵測器範例程式碼由 GitHub 代管。
下載程式碼
以下操作說明說明如何使用 git 指令列工具建立範例程式碼的本機副本。
如要下載範例程式碼,請按照下列步驟操作:
使用下列指令複製 Git 存放區:
git clone https://github.com/google-ai-edge/mediapipe-samples
您可以選擇將 Git 執行個體設為使用稀疏檢查,因此只有臉部偵測器範例應用程式的檔案:
cd mediapipe git sparse-checkout init --cone git sparse-checkout set examples/face_detector/ios/
建立範例程式碼的本機版本後,可以安裝 MediaPipe 工作程式庫,使用 Xcode 開啟專案並執行應用程式。如需操作說明,請參閱 iOS 設定指南。
重要元件
下列檔案包含臉部偵測器範例應用程式的重要程式碼:
- FaceDetectorService.swift:初始化偵測工具、處理模型選取作業,並針對輸入資料執行推論。
- CameraViewController:為即時攝影機畫面輸入模式實作 UI,並以視覺化方式呈現偵測結果。
- MediaLibraryViewController.swift:實作靜態圖片和影片檔案輸入模式的 UI,並以視覺化方式呈現偵測結果。
設定
本節說明設定開發環境及程式碼專案,以使用臉部偵測器的重要步驟。如需瞭解如何設定開發環境以使用 MediaPipe 工作 (包括平台版本需求),請參閱「iOS 設定指南」。
依附元件
臉部偵測器會使用 MediaPipeTasksVision
程式庫,因此您必須使用 CocoaPods 安裝這個程式庫。這個程式庫與 Swift 和 Objective-C 應用程式相容,不需要任何其他語言的特定設定。
如需在 macOS 上安裝 CocoaPods 的操作說明,請參閱 CocoaPods 安裝指南。
如要瞭解如何建立具有應用程式必要 Pod 的 Podfile
,請參閱「使用 CocoaPods」。
使用下列程式碼,在 Podfile
中新增 MediaPipeTasksVision Pod:
target 'MyFaceDetectorApp' do
use_frameworks!
pod 'MediaPipeTasksVision'
end
如果您的應用程式含有單元測試目標,請參閱 iOS 設定指南,進一步瞭解如何設定 Podfile
。
型號
MediaPipe 臉部偵測器工作所需的已訓練模型與這項工作相容。如要進一步瞭解臉部偵測器的可用已訓練模型,請參閱工作總覽「模型」一節。
選取並下載模型,然後使用 Xcode 將其新增至專案目錄。 如需將檔案新增至 Xcode 專案的操作說明,請參閱「管理 Xcode 專案中的檔案和資料夾」。
使用 BaseOptions.modelAssetPath
屬性指定應用程式套件中的模型路徑。如需程式碼範例,請參閱下一節。
建立工作
如要建立臉部偵測器工作,請呼叫其中一個初始化器。FaceDetector(options:)
初始化器會接受設定選項的值。
如果不需要以自訂設定選項初始化的臉部偵測器,可以使用 FaceDetector(modelPath:)
初始化器,透過預設選項建立臉部偵測器。如要進一步瞭解設定選項,請參閱「設定總覽」。
臉部偵測器工作支援 3 種輸入資料類型:靜態圖片、影片檔案和即時影片串流。根據預設,FaceDetector(modelPath:)
會初始化靜態圖片的工作。如果想將工作初始化,以便處理影片檔案或直播影片串流,請使用 FaceDetector(options:)
指定影片或直播執行模式。直播模式也需要額外的 faceDetectorLiveStreamDelegate
設定選項,讓臉部偵測器能夠以非同步方式將臉部偵測結果傳送給委派代表。
請選擇與執行模式對應的分頁,瞭解如何建立工作並執行推論。
Swift
圖片
import MediaPipeTasksVision let modelPath = Bundle.main.path(forResource: "model", ofType: "tflite") let options = FaceDetectorOptions() options.baseOptions.modelAssetPath = modelPath options.runningMode = .image let faceDetector = try FaceDetector(options: options)
影片
import MediaPipeTasksVision let modelPath = Bundle.main.path(forResource: "model", ofType: "tflite") let options = FaceDetectorOptions() options.baseOptions.modelAssetPath = modelPath options.runningMode = .video let faceDetector = try FaceDetector(options: options)
直播
import MediaPipeTasksVision // Class that conforms to the `FaceDetectorLiveStreamDelegate` protocol and // implements the method that the face detector calls once it finishes // detecting faces in each input frame. class FaceDetectorResultProcessor: NSObject, FaceDetectorLiveStreamDelegate { func faceDetector( _ faceDetector: FaceDetector, didFinishDetection result: FaceDetectorResult?, timestampInMilliseconds: Int, error: Error?) { // Process the face detection result or errors here. } } let modelPath = Bundle.main.path( forResource: "model", ofType: "tflite") let options = FaceDetectorOptions() options.baseOptions.modelAssetPath = modelPath options.runningMode = .liveStream // Assign an object of the class to the `faceDetectorLiveStreamDelegate` // property. let processor = FaceDetectorResultProcessor() options.faceDetectorLiveStreamDelegate = processor let faceDetector = try FaceDetector(options: options)
Objective-C
圖片
@import MediaPipeTasksVision; NSString *modelPath = [[NSBundle mainBundle] pathForResource:@"model" ofType:@"tflite"]; MPPFaceDetectorOptions *options = [[MPPFaceDetectorOptions alloc] init]; options.baseOptions.modelAssetPath = modelPath; options.runningMode = MPPRunningModeImage; MPPFaceDetector *faceDetector = [[MPPFaceDetector alloc] initWithOptions:options error:nil];
影片
@import MediaPipeTasksVision; NSString *modelPath = [[NSBundle mainBundle] pathForResource:@"model" ofType:@"tflite"]; MPPFaceDetectorOptions *options = [[MPPFaceDetectorOptions alloc] init]; options.baseOptions.modelAssetPath = modelPath; options.runningMode = MPPRunningModeVideo; MPPFaceDetector *faceDetector = [[MPPFaceDetector alloc] initWithOptions:options error:nil];
直播
@import MediaPipeTasksVision; // Class that conforms to the `MPPFaceDetectorLiveStreamDelegate` protocol // and implements the method that the face detector calls once it finishes // detecting faces in each input frame. @interface APPFaceDetectorResultProcessor : NSObject@end @implementation APPFaceDetectorResultProcessor - (void)faceDetector:(MPPFaceDetector *)faceDetector didFinishDetectionWithResult:(MPPFaceDetectorResult *)faceDetectorResult timestampInMilliseconds:(NSInteger)timestampInMilliseconds error:(NSError *)error { // Process the face detector result or errors here. } @end NSString *modelPath = [[NSBundle mainBundle] pathForResource:@"model" ofType:@"tflite"]; MPPFaceDetectorOptions *options = [[MPPFaceDetectorOptions alloc] init]; options.baseOptions.modelAssetPath = modelPath; options.runningMode = MPPRunningModeLiveStream; // Assign an object of the class to the `faceDetectorLiveStreamDelegate` // property. APPFaceDetectorResultProcessor *processor = [APPFaceDetectorResultProcessor new]; options.faceDetectorLiveStreamDelegate = processor; MPPFaceDetector *faceDetector = [[MPPFaceDetector alloc] initWithOptions:options error:nil];
注意:如果您使用影片模式或直播模式,臉部偵測器會使用追蹤功能,避免在每個影格觸發偵測模型,有助於縮短延遲時間。
設定選項
這項工作的 iOS 應用程式設定選項如下:
選項名稱 | 說明 | 值範圍 | 預設值 |
---|---|---|---|
runningMode |
設定工作的執行模式。共有三種模式: IMAGE:單一圖片輸入的模式。 影片:影片已解碼影格的模式。 LIVE_STREAM:輸入資料串流 (例如攝影機) 的直播模式。在這個模式下,必須呼叫 resultListener 才能設定事件監聽器,以非同步方式接收結果。 |
{RunningMode.image, RunningMode.video, RunningMode.liveStream } |
RunningMode.image |
minDetectionConfidence |
系統會將臉部偵測判定為成功的最低可信度分數。 | Float [0,1] |
0.5 |
minSuppressionThreshold |
系統會將臉部偵測判定為重疊的非最大抑制門檻。 | Float [0,1] |
0.3 |
直播設定
執行模式設為直播時,臉部偵測器需要額外的 faceDetectorLiveStreamDelegate
設定選項,讓臉部偵測器以非同步方式提供偵測結果。委派項目會實作 faceDetector(_:didFinishDetection:timestampInMilliseconds:error:)
方法,臉部偵測器會在處理每個影格的臉部偵測結果後呼叫此方法。
選項名稱 | 說明 | 值範圍 | 預設值 |
---|---|---|---|
faceDetectorLiveStreamDelegate |
啟用臉部偵測器,在直播模式下以非同步方式接收臉部偵測結果。執行個體設為此屬性的類別必須實作 faceDetector(_:didFinishDetection:timestampInMilliseconds:error:) 方法。 |
不適用 | 未設定 |
準備資料
您必須先將輸入圖片或框架轉換為 MPImage
物件,才能將其傳送至臉部偵測器。MPImage
支援不同類型的 iOS 圖片格式,且可在任何執行模式下用於推論。如要進一步瞭解 MPImage
,請參閱 MPImage API。
依據您的用途和應用程式所需的執行模式選擇 iOS 圖片格式。MPImage
接受 UIImage
、CVPixelBuffer
和 CMSampleBuffer
iOS 圖片格式。
UIImage
UIImage
格式非常適合下列執行模式:
圖片:應用程式套件、使用者圖片庫或檔案系統格式的圖片,可以轉換為
MPImage
物件。UIImage
影片:使用 AVAssetImageGenerator 將影片影格擷取為 CGImage 格式,然後轉換為
UIImage
圖片。
Swift
// Load an image on the user's device as an iOS `UIImage` object. // Convert the `UIImage` object to a MediaPipe's Image object having the default // orientation `UIImage.Orientation.up`. let image = try MPImage(uiImage: image)
Objective-C
// Load an image on the user's device as an iOS `UIImage` object. // Convert the `UIImage` object to a MediaPipe's Image object having the default // orientation `UIImageOrientationUp`. MPImage *image = [[MPPImage alloc] initWithUIImage:image error:nil];
這個範例會使用預設的 UIImage.Orientation.Up 方向初始化 MPImage
。您可以使用任何支援的 UIImage.Orientation 值初始化 MPImage
。臉部偵測器不支援鏡像方向,例如 .upMirrored
、.downMirrored
、.leftMirrored
、.rightMirrored
。
如要進一步瞭解 UIImage
,請參閱「UIImage Apple Developer 說明文件」。
CVPixelBuffer
CVPixelBuffer
格式非常適合產生影格以及使用 iOS CoreImage 架構處理的應用程式。
CVPixelBuffer
格式非常適合下列執行模式:
圖片:在使用 iOS 的
CoreImage
架構進行某些處理後產生CVPixelBuffer
圖片的應用程式,可透過圖片執行模式傳送至臉部偵測工具。影片:您可以將影片影格轉換為
CVPixelBuffer
格式進行處理,接著將其傳送至影片模式的臉部偵測器。直播:使用 iOS 相機產生影格的應用程式可能會先轉換為
CVPixelBuffer
格式進行處理,再傳送至直播模式下的臉部偵測器。
Swift
// Obtain a CVPixelBuffer. // Convert the `CVPixelBuffer` object to a MediaPipe's Image object having the default // orientation `UIImage.Orientation.up`. let image = try MPImage(pixelBuffer: pixelBuffer)
Objective-C
// Obtain a CVPixelBuffer. // Convert the `CVPixelBuffer` object to a MediaPipe's Image object having the // default orientation `UIImageOrientationUp`. MPImage *image = [[MPPImage alloc] initWithUIImage:image error:nil];
如要進一步瞭解 CVPixelBuffer
,請參閱 CVPixelBuffer Apple 開發人員說明文件。
CMSampleBuffer
CMSampleBuffer
格式可儲存統一媒體類型的媒體樣本,非常適合用於直播執行模式。iOS 相機的即時影格會由 iOS AVCaptureVideoDataOutput 以 CMSampleBuffer
格式非同步傳送。
Swift
// Obtain a CMSampleBuffer. // Convert the `CMSampleBuffer` object to a MediaPipe's Image object having the default // orientation `UIImage.Orientation.up`. let image = try MPImage(sampleBuffer: sampleBuffer)
Objective-C
// Obtain a `CMSampleBuffer`. // Convert the `CMSampleBuffer` object to a MediaPipe's Image object having the // default orientation `UIImageOrientationUp`. MPImage *image = [[MPPImage alloc] initWithSampleBuffer:sampleBuffer error:nil];
如要進一步瞭解 CMSampleBuffer
,請參閱 CMSampleBuffer Apple 開發人員說明文件。
執行工作
如要執行臉部偵測器,請使用已指派的執行模式專屬的 detect()
方法:
- 靜態圖片:
detect(image:)
- 影片:《
detect(videoFrame:timestampInMilliseconds:)
》 - 直播:
detectAsync(image:timestampInMilliseconds:)
臉部偵測器傳回在輸入圖片或頁框中偵測到的臉孔。
以下程式碼範例顯示如何在這些不同的執行模式中執行臉部偵測器的簡易範例:
Swift
圖片
let result = try faceDetector.detect(image: image)
影片
let result = try faceDetector.detect( videoFrame: image, timestampInMilliseconds: timestamp)
直播
try faceDetector.detectAsync( image: image, timestampInMilliseconds: timestamp)
Objective-C
圖片
MPPFaceDetectorResult *result = [faceDetector detectInImage:image error:nil];
影片
MPPFaceDetectorResult *result = [faceDetector detectInVideoFrame:image timestampInMilliseconds:timestamp error:nil];
直播
BOOL success = [faceDetector detectAsyncInImage:image timestampInMilliseconds:timestamp error:nil];
臉部偵測器程式碼範例會顯示這些模式的實作,詳細說明 detect(image:)
、detect(videoFrame:timestampInMilliseconds:)
和 detectAsync(image:timestampInMilliseconds:)
。範例程式碼可讓使用者切換不同的處理模式,但您的用途可能不需要這些模式。
注意事項:
以影片模式或直播模式執行時,您必須在臉部偵測器工作中提供輸入影格的時間戳記。
以圖片或影片模式執行時,臉部偵測器工作會封鎖目前的執行緒,直到處理完成輸入圖片或影格為止。為避免封鎖目前的執行緒,請使用 iOS Dispatch 或 NSOperation 架構在背景執行緒中執行處理作業。
以直播模式執行時,臉部偵測器工作會立即傳回,且不會封鎖目前的執行緒。會在處理每個輸入影格後,使用臉部偵測結果叫用
faceDetector(_:didFinishDetection:timestampInMilliseconds:error:)
方法。臉部偵測器會在專屬的序列調度佇列上,以非同步方式叫用這個方法。如要在使用者介面上顯示結果,請在處理結果後將結果分派到主佇列。如果在臉部偵測器工作忙於處理其他影格時呼叫detectAsync
函式,臉部偵測器會忽略新的輸入影格。
處理並顯示結果
執行推論時,臉部偵測工作會傳回 FaceDetectorResult
物件,其中包含偵測到臉孔的定界框,以及每個偵測到的臉孔可信度分數。
以下為這項工作的輸出資料範例:
FaceDetectionResult:
Detections:
Detection #0:
BoundingBox:
origin_x: 126
origin_y: 100
width: 463
height: 463
Categories:
Category #0:
index: 0
score: 0.9729152917861938
NormalizedKeypoints:
NormalizedKeypoint #0:
x: 0.18298381567001343
y: 0.2961040139198303
NormalizedKeypoint #1:
x: 0.3302789330482483
y: 0.29289937019348145
... (6 keypoints for each face)
Detection #1:
BoundingBox:
origin_x: 616
origin_y: 193
width: 430
height: 430
Categories:
Category #0:
index: 0
score: 0.9251380562782288
NormalizedKeypoints:
NormalizedKeypoint #0:
x: 0.6151331663131714
y: 0.3713381886482239
NormalizedKeypoint #1:
x: 0.7460576295852661
y: 0.38825345039367676
... (6 keypoints for each face)
下圖以視覺化方式呈現工作輸出內容:
如果圖片沒有定界框,請參閱原始圖片。
臉部偵測器範例程式碼示範如何顯示結果。詳情請參閱程式碼範例。