您可以使用机器学习套件识别图片中的实体并为其添加标签。此 API 支持各种自定义图片分类模型。如需有关模型兼容性要求、在哪里可以找到预训练模型以及如何训练您自己的模型,请参阅使用机器学习套件自定义模型。
您可以通过两种方式集成自定义模型。您可以将模型放入应用的资源文件夹中来捆绑模型,也可以从 Firebase 动态下载模型。下表对这两个选项进行了比较。
捆绑模型 | 托管的模型 |
---|---|
模型是应用 APK 的一部分,这会增加其大小。 | 该模型不是您的 APK 的一部分。该测试通过上传到 Firebase Machine Learning 进行托管。 |
即使 Android 设备处于离线状态,模型也可立即使用 | 按需下载模型 |
不需要 Firebase 项目 | 需要 Firebase 项目 |
您必须重新发布应用才能更新模型 | 无需重新发布应用即可推送模型更新 |
没有内置的 A/B 测试 | 使用 Firebase Remote Config 轻松进行 A/B 测试 |
试试看
- 如需查看捆绑模型的示例用法,请参阅 Vision 快速入门应用;如需查看托管模型的用法示例,请参阅 automl 快速入门应用。
准备工作
在 Podfile 中添加机器学习套件库:
如需将模型与您的应用捆绑在一起,请执行以下操作:
pod 'GoogleMLKit/ImageLabelingCustom', '3.2.0'
如需从 Firebase 动态下载模型,请添加
LinkFirebase
依赖项:pod 'GoogleMLKit/ImageLabelingCustom', '3.2.0' pod 'GoogleMLKit/LinkFirebase', '3.2.0'
安装或更新项目的 Pod 之后,请使用 Xcode 项目的
.xcworkspace
来打开该项目。Xcode 13.2.1 版或更高版本支持机器学习套件。如果您想下载模型,请务必将 Firebase 添加到您的 iOS 项目(如果尚未添加)。捆绑模型时不需要这样做。
1. 加载模型
配置本地模型来源
如需将模型与您的应用捆绑在一起,请执行以下操作:
将模型文件(通常以
.tflite
或.lite
结尾)复制到 Xcode 项目,并在执行此操作时注意选择Copy bundle resources
。模型文件将包含在应用软件包中,并提供给机器学习套件使用。创建
LocalModel
对象,指定模型文件的路径:Swift
let localModel = LocalModel(path: localModelFilePath)
Objective-C
MLKLocalModel *localModel = [[MLKLocalModel alloc] initWithPath:localModelFilePath];
配置 Firebase 托管的模型来源
如需使用远程托管的模型,请创建一个 RemoteModel
对象,指定您在发布该模型时分配给模型的名称:
Swift
let firebaseModelSource = FirebaseModelSource( name: "your_remote_model") // The name you assigned in // the Firebase console. let remoteModel = CustomRemoteModel(remoteModelSource: firebaseModelSource)
Objective-C
MLKFirebaseModelSource *firebaseModelSource = [[MLKFirebaseModelSource alloc] initWithName:@"your_remote_model"]; // The name you assigned in // the Firebase console. 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] downloadModel:remoteModel conditions:downloadConditions];
许多应用会通过其初始化代码启动下载任务,但您可以在需要使用该模型之前随时启动下载任务。
配置图片标记器
配置模型来源后,根据其中一个模型创建 ImageLabeler
对象。
提供的选项如下:
选项 | |
---|---|
confidenceThreshold
|
检测到的标签的最小置信度分数。如果未设置,系统将使用模型的元数据指定的任何分类器阈值。如果模型不包含任何元数据,或者元数据未指定分类器阈值,则系统会使用默认阈值 0.0。 |
maxResultCount
|
要返回的标签数量上限。如果未设置此政策,系统将使用默认值 10。 |
如果您只有本地捆绑的模型,则只需根据 LocalModel
对象创建一个标记器即可:
Swift
let options = CustomImageLabelerOptions(localModel: localModel) options.confidenceThreshold = NSNumber(value: 0.0) let imageLabeler = ImageLabeler.imageLabeler(options: options)
Objective-C
MLKCustomImageLabelerOptions *options = [[MLKCustomImageLabelerOptions alloc] initWithLocalModel:localModel]; options.confidenceThreshold = @(0.0); 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) 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.0); MLKImageLabeler *imageLabeler = [MLKImageLabeler imageLabelerWithOptions:options];
如果您只有远程托管的模型,则应停用与模型相关的功能(例如灰显或隐藏部分界面),直到您确认模型已下载。
您可以将观察者附加到默认通知中心,以获取模型下载状态。请务必在观察者块中使用对 self
的弱引用,因为下载可能需要一些时间,并且源对象可能到下载完成才会被释放。例如:
Swift
NotificationCenter.default.addObserver( forName: .mlkitModelDownloadDidSucceed, 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: .mlkitModelDownloadDidFail, 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
或 CMSampleBuffer
创建一个 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;
如果您使用的是 CMSampleBuffer
,请按以下步骤操作:
-
指定
CMSampleBuffer
中包含的图片数据的方向。如需获取图片方向,请运行以下命令:
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 cameraPosition == AVCaptureDevicePositionFront ? UIImageOrientationLeftMirrored : UIImageOrientationRight; case UIDeviceOrientationLandscapeLeft: return cameraPosition == AVCaptureDevicePositionFront ? UIImageOrientationDownMirrored : UIImageOrientationUp; case UIDeviceOrientationPortraitUpsideDown: return cameraPosition == AVCaptureDevicePositionFront ? UIImageOrientationRightMirrored : UIImageOrientationLeft; case UIDeviceOrientationLandscapeRight: return cameraPosition == AVCaptureDevicePositionFront ? UIImageOrientationUpMirrored : UIImageOrientationDown; case UIDeviceOrientationUnknown: case UIDeviceOrientationFaceUp: case UIDeviceOrientationFaceDown: return UIImageOrientationUp; } }
- 使用
CMSampleBuffer
对象和方向创建一个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. 运行图片标记器
如需给图片中的对象加标签,请将 image
对象传递给 ImageLabeler
的 process()
方法。
异步:
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*_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*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; }
提高实时性能的相关提示
如果要在实时应用中给图片加标签,请遵循以下准则以实现最佳帧速率:
- 如需处理视频帧,请使用检测器的
results(in:)
同步 API。从AVCaptureVideoDataOutputSampleBufferDelegate
的captureOutput(_, didOutput:from:)
函数调用此方法,以同步获取给定视频帧的结果。将AVCaptureVideoDataOutput
的alwaysDiscardsLateVideoFrames
保持为true
,以限制对检测器的调用。如果在检测器运行时有新的视频帧可用,该帧将被丢弃。 - 如果使用检测器的输出将图形叠加在输入图片上,请先从机器学习套件获取结果,然后在一个步骤中完成图片的呈现和叠加。采用这一方法,每个已处理的输入帧只需在显示表面渲染一次。如需查看示例,请参阅机器学习套件快速入门示例中的 updatePreviewOverlayViewWithLastFrame。