機器學習套件提供用於最佳化區隔的最佳化 SDK。「自拍區隔器」素材資源會在建構期間以靜態方式連結至您的應用程式。這樣可將應用程式大小增加至 24MB,且根據 iPhone X 測得的輸入大小,API 延遲時間可能介於 7 毫秒到 12 毫秒之間。
立即體驗
- 請試用範例應用程式,查看這個 API 的使用範例。
事前準備
在 Podfile 中加入下列機器學習套件程式庫:
pod 'GoogleMLKit/SegmentationSelfie', '3.2.0'
安裝或更新專案的 Pod 後,請使用 .
xcworkspace
開啟 Xcode 專案。Xcode 13.2.1 以上版本支援機器學習套件。
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(_, doesOutput:from:) 函式呼叫此方法,以同步取得指定影片影格的結果。將 AVCaptureVideoDataOutput 的 alwaysDropsLateVideoFrames 保留為 true,以保護對區隔器的呼叫。如果在執行區隔時有可用的新影格,系統就會捨棄該影格。 - 如果您使用區隔器的輸出結果,在輸入圖片上重疊圖像,請先透過 ML Kit 取得結果,再透過單一步驟顯示圖像和疊加層。如此一來,每個處理的輸入影格只會轉譯一次到顯示途徑一次。請參閱 ML Kit 快速入門導覽課程範例中的 previewOverlayView 和 CameraViewController 類別。