使用 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 項目,執行此操作時請注意選擇“創建文件夾引用” 。模型文件和元數據將包含在應用程序包中並可供 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)
目標-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)
目標-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
)
目標-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)
目標-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)
目標-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]
// ...
}
目標-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
目標-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 } }
目標-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)
目標-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.
}
目標-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.
目標-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
}
目標-C
for (MLKImageLabel *label in labels) {
NSString *labelText = label.text;
float confidence = label.confidence;
NSInteger index = label.index;
}
提高實時性能的技巧
如果您想在實時應用程序中標記圖像,請遵循以下準則以獲得最佳幀率:
- 限制對檢測器的調用。如果在檢測器運行時有新的視頻幀可用,則丟棄該幀。
- 如果您使用檢測器的輸出在輸入圖像上疊加圖形,請先獲取結果,然後一步渲染圖像和疊加。通過這樣做,您只需為每個輸入幀渲染到顯示表面一次。有關示例,請參閱展示示例應用程序中的previewOverlayView和FIRDetectionOverlayView類。