当您将图片传递给机器学习套件时,它会检测图片中的最多五个对象,以及图片中每个对象的位置。检测视频流中的对象时,每个对象都有一个唯一 ID,您可以使用该 ID 逐帧跟踪对象。
您可以使用自定义图片分类模型对检测到的对象进行分类。如需了解有关模型兼容性要求、在哪里可以找到预训练模型以及如何训练您自己的模型,请参阅使用机器学习套件自定义模型。
您可以通过两种方式集成自定义模型。您可以将模型放入应用的资源文件夹中来捆绑模型,也可以从 Firebase 动态下载模型。下表对这两个选项进行了比较。
捆绑模型 | 托管的模型 |
---|---|
该模型是应用的 .ipa 文件的一部分,这会增加其大小。 |
模型不是应用的 .ipa 文件的一部分。该测试通过上传到 Firebase Machine Learning 进行托管。 |
即使 Android 设备处于离线状态,模型也可立即使用 | 按需下载模型 |
不需要 Firebase 项目 | 需要 Firebase 项目 |
您必须重新发布应用才能更新模型 | 无需重新发布应用即可推送模型更新 |
没有内置的 A/B 测试 | 使用 Firebase Remote Config 轻松进行 A/B 测试 |
试试看
- 如需查看捆绑模型的示例用法,请参阅 Vision 快速入门应用;如需查看托管模型的用法示例,请参阅 automl 快速入门应用。
- 如需了解此 API 的端到端实现,请参阅 Material Design 展示应用。
准备工作
在 Podfile 中添加机器学习套件库:
如需将模型与您的应用捆绑在一起,请执行以下操作:
pod 'GoogleMLKit/ObjectDetectionCustom', '3.2.0'
如需从 Firebase 动态下载模型,请添加
LinkFirebase
依赖项:pod 'GoogleMLKit/ObjectDetectionCustom', '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 托管的模型来源
如需使用远程托管的模型,请创建一个 CustomRemoteModel
对象,指定您在发布该模型时分配给模型的名称:
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];
许多应用会通过其初始化代码启动下载任务,但您可以在需要使用该模型之前随时启动下载任务。
2. 配置对象检测器
配置模型来源后,请使用 CustomObjectDetectorOptions
对象为您的使用场景配置对象检测器。您可以更改以下设置:
对象检测器设置 | |
---|---|
检测模式 |
STREAM_MODE (默认值)| SINGLE_IMAGE_MODE
在 在 |
检测和跟踪多个对象 |
false (默认值)| true
是检测和跟踪最多五个对象,还是仅检测和跟踪最突出的对象(默认)。 |
对对象进行分类 |
false (默认值)| true
是否使用提供的自定义分类器模型对检测到的对象进行分类。如需使用自定义分类模型,您需要将此属性设置为 |
分类置信度阈值 |
检测到的标签的最小置信度分数。如果未设置,系统将使用模型的元数据指定的任何分类器阈值。如果模型不包含任何元数据,或者元数据未指定分类器阈值,则系统会使用默认阈值 0.0。 |
每个对象的标签数上限 |
检测器会返回的每个对象的标签数上限。如果未设置此政策,系统将使用默认值 10。 |
如果您只有本地捆绑的模型,则只需根据 LocalModel
对象创建对象检测器:
Swift
let options = CustomObjectDetectorOptions(localModel: localModel) options.detectorMode = .singleImage options.shouldEnableClassification = true options.shouldEnableMultipleObjects = true options.classificationConfidenceThreshold = NSNumber(value: 0.5) options.maxPerObjectLabelCount = 3
Objective-C
MLKCustomObjectDetectorOptions *options = [[MLKCustomObjectDetectorOptions alloc] initWithLocalModel:localModel]; options.detectorMode = MLKObjectDetectorModeSingleImage; options.shouldEnableClassification = YES; options.shouldEnableMultipleObjects = YES; options.classificationConfidenceThreshold = @(0.5); options.maxPerObjectLabelCount = 3;
如果您有一个远程托管的模型,则必须在运行该模型之前检查是否已下载该模型。您可以使用模型管理器的 isModelDownloaded(remoteModel:)
方法检查模型下载任务的状态。
虽然您只需在运行对象检测器之前确认这一点,但如果您同时拥有远程托管模型和本地捆绑模型,则可能需要在实例化 ObjectDetector
时执行此检查:如果已下载,则根据远程模型创建检测器,否则根据本地模型进行创建。
Swift
var options: CustomObjectDetectorOptions! if (ModelManager.modelManager().isModelDownloaded(remoteModel)) { options = CustomObjectDetectorOptions(remoteModel: remoteModel) } else { options = CustomObjectDetectorOptions(localModel: localModel) } options.detectorMode = .singleImage options.shouldEnableClassification = true options.shouldEnableMultipleObjects = true options.classificationConfidenceThreshold = NSNumber(value: 0.5) options.maxPerObjectLabelCount = 3
Objective-C
MLKCustomObjectDetectorOptions *options; if ([[MLKModelManager modelManager] isModelDownloaded:remoteModel]) { options = [[MLKCustomObjectDetectorOptions alloc] initWithRemoteModel:remoteModel]; } else { options = [[MLKCustomObjectDetectorOptions alloc] initWithLocalModel:localModel]; } options.detectorMode = MLKObjectDetectorModeSingleImage; options.shouldEnableClassification = YES; options.shouldEnableMultipleObjects = YES; options.classificationConfidenceThreshold = @(0.5); options.maxPerObjectLabelCount = 3;
如果您只有远程托管的模型,则应停用与模型相关的功能(例如灰显或隐藏部分界面),直到您确认模型已下载。
您可以将观察者附加到默认通知中心,以获取模型下载状态。请务必在观察者块中使用对 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]; }];
对象检测和跟踪 API 针对以下两个核心使用场景进行了优化:
- 实时检测和跟踪相机取景器中最显眼的对象。
- 从静态图片中检测多个对象。
如需为这些用例配置 API,请执行以下操作:
Swift
// Live detection and tracking let options = CustomObjectDetectorOptions(localModel: localModel) options.shouldEnableClassification = true options.maxPerObjectLabelCount = 3 // Multiple object detection in static images let options = CustomObjectDetectorOptions(localModel: localModel) options.detectorMode = .singleImage options.shouldEnableMultipleObjects = true options.shouldEnableClassification = true options.maxPerObjectLabelCount = 3
Objective-C
// Live detection and tracking MLKCustomObjectDetectorOptions *options = [[MLKCustomObjectDetectorOptions alloc] initWithLocalModel:localModel]; options.shouldEnableClassification = YES; options.maxPerObjectLabelCount = 3; // Multiple object detection in static images MLKCustomObjectDetectorOptions *options = [[MLKCustomObjectDetectorOptions alloc] initWithLocalModel:localModel]; options.detectorMode = MLKObjectDetectorModeSingleImage; options.shouldEnableMultipleObjects = YES; options.shouldEnableClassification = YES; options.maxPerObjectLabelCount = 3;
3. 准备输入图片
使用 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];
4. 创建并运行对象检测器
创建新的对象检测器:
Swift
let objectDetector = ObjectDetector.objectDetector(options: options)
Objective-C
MLKObjectDetector *objectDetector = [MLKObjectDetector objectDetectorWithOptions:options];
然后,使用检测器:
异步:
Swift
objectDetector.process(image) { objects, error in guard error == nil, let objects = objects, !objects.isEmpty else { // Handle the error. return } // Show results. }
Objective-C
[objectDetector processImage:image completion:^(NSArray
*_Nullable objects, NSError *_Nullable error) { if (objects.count == 0) { // Handle the error. return; } // Show results. }]; 同步:
Swift
var objects: [Object] do { objects = try objectDetector.results(in: image) } catch let error { // Handle the error. return } // Show results.
Objective-C
NSError *error; NSArray
*objects = [objectDetector resultsInImage:image error:&error]; // Show results or handle the error.
5. 获取有关已加标签的对象的信息
如果对图片处理器的调用成功,则系统会将 Object
列表传递给完成处理程序或返回该列表,具体取决于您调用的是异步方法还是同步方法。
每个 Object
包含以下属性:
frame |
一个 CGRect ,指示图片中对象的位置。 |
||||||
trackingID |
一个整数,用于跨映像标识对象;在 SINGLE_IMAGE_MODE 下则为“nil”。 | ||||||
labels |
|
Swift
// objects contains one item if multiple object detection wasn't enabled. for object in objects { let frame = object.frame let trackingID = object.trackingID let description = object.labels.enumerated().map { (index, label) in "Label \(index): \(label.text), \(label.confidence), \(label.index)" }.joined(separator: "\n") }
Objective-C
// The list of detected objects contains one item if multiple object detection // wasn't enabled. for (MLKObject *object in objects) { CGRect frame = object.frame; NSNumber *trackingID = object.trackingID; for (MLKObjectLabel *label in object.labels) { NSString *labelString = [NSString stringWithFormat:@"%@, %f, %lu", label.text, label.confidence, (unsigned long)label.index]; } }
确保提供出色的用户体验
为了提供最佳用户体验,请在您的应用中遵循以下准则:
- 对象检测成功与否取决于对象的视觉复杂性。具有少量视觉特征的对象可能需要占据图片的大部分区域才能被检测到。您应该为用户提供有关如何捕获适用于要检测的对象类型的输入的指导。
- 使用分类时,如果要检测未完全归入受支持类别的对象,请对未知对象实现特殊处理。
此外,请查看 [机器学习套件 Material Design 展示应用][showcase-link]{: .external } 和适用于机器学习驱动的功能的 Material Design 模式集合。
提高性能
如果要在实时应用中使用对象检测,请遵循以下准则以实现最佳帧速率:在实时应用中使用流式传输模式时,请勿使用多对象检测,因为大多数设备无法生成足够的帧速率。
- 如需处理视频帧,请使用检测器的
results(in:)
同步 API。从AVCaptureVideoDataOutputSampleBufferDelegate
的captureOutput(_, didOutput:from:)
函数调用此方法,以同步获取给定视频帧的结果。将AVCaptureVideoDataOutput
的alwaysDiscardsLateVideoFrames
保持为true
,以限制对检测器的调用。如果在检测器运行时有新的视频帧可用,该帧将被丢弃。 - 如果使用检测器的输出将图形叠加在输入图片上,请先从机器学习套件获取结果,然后在一个步骤中完成图片的呈现和叠加。采用这一方法,每个已处理的输入帧只需在显示表面渲染一次。如需查看示例,请参阅机器学习套件快速入门示例中的 updatePreviewOverlayViewWithLastFrame。