使用 AutoML Vision Edge 訓練自己的模型後,您可以在應用程式中使用它來標記圖像。
有兩種方法可以整合從 AutoML Vision Edge 訓練的模型。您可以透過將模型的檔案複製到 Xcode 專案中來捆綁模型,也可以從 Firebase 動態下載它。
模型捆綁選項 | |
---|---|
捆綁在您的應用程式中 |
|
使用 Firebase 託管 |
|
在你開始之前
將 ML Kit 庫包含在您的 Podfile 中:
將模型與您的應用程式捆綁在一起:
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 項目,執行此操作時請注意選擇「建立資料夾參考」 。模型檔案和元資料將包含在應用程式套件中並可供 ML Kit 使用。
建立
LocalModel
對象,指定模型清單檔案的路徑:迅速
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
對象,並指定您在發布模型時為其指定的名稱:
迅速
// 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 非同步下載模型:
迅速
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
物件建立標記器並配置您想要的置信度分數閾值(請參閱評估您的模型):
迅速
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
時執行此檢查可能是有意義的:如果是,則從遠端模型創建貼標機已下載,否則從本機模型下載。
迅速
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
弱引用,因為下載可能需要一些時間,並且在下載完成時可以釋放原始物件。例如:
迅速
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
。迅速
let image = VisionImage(image: uiImage) visionImage.orientation = image.imageOrientation
Objective-C
MLKVisionImage *visionImage = [[MLKVisionImage alloc] initWithImage:image]; visionImage.orientation = image.imageOrientation;
如果您使用CMSampleBufferRef
,請依照下列步驟操作:
指定
CMSampleBufferRef
緩衝區中包含的影像資料的方向。若要取得影像方向:
迅速
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
物件:迅速
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. 運行影像標記器
非同步:
迅速
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.
}];
同步:
迅速
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 模型檔案的元資料中可用)、置信度分數和索引。例如:
迅速
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類別。