使用 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类。