使用 AutoML Vision Edge 自行訓練模型後,即可在應用程式中使用模型為圖片加上標籤。
有兩種方法可以整合透過 AutoML Vision Edge 訓練的模型。如要組合模型,您可以將模型的檔案複製到 Xcode 專案,也可以從 Firebase 動態下載模型。
模型組合選項 | |
---|---|
在應用程式中封裝 |
|
由 Firebase 代管 |
|
事前準備
在 Podfile 中加入 ML Kit 程式庫:
將模型與應用程式綁定:
pod 'GoogleMLKit/ImageLabelingCustom'
如要從 Firebase 動態下載模型,請新增
LinkFirebase
依附元件:pod 'GoogleMLKit/ImageLabelingCustom' pod 'GoogleMLKit/LinkFirebase'
安裝或更新專案的 Pod 後,請使用
.xcworkspace
開啟 Xcode 專案,Xcode 12.2 以上版本支援 ML Kit。如要下載模型,請務必將 Firebase 新增至 Android 專案 (如果尚未新增的話)。在組合模型時不需要這麼做。
1. 載入模型
設定本機模型來源
將模型與應用程式組合如下:
將您從 Firebase 主控台下載的 ZIP 封存檔中,將模型及其中繼資料擷取至資料夾:
your_model_directory |____dict.txt |____manifest.json |____model.tflite
這三個檔案都必須位於同一個資料夾中。建議您使用下載時的檔案,不要修改 (包含檔案名稱)。
將資料夾複製到 Xcode 專案,並在刪除時小心選取「Create folder reference」。模型檔案和中繼資料會包含在應用程式套件中,並可供 ML Kit 使用。
建立
LocalModel
物件,指定模型資訊清單檔案的路徑:Swift
guard let manifestPath = Bundle.main.path( forResource: "manifest", ofType: "json", inDirectory: "your_model_directory" ) else { return true } let localModel = LocalModel(manifestPath: manifestPath)
Objective-C
NSString *manifestPath = [NSBundle.mainBundle pathForResource:@"manifest" ofType:@"json" inDirectory:@"your_model_directory"]; MLKLocalModel *localModel = [[MLKLocalModel alloc] initWithManifestPath:manifestPath];
設定 Firebase 託管的模型來源
如要使用遠端託管的模型,請建立 CustomRemoteModel
物件,並指定您發布模型時指派的名稱:
Swift
// Initialize the model source with the name you assigned in
// the Firebase console.
let remoteModelSource = FirebaseModelSource(name: "your_remote_model")
let remoteModel = CustomRemoteModel(remoteModelSource: remoteModelSource)
Objective-C
// Initialize the model source with the name you assigned in
// the Firebase console.
MLKFirebaseModelSource *firebaseModelSource =
[[MLKFirebaseModelSource alloc] initWithName:@"your_remote_model"];
MLKCustomRemoteModel *remoteModel =
[[MLKCustomRemoteModel alloc] initWithRemoteModelSource:firebaseModelSource];
接著,開始模型下載工作,指定要允許下載的條件。如果裝置上沒有該模型,或者有較新版本的模型,這項工作就會以非同步方式從 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] downloadRemoteModel:remoteModel
conditions:downloadConditions];
許多應用程式會在初始化程式碼中啟動下載工作,但在您需要使用模型前,您可以隨時執行此操作。
從模型建立圖片標籤工具
設定模型來源後,請從其中一個建立 ImageLabeler
物件。
如果您只有本機組合模型,只需透過 LocalModel
物件建立標籤人員,並設定所需的可信度分數門檻即可 (請參閱評估模型):
Swift
let options = CustomImageLabelerOptions(localModel: localModel)
options.confidenceThreshold = NSNumber(value: 0.0) // Evaluate your model in the Cloud console
// to determine an appropriate value.
let imageLabeler = ImageLabeler.imageLabeler(options)
Objective-C
CustomImageLabelerOptions *options =
[[CustomImageLabelerOptions alloc] initWithLocalModel:localModel];
options.confidenceThreshold = @(0.0f); // Evaluate your model in the Cloud console
// to determine an appropriate value.
MLKImageLabeler *imageLabeler =
[MLKImageLabeler imageLabelerWithOptions:options];
如果您有遠端託管的模型,必須先檢查是否已下載過該模型,才能執行。您可以使用模型管理員的 isModelDownloaded(remoteModel:)
方法,查看模型下載工作的狀態。
雖然您只需在執行標籤人員前進行確認,但如果您同時擁有遠端託管的模型和本機組合模型,那麼在將 ImageLabeler
執行個體化時,可能很適合執行這項檢查:在執行個體化時,透過遠端模型建立標籤器 (如果已下載的話),再從本機模型建立標籤器。
Swift
var options: CustomImageLabelerOptions
if (ModelManager.modelManager().isModelDownloaded(remoteModel)) {
options = CustomImageLabelerOptions(remoteModel: remoteModel)
} else {
options = CustomImageLabelerOptions(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
MLKCustomImageLabelerOptions *options;
if ([[MLKModelManager modelManager] isModelDownloaded:remoteModel]) {
options = [[MLKCustomImageLabelerOptions alloc] initWithRemoteModel:remoteModel];
} else {
options = [[MLKCustomImageLabelerOptions alloc] initWithLocalModel:localModel];
}
options.confidenceThreshold = @(0.0f); // Evaluate your model in the Firebase console
// to determine an appropriate value.
MLKImageLabeler *imageLabeler =
[MLKImageLabeler imageLabelerWithOptions:options];
如果您只有遠端託管的模型,請在確認下載模型之前,停用模型相關功能,例如將 UI 顯示為灰色或隱藏。
您可以將觀察器附加至預設通知中心,藉此取得模型下載狀態。由於下載可能需要一點時間,並在下載完成後釋出原始物件,因此請務必在觀察器區塊中使用調整的 self
參照。例如:
Swift
NotificationCenter.default.addObserver(
forName: .mlkitMLModelDownloadDidSucceed,
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: .mlkitMLModelDownloadDidFail,
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
或 CMSampleBufferRef
建立 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;
如果您使用 CMSampleBufferRef
,請按照下列步驟操作:
-
指定
CMSampleBufferRef
緩衝區中圖片資料的方向。如何取得圖片方向:
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 position == AVCaptureDevicePositionFront ? UIImageOrientationLeftMirrored : UIImageOrientationRight; case UIDeviceOrientationLandscapeLeft: return position == AVCaptureDevicePositionFront ? UIImageOrientationDownMirrored : UIImageOrientationUp; case UIDeviceOrientationPortraitUpsideDown: return position == AVCaptureDevicePositionFront ? UIImageOrientationRightMirrored : UIImageOrientationLeft; case UIDeviceOrientationLandscapeRight: return position == AVCaptureDevicePositionFront ? UIImageOrientationUpMirrored : UIImageOrientationDown; case UIDeviceOrientationUnknown: case UIDeviceOrientationFaceUp: case UIDeviceOrientationFaceDown: return UIImageOrientationUp; } }
- 使用
CMSampleBufferRef
物件和方向建立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<MLKImageLabel *> *_Nullable labels,
NSError *_Nullable error) {
if (label.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<MLKImageLabel *> *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;
}
即時效能改善訣竅
如要在即時應用程式中為圖片加上標籤,請遵循下列準則,以便達到最佳的影格速率:
- 限制對偵測工具的呼叫。如果在偵測工具執行時有新的影片影格,請捨棄影格。
- 如要使用偵測工具的輸出內容在輸入圖片上重疊圖像,請先取得結果,然後在單一步驟中算繪圖片和疊加層。如此一來,每個輸入影格都只會算繪到顯示介面一次。如需範例,請參閱展示範例應用程式中的 previewOverlayView 和 FIRDetectionOverlayView 類別。