ML Kit 提供最佳化的 SDK 來區隔自拍照。自拍區隔素材資源在建構期間會以靜態方式連結至您的應用程式。這會造成應用程式大小增加至 24 MB,且 API 延遲時間也會因輸入的圖片大小而異約 7 毫秒,甚至約 12 毫秒 (根據 iPhone X 的測量結果而定)。
立即體驗
- 試試範例應用程式,查看這個 API 的使用範例。
事前準備
在 Podfile 中加入下列 ML Kit 程式庫:
pod 'GoogleMLKit/SegmentationSelfie', '3.2.0'
安裝或更新專案的 Pod 後,請使用該專案的 .
xcworkspace
開啟 Xcode 專案。Xcode 13.2.1 以上版本支援 ML Kit。
1. 建立區隔器執行個體
如要對自拍圖片執行區隔,請先建立含有 SelfieSegmenterOptions
的 Segmenter
執行個體,並視需要指定區隔設定。
區隔選項
分段模式
Segmenter
會在兩種模式下運作。請務必選擇符合您用途的方案。
STREAM_MODE (default)
這個模式是用來串流播放影片或相機畫面。在這個模式下,區隔器會運用先前影格的結果,傳回更順暢的區隔結果。
SINGLE_IMAGE_MODE (default)
這個模式適用於無關的單一圖片。在這個模式中,區隔器會分別處理每張圖片,不會平滑地處理畫面。
啟用原始大小遮罩
要求區隔器傳回與模型輸出大小相符的原始大小遮罩。
原始遮罩大小 (例如 256x256) 通常小於輸入的圖片大小。
如果不指定這個選項,區隔器就會根據輸入的圖片大小重新調整原始遮罩。如果您想套用自訂的縮放邏輯,或者您的用途不需要重新調整大小,建議您使用這個選項。
指定區隔選項:
Swift
let options = SelfieSegmenterOptions() options.segmenterMode = .singleImage options.shouldEnableRawSizeMask = true
Objective-C
MLKSelfieSegmenterOptions *options = [[MLKSelfieSegmenterOptions alloc] init]; options.segmenterMode = MLKSegmenterModeSingleImage; options.shouldEnableRawSizeMask = YES;
最後,取得 Segmenter
的執行個體。傳送您指定的選項:
Swift
let segmenter = Segmenter.segmenter(options: options)
Objective-C
MLKSegmenter *segmenter = [MLKSegmenter segmenterWithOptions:options];
2. 準備輸入圖片
如要分段自拍影片,請對每張圖片或影片畫面執行下列動作。
如果啟用串流模式,就必須從 CMSampleBuffer
建立 VisionImage
物件。
使用 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. 處理圖片
將 VisionImage
物件傳遞至 Segmenter
的其中一種圖片處理方法。您可以使用非同步 process(image:)
方法或同步 results(in:)
方法。
如何同步對自拍圖片進行區隔:
Swift
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.
Objective-C
NSError *error; MLKSegmentationMask *mask = [segmenter resultsInImage:image error:&error]; if (error != nil) { // Error. return; } // Success. Get a segmentation mask here.
如何以非同步的方式對自拍照進行區隔:
Swift
segmenter.process(image) { mask, error in guard error == nil else { // Error. return } // Success. Get a segmentation mask here.
Objective-C
[segmenter processImage:image completion:^(MLKSegmentationMask * _Nullable mask, NSError * _Nullable error) { if (error != nil) { // Error. return; } // Success. Get a segmentation mask here. }];
4. 取得區隔遮罩
您可以按照以下方式取得區隔結果:
Swift
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 }
Objective-C
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 獲得準確的區隔結果,圖片必須至少為 256x256 像素。
- 如果您在即時應用程式中執行自拍照區隔,建議您一併考量輸入圖片的整體尺寸。縮小了圖片的處理速度較快,因此為了縮短延遲時間,請以較低解析度拍攝圖片,但請留意上述的解析度規定,並確保主題盡可能佔據圖片比例。
- 圖片對焦不佳也可能會影響準確度。如果無法取得可接受的圖片,請要求使用者重新拍照。
如果您想在即時應用程式中使用區隔功能,請遵循下列指南來達成最佳影格速率:
- 使用
stream
區隔模式。 - 建議你拍攝解析度較低的圖片。不過,也請留意這個 API 的圖片尺寸規定。
- 如要處理影片影格,請使用區隔器的
results(in:)
同步 API。從 AVCaptureVideoDataOutputSampleBufferDelegate 的 captureOutput(_, didOutput:from:) 函式呼叫這個方法,以同步從指定的影片影格取得結果。將 AVCaptureVideoDataOutput 的 alwaysDiscardsLateVideoFrames 設為 true,以限制對區隔器發出的呼叫。如果該片段執行時出現新的影片影格,系統會捨棄該影格。 - 如果使用區隔的輸出內容,在輸入圖片上疊加圖像,請先透過 ML Kit 取得結果,然後透過單一步驟算繪圖片和重疊結果。如此一來,每個已處理的輸入影格都只會轉譯一次螢幕介面一次。如需範例,請參閱 ML Kit 快速入門導覽課程範例中的 previewOverlayView 和 CameraViewController 類別。