使用 AutoML Vision Edge 自行訓練模型後,即可在應用程式中使用模型為圖片加上標籤。
事前準備
- 如果您尚未將 Firebase 加入應用程式,請按照入門指南中的步驟進行。
- 在 Podfile 中加入 ML Kit 程式庫:
pod 'Firebase/MLVision', '6.25.0' pod 'Firebase/MLVisionAutoML', '6.25.0'
安裝或更新專案的 Pod 後,請務必使用.xcworkspace
開啟 Xcode 專案。 - 在應用程式中匯入 Firebase:
Swift
import Firebase
Objective-C
@import Firebase;
1. 載入模型
ML Kit 會在裝置上執行 AutoML 產生的模型。不過,您可以設定 ML Kit,藉此從 Firebase 或/或本機儲存空間遠端載入模型。
在 Firebase 上託管模型之後,您就能在不發布新的應用程式版本的情況下更新模型,也能使用遠端設定和 A/B 測試功能,動態提供不同的模型給不同的使用者組。
如果您選擇只透過 Firebase 代管模型,不將其與應用程式組合在一起,可以縮減應用程式的初始下載大小。不過,請注意,如果應用程式未搭配應用程式,就無法使用任何模型相關功能,直到應用程式首次下載該模型為止。
透過整合模型與應用程式,確保在 Firebase 託管模型無法使用時,應用程式的機器學習功能仍可正常運作。
設定 Firebase 託管的模型來源
如要使用遠端託管的模型,請建立 AutoMLRemoteModel
物件,並指定您發布模型時指派的名稱:
Swift
let remoteModel = AutoMLRemoteModel(
name: "your_remote_model" // The name you assigned in the Firebase console.
)
Objective-C
FIRAutoMLRemoteModel *remoteModel = [[FIRAutoMLRemoteModel 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
FIRModelDownloadConditions *downloadConditions =
[[FIRModelDownloadConditions alloc] initWithAllowsCellularAccess:YES
allowsBackgroundDownloading:YES];
NSProgress *downloadProgress =
[[FIRModelManager modelManager] downloadRemoteModel:remoteModel
conditions:downloadConditions];
許多應用程式會在初始化程式碼中啟動下載工作,但在需要使用模型前,您可以隨時執行此操作。
設定本機模型來源
將模型與應用程式組合如下:
- 將從 Firebase 控制台下載的 ZIP 封存檔中,將模型及其中繼資料擷取至資料夾:
your_model_directory |____dict.txt |____manifest.json |____model.tflite
這三個檔案都必須位於同一個資料夾中。建議您使用下載的檔案,不要修改 (包含檔案名稱)。 - 將資料夾複製到 Xcode 專案,並在刪除時小心選取「Create folder reference」。模型檔案和中繼資料會包含在應用程式套件中,並可供 ML Kit 使用。
- 建立
AutoMLLocalModel
物件,指定模型資訊清單檔案的路徑:Swift
guard let manifestPath = Bundle.main.path( forResource: "manifest", ofType: "json", inDirectory: "your_model_directory" ) else { return true } let localModel = AutoMLLocalModel(manifestPath: manifestPath)
Objective-C
NSString *manifestPath = [NSBundle.mainBundle pathForResource:@"manifest" ofType:@"json" inDirectory:@"your_model_directory"]; FIRAutoMLLocalModel *localModel = [[FIRAutoMLLocalModel alloc] initWithManifestPath:manifestPath];
從模型建立圖片標籤工具
設定模型來源後,請從其中一個建立 VisionImageLabeler
物件。
如果您只有本機組合模型,只需透過 AutoMLLocalModel
物件建立標籤人員,並設定所需的可信度分數門檻即可 (請參閱評估模型):
Swift
let options = VisionOnDeviceAutoMLImageLabelerOptions(localModel: localModel)
options.confidenceThreshold = 0 // Evaluate your model in the Firebase console
// to determine an appropriate value.
let labeler = Vision.vision().onDeviceAutoMLImageLabeler(options: options)
Objective-C
FIRVisionOnDeviceAutoMLImageLabelerOptions *options =
[[FIRVisionOnDeviceAutoMLImageLabelerOptions alloc] initWithLocalModel:localModel];
options.confidenceThreshold = 0; // Evaluate your model in the Firebase console
// to determine an appropriate value.
FIRVisionImageLabeler *labeler =
[[FIRVision vision] onDeviceAutoMLImageLabelerWithOptions:options];
如果您有遠端託管的模型,必須先檢查是否已下載過該模型,才能執行。您可以使用模型管理員的 isModelDownloaded(remoteModel:)
方法,查看模型下載工作的狀態。
雖然您只需要在執行標籤人員前確認這點,但如果您同時擁有遠端託管的模型和本機組合模型,那麼在將 VisionImageLabeler
執行個體化時,可能很適合執行這項檢查:從遠端模型 (如果已下載) 建立標籤器;如果不是,則會從本機模型建立標籤器。
Swift
var options: VisionOnDeviceAutoMLImageLabelerOptions?
if (ModelManager.modelManager().isModelDownloaded(remoteModel)) {
options = VisionOnDeviceAutoMLImageLabelerOptions(remoteModel: remoteModel)
} else {
options = VisionOnDeviceAutoMLImageLabelerOptions(localModel: localModel)
}
options.confidenceThreshold = 0 // Evaluate your model in the Firebase console
// to determine an appropriate value.
let labeler = Vision.vision().onDeviceAutoMLImageLabeler(options: options)
Objective-C
VisionOnDeviceAutoMLImageLabelerOptions *options;
if ([[FIRModelManager modelManager] isModelDownloaded:remoteModel]) {
options = [[FIRVisionOnDeviceAutoMLImageLabelerOptions alloc] initWithRemoteModel:remoteModel];
} else {
options = [[FIRVisionOnDeviceAutoMLImageLabelerOptions alloc] initWithLocalModel:localModel];
}
options.confidenceThreshold = 0.0f; // Evaluate your model in the Firebase console
// to determine an appropriate value.
FIRVisionImageLabeler *labeler = [[FIRVision vision] onDeviceAutoMLImageLabelerWithOptions:options];
如果您只有遠端託管的模型,請在確認下載模型之前,停用模型相關功能,例如將 UI 顯示為灰色或隱藏。
您可以將觀察器附加至預設通知中心,藉此取得模型下載狀態。由於下載可能需要一點時間,並在下載完成後釋出原始物件,因此請務必在觀察器區塊中使用調整的 self
參照。例如:
Swift
NotificationCenter.default.addObserver( forName: .firebaseMLModelDownloadDidSucceed, 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: .firebaseMLModelDownloadDidFail, 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:FIRModelDownloadDidSucceedNotification object:nil queue:nil usingBlock:^(NSNotification *_Nonnull note) { if (weakSelf == nil | note.userInfo == nil) { return; } __strong typeof(self) strongSelf = weakSelf; FIRRemoteModel *model = note.userInfo[FIRModelDownloadUserInfoKeyRemoteModel]; if ([model.name isEqualToString:@"your_remote_model"]) { // The model was downloaded and is available on the device } }]; [NSNotificationCenter.defaultCenter addObserverForName:FIRModelDownloadDidFailNotification object:nil queue:nil usingBlock:^(NSNotification *_Nonnull note) { if (weakSelf == nil | note.userInfo == nil) { return; } __strong typeof(self) strongSelf = weakSelf; NSError *error = note.userInfo[FIRModelDownloadUserInfoKeyError]; }];
2. 準備輸入圖片
然後針對要加上標籤的每張圖片,使用本節所述的其中一個選項建立 VisionImage
物件,並將其傳送至 VisionImageLabeler
的例項 (如下節所述)。
使用 UIImage
或 CMSampleBufferRef
建立 VisionImage
物件。
如何使用 UIImage
:
- 視需要旋轉圖片,讓
imageOrientation
屬性為.up
。 - 使用正確旋轉的
UIImage
建立VisionImage
物件。請勿指定任何旋轉中繼資料,必須使用預設值.topLeft
。Swift
let image = VisionImage(image: uiImage)
Objective-C
FIRVisionImage *image = [[FIRVisionImage alloc] initWithImage:uiImage];
如何使用 CMSampleBufferRef
:
-
建立
VisionImageMetadata
物件,指定CMSampleBufferRef
緩衝區中圖片資料的方向。如何取得圖片方向:
Swift
func imageOrientation( deviceOrientation: UIDeviceOrientation, cameraPosition: AVCaptureDevice.Position ) -> VisionDetectorImageOrientation { switch deviceOrientation { case .portrait: return cameraPosition == .front ? .leftTop : .rightTop case .landscapeLeft: return cameraPosition == .front ? .bottomLeft : .topLeft case .portraitUpsideDown: return cameraPosition == .front ? .rightBottom : .leftBottom case .landscapeRight: return cameraPosition == .front ? .topRight : .bottomRight case .faceDown, .faceUp, .unknown: return .leftTop } }
Objective-C
- (FIRVisionDetectorImageOrientation) imageOrientationFromDeviceOrientation:(UIDeviceOrientation)deviceOrientation cameraPosition:(AVCaptureDevicePosition)cameraPosition { switch (deviceOrientation) { case UIDeviceOrientationPortrait: if (cameraPosition == AVCaptureDevicePositionFront) { return FIRVisionDetectorImageOrientationLeftTop; } else { return FIRVisionDetectorImageOrientationRightTop; } case UIDeviceOrientationLandscapeLeft: if (cameraPosition == AVCaptureDevicePositionFront) { return FIRVisionDetectorImageOrientationBottomLeft; } else { return FIRVisionDetectorImageOrientationTopLeft; } case UIDeviceOrientationPortraitUpsideDown: if (cameraPosition == AVCaptureDevicePositionFront) { return FIRVisionDetectorImageOrientationRightBottom; } else { return FIRVisionDetectorImageOrientationLeftBottom; } case UIDeviceOrientationLandscapeRight: if (cameraPosition == AVCaptureDevicePositionFront) { return FIRVisionDetectorImageOrientationTopRight; } else { return FIRVisionDetectorImageOrientationBottomRight; } default: return FIRVisionDetectorImageOrientationTopLeft; } }
然後,建立中繼資料物件:
Swift
let cameraPosition = AVCaptureDevice.Position.back // Set to the capture device you used. let metadata = VisionImageMetadata() metadata.orientation = imageOrientation( deviceOrientation: UIDevice.current.orientation, cameraPosition: cameraPosition )
Objective-C
FIRVisionImageMetadata *metadata = [[FIRVisionImageMetadata alloc] init]; AVCaptureDevicePosition cameraPosition = AVCaptureDevicePositionBack; // Set to the capture device you used. metadata.orientation = [self imageOrientationFromDeviceOrientation:UIDevice.currentDevice.orientation cameraPosition:cameraPosition];
- 使用
CMSampleBufferRef
物件和旋轉中繼資料建立VisionImage
物件:Swift
let image = VisionImage(buffer: sampleBuffer) image.metadata = metadata
Objective-C
FIRVisionImage *image = [[FIRVisionImage alloc] initWithBuffer:sampleBuffer]; image.metadata = metadata;
3. 執行映像檔標籤工具
如要為圖片中的物件加上標籤,請將 VisionImage
物件傳遞至 VisionImageLabeler
的 process()
方法:
Swift
labeler.process(image) { labels, error in
guard error == nil, let labels = labels else { return }
// Task succeeded.
// ...
}
Objective-C
[labeler
processImage:image
completion:^(NSArray<FIRVisionImageLabel *> *_Nullable labels, NSError *_Nullable error) {
if (error != nil || labels == nil) {
return;
}
// Task succeeded.
// ...
}];
如果圖片標籤成功,系統會將 VisionImageLabel
物件陣列傳遞至完成處理常式。您可以透過每個物件
取得在圖片中辨識的地圖項目相關資訊
例如:
Swift
for label in labels {
let labelText = label.text
let confidence = label.confidence
}
Objective-C
for (FIRVisionImageLabel *label in labels) {
NSString *labelText = label.text;
NSNumber *confidence = label.confidence;
}
即時效能改善訣竅
- 限制對偵測工具的呼叫。如果在偵測工具執行時有新的影片影格,請捨棄影格。
- 如果您使用偵測工具的輸出內容,在輸入圖片上疊加圖像,請先從 ML Kit 取得結果,然後透過一個步驟算繪圖像和疊加層。如此一來,每個輸入影格都只會算繪到顯示介面一次。如需範例,請參閱展示範例應用程式中的 previewOverlayView 和 FIRDetectionOverlayView 類別。