在 iOS 裝置上使用 AutoML 訓練的模型為圖片加上標籤
使用 AutoML Vision Edge 訓練專屬模型後,即可在應用程式中使用該模型為圖片加上標籤。
整合透過 AutoML Vision Edge 訓練的模型有兩種方式。您可以將模型檔案複製到 Xcode 專案中,藉此將模型套裝組合,也可以從 Firebase 動態下載模型。
| 模型搭售方案選項 | |
|---|---|
| 與應用程式一併提供 |
|
| 託管於 Firebase |
|
立即試用
- 請試用範例應用程式,瞭解這個 API 的使用範例。
事前準備
1. 在 Podfile 中加入 ML Kit 程式庫:如要將模型與應用程式一併封裝:
pod 'GoogleMLKit/ImageLabelingAutoML'
LinkFirebase
依附元件:
pod 'GoogleMLKit/ImageLabelingAutoML'
pod 'GoogleMLKit/LinkFirebase'
.xcworkspacecode> 開啟 Xcode 專案。Xcode 13.2.1 以上版本支援 ML Kit。3. 如要下載模型,請務必將 Firebase 新增至 iOS 專案 (如果尚未新增)。如果將模型套裝組合,則不需要這麼做。
1. 載入模型
設定本機模型來源
如要將模型與應用程式組合,請按照下列步驟操作:1. 將從 Firebase 控制台下載的 zip 封存檔解壓縮到資料夾,即可取得模型及其相關中繼資料:
your_model_directory
|____dict.txt
|____manifest.json
|____model.tflite
2. 將資料夾複製到 Xcode 專案,複製時請務必選取「Create folder references」(建立資料夾參照)。這樣一來,模型檔案和中繼資料就會納入應用程式套件,供 ML Kit 使用。
3. 建立
AutoMLImageLabelerLocalModel 物件,指定模型資訊清單檔案的路徑:Swift
guard let manifestPath = Bundle.main.path( forResource: "manifest", ofType: "json", inDirectory: "your_model_directory" ) else { return } let localModel = AutoMLImageLabelerLocalModel(manifestPath: manifestPath)
Objective-C
NSString *manifestPath = [NSBundle.mainBundle pathForResource:@"manifest" ofType:@"json" inDirectory:@"your_model_directory"]; MLKAutoMLImageLabelerLocalModel *localModel = [[MLKAutoMLImageLabelerLocalModel alloc] initWithManifestPath:manifestPath];
設定 Firebase 託管的模型來源
如要使用遠端代管模型,請建立 AutoMLImageLabelerRemoteModel 物件,並指定您發布模型時指派的名稱:
Swift
let remoteModel = AutoMLImageLabelerRemoteModel( name: "your_remote_model" // The name you assigned in // the Firebase console. )
Objective-C
MLKAutoMLImageLabelerRemoteModel *remoteModel = [[MLKAutoMLImageLabelerRemoteModel alloc] initWithName:@"your_remote_model"]; // The name you assigned in // the Firebase console.
接著啟動模型下載工作,並指定允許下載的條件。如果裝置上沒有模型,或是模型有較新版本,工作會從 Firebase 非同步下載模型:
Swift
let downloadConditions = ModelDownloadConditions( allowsCellularAccess: true, allowsBackgroundDownloading: true ) let downloadProgress = ModelManager.modelManager().download( remoteModel, conditions: downloadConditions )
Objective-C
MLKModelDownloadConditions *downloadConditions = [[MLKModelDownloadConditions alloc] initWithAllowsCellularAccess:YES allowsBackgroundDownloading:YES]; NSProgress *downloadProgress = [[MLKModelManager modelManager] downloadModel:remoteModel conditions:downloadConditions];
許多應用程式會在初始化程式碼中啟動下載工作,但您可以在需要使用模型前的任何時間點執行這項操作。
從模型建立圖片標籤器
設定模型來源後,請從其中一個來源建立 ImageLabeler 物件。
如果只有本機綁定的模型,只要從 AutoMLImageLabelerLocalModel 物件建立標籤器,並設定所需的可信度分數門檻即可 (請參閱「評估模型」):
Swift
let options = AutoMLImageLabelerOptions(localModel: localModel) options.confidenceThreshold = NSNumber(value: 0.0) // Evaluate your model in the Firebase console // to determine an appropriate value. let imageLabeler = ImageLabeler.imageLabeler(options: options)
Objective-C
MLKAutoMLImageLabelerOptions *options = [[MLKAutoMLImageLabelerOptions alloc] initWithLocalModel:localModel]; options.confidenceThreshold = @(0.0); // Evaluate your model in the Firebase console // to determine an appropriate value. MLKImageLabeler *imageLabeler = [MLKImageLabeler imageLabelerWithOptions:options];
如果您有遠端代管模型,必須先確認模型已下載,才能執行。您可以使用模型管理工具的 isModelDownloaded(remoteModel:) 方法,檢查模型下載作業的狀態。
雖然您只需要在執行標籤器前確認這項設定,但如果您同時有遠端代管模型和本機綁定的模型,在例項化 ImageLabeler 時執行這項檢查可能會有意義:如果已下載遠端模型,請從該模型建立標籤器,否則請從本機模型建立。
Swift
var options: AutoMLImageLabelerOptions! if (ModelManager.modelManager().isModelDownloaded(remoteModel)) { options = AutoMLImageLabelerOptions(remoteModel: remoteModel) } else { options = AutoMLImageLabelerOptions(localModel: localModel) } options.confidenceThreshold = NSNumber(value: 0.0) // Evaluate your model in the Firebase console // to determine an appropriate value. let imageLabeler = ImageLabeler.imageLabeler(options: options)
Objective-C
MLKAutoMLImageLabelerOptions *options; if ([[MLKModelManager modelManager] isModelDownloaded:remoteModel]) { options = [[MLKAutoMLImageLabelerOptions alloc] initWithRemoteModel:remoteModel]; } else { options = [[MLKAutoMLImageLabelerOptions alloc] initWithLocalModel:localModel]; } options.confidenceThreshold = @(0.0); // Evaluate your model in the Firebase console // to determine an appropriate value. MLKImageLabeler *imageLabeler = [MLKImageLabeler imageLabelerWithOptions:options];
如果只有遠端託管模型,您應停用模型相關功能 (例如將部分 UI 設為灰色或隱藏),直到確認模型已下載為止。
您可以將觀察器附加至預設的通知中心,取得模型下載狀態。請務必在觀察器區塊中使用對 self 的弱參照,因為下載作業可能需要一些時間,而原始物件可能會在下載完成前釋出。例如:
Swift
NotificationCenter.default.addObserver( forName: .mlkitModelDownloadDidSucceed, object: nil, queue: nil ) { [weak self] notification in guard let strongSelf = self, let userInfo = notification.userInfo, let model = userInfo[ModelDownloadUserInfoKey.remoteModel.rawValue] as? RemoteModel, model.name == "your_remote_model" else { return } // The model was downloaded and is available on the device } NotificationCenter.default.addObserver( forName: .mlkitModelDownloadDidFail, object: nil, queue: nil ) { [weak self] notification in guard let strongSelf = self, let userInfo = notification.userInfo, let model = userInfo[ModelDownloadUserInfoKey.remoteModel.rawValue] as? RemoteModel else { return } let error = userInfo[ModelDownloadUserInfoKey.error.rawValue] // ... }
Objective-C
__weak typeof(self) weakSelf = self; [NSNotificationCenter.defaultCenter addObserverForName:MLKModelDownloadDidSucceedNotification object:nil queue:nil usingBlock:^(NSNotification *_Nonnull note) { if (weakSelf == nil | note.userInfo == nil) { return; } __strong typeof(self) strongSelf = weakSelf; MLKRemoteModel *model = note.userInfo[MLKModelDownloadUserInfoKeyRemoteModel]; if ([model.name isEqualToString:@"your_remote_model"]) { // The model was downloaded and is available on the device } }]; [NSNotificationCenter.defaultCenter addObserverForName:MLKModelDownloadDidFailNotification object:nil queue:nil usingBlock:^(NSNotification *_Nonnull note) { if (weakSelf == nil | note.userInfo == nil) { return; } __strong typeof(self) strongSelf = weakSelf; NSError *error = note.userInfo[MLKModelDownloadUserInfoKeyError]; }];
2. 準備輸入圖片
使用 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. 執行圖片標籤器
非同步:
Swift
imageLabeler.process(image) { labels, error in guard error == nil, let labels = labels, !labels.isEmpty else { // Handle the error. return } // Show results. }
Objective-C
[imageLabeler processImage:image completion:^(NSArray*_Nullable labels, NSError *_Nullable error) { if (labels.count == 0) { // Handle the error. return; } // Show results. }];
同步:
Swift
var labels: [ImageLabel] do { labels = try imageLabeler.results(in: image) } catch let error { // Handle the error. return } // Show results.
Objective-C
NSError *error; NSArray*labels = [imageLabeler resultsInImage:image error:&error]; // Show results or handle the error.
4. 取得標示物件的相關資訊
如果圖片標籤作業成功,系統會傳回ImageLabel 陣列。每個 ImageLabel 都代表圖片中標示的項目。您可以取得每個標籤的文字說明 (如果 TensorFlow Lite 模型檔案的中繼資料提供這項資訊)、信賴分數和索引。例如:Swift
for label in labels { let labelText = label.text let confidence = label.confidence let index = label.index }
Objective-C
for (MLKImageLabel *label in labels) { NSString *labelText = label.text; float confidence = label.confidence; NSInteger index = label.index; }
提升即時成效的訣竅
如要在即時應用程式中標記圖片,請遵循下列指南,盡可能提高影格速率:
- 如要處理影片影格,請使用偵測器的
results(in:)同步 API。從AVCaptureVideoDataOutputSampleBufferDelegate的captureOutput(_, didOutput:from:)函式呼叫這個方法,即可從指定影片影格同步取得結果。將AVCaptureVideoDataOutput的alwaysDiscardsLateVideoFrames設為true,以節流對偵測器的呼叫。如果偵測器執行期間有新的視訊影格可用,系統會捨棄該影格。 - 如果使用偵測器的輸出內容,在輸入圖片上疊加圖像,請先從 ML Kit 取得結果,然後在單一步驟中算繪圖片並疊加圖像。這樣一來,每個處理過的輸入影格只會轉譯到顯示表面一次。如需範例,請參閱 ML Kit 快速入門範例中的 updatePreviewOverlayViewWithLastFrame。