您可以使用机器学习套件来跨视频帧检测和跟踪对象。
当您向机器学习套件传递图片后,机器学习套件会以列表形式为每个图片返回最多五个检测到的对象及其在图片中的位置。检测视频流中的对象时,每个对象都有一个 ID,您可以使用此 ID 来跨图片跟踪对象。您还可以选择启用对象粗分类,该功能会使用粗略的类别描述来给对象加标签。
准备工作
- 如果您尚未将 Firebase 添加到自己的应用中,请按照入门指南中的步骤执行此操作。
- 在 Podfile 中添加机器学习套件库:pod 'Firebase/MLVision', '6.25.0' pod 'Firebase/MLVisionObjectDetection', '6.25.0' .xcworkspace来打开项目。
- 在您的应用中导入 Firebase:Swiftimport Firebase Objective-C@import Firebase; 
1. 配置对象检测器
要开始检测和跟踪对象,请先创建一个 VisionObjectDetector 实例,并视需要更改任何检测器默认设置。
- 使用 - VisionObjectDetectorOptions对象为您的使用场景配置对象检测器。您可以更改以下设置:- 对象检测器设置 - 检测模式 - .stream(默认)|- .singleImage- 在流模式(默认)下,对象检测器以极低的延迟运行,但在前几次调用检测器时可能会产生不完整的结果(例如未指定的边界框或类别)。此外,在流模式下,检测器会为对象分配跟踪 ID,您可以用该 ID 来跨帧跟踪对象。 如果您想要跟踪对象,或者对延迟有要求(例如在实时处理视频流时),请使用此模式。 - 在单图片模式下,直到获得所检测到的对象的边界框和类别标签(如果启用了分类),对象检测器才会返回结果。因此,此模式下的检测延迟可能较高。此外,在单图片模式下,不分配跟踪 ID。如果不计较延迟高低,且不想处理不完整的结果,请使用此模式。 - 检测和跟踪多个对象 - false(默认)|- true- 是检测和跟踪最多五个对象,还是仅检测和跟踪最突出的对象(默认)。 - 对对象进行分类 - false(默认)|- true- 是否对检测到的对象进行粗分类。启用后,对象检测器会将对象分为以下类别:时尚商品、食品、家居用品、地点、植物和未知类别。 - 对象检测和跟踪 API 针对以下两个核心使用场景进行了优化: - 实时检测和跟踪相机取景器中最突出的对象
- 检测静态图片中的多个对象
 - 要为这些使用场景配置 API,请运行以下代码: - Swift- // Live detection and tracking let options = VisionObjectDetectorOptions() options.detectorMode = .stream options.shouldEnableMultipleObjects = false options.shouldEnableClassification = true // Optional // Multiple object detection in static images let options = VisionObjectDetectorOptions() options.detectorMode = .singleImage options.shouldEnableMultipleObjects = true options.shouldEnableClassification = true // Optional- Objective-C- // Live detection and tracking FIRVisionObjectDetectorOptions *options = [[FIRVisionObjectDetectorOptions alloc] init]; options.detectorMode = FIRVisionObjectDetectorModeStream; options.shouldEnableMultipleObjects = NO; options.shouldEnableClassification = YES; // Optional // Multiple object detection in static images FIRVisionObjectDetectorOptions *options = [[FIRVisionObjectDetectorOptions alloc] init]; options.detectorMode = FIRVisionObjectDetectorModeSingleImage; options.shouldEnableMultipleObjects = YES; options.shouldEnableClassification = YES; // Optional
- 获取 - FirebaseVisionObjectDetector的一个实例:- Swift- let objectDetector = Vision.vision().objectDetector() // Or, to change the default settings: let objectDetector = Vision.vision().objectDetector(options: options)- Objective-C- FIRVisionObjectDetector *objectDetector = [[FIRVision vision] objectDetector]; // Or, to change the default settings: FIRVisionObjectDetector *objectDetector = [[FIRVision vision] objectDetectorWithOptions:options];
2. 运行对象检测器
要检测和跟踪对象,请对每个图片或视频帧执行以下操作。
如果您启用了流模式,则必须基于 CMSampleBufferRef 创建 VisionImage 对象。
- 使用 - UIImage或- CMSampleBufferRef创建一个- VisionImage对象。- 如需使用 - UIImage,请按以下步骤操作:- 在必要时旋转图片,以使其 imageOrientation属性为.up。
- 使用方向正确的 UIImage创建一个VisionImage对象。不要指定任何旋转方式元数据,必须使用默认值.topLeft。Swiftlet image = VisionImage(image: uiImage) Objective-CFIRVisionImage *image = [[FIRVisionImage alloc] initWithImage:uiImage]; 
 - 如需使用 - CMSampleBufferRef,请按以下步骤操作:- 
    创建一个 VisionImageMetadata对象,用其指定CMSampleBufferRef缓冲区中所含图片数据的方向。如需获取图片方向,请运行以下代码: Swiftfunc imageOrientation( deviceOrientation: UIDeviceOrientation, cameraPosition: AVCaptureDevice.Position ) -> VisionDetectorImageOrientation { switch deviceOrientation { case .portrait: return cameraPosition == .front ? .leftTop : .rightTop case .landscapeLeft: return cameraPosition == .front ? .bottomLeft : .topLeft case .portraitUpsideDown: return cameraPosition == .front ? .rightBottom : .leftBottom case .landscapeRight: return cameraPosition == .front ? .topRight : .bottomRight case .faceDown, .faceUp, .unknown: return .leftTop } } Objective-C- (FIRVisionDetectorImageOrientation) imageOrientationFromDeviceOrientation:(UIDeviceOrientation)deviceOrientation cameraPosition:(AVCaptureDevicePosition)cameraPosition { switch (deviceOrientation) { case UIDeviceOrientationPortrait: if (cameraPosition == AVCaptureDevicePositionFront) { return FIRVisionDetectorImageOrientationLeftTop; } else { return FIRVisionDetectorImageOrientationRightTop; } case UIDeviceOrientationLandscapeLeft: if (cameraPosition == AVCaptureDevicePositionFront) { return FIRVisionDetectorImageOrientationBottomLeft; } else { return FIRVisionDetectorImageOrientationTopLeft; } case UIDeviceOrientationPortraitUpsideDown: if (cameraPosition == AVCaptureDevicePositionFront) { return FIRVisionDetectorImageOrientationRightBottom; } else { return FIRVisionDetectorImageOrientationLeftBottom; } case UIDeviceOrientationLandscapeRight: if (cameraPosition == AVCaptureDevicePositionFront) { return FIRVisionDetectorImageOrientationTopRight; } else { return FIRVisionDetectorImageOrientationBottomRight; } default: return FIRVisionDetectorImageOrientationTopLeft; } } 然后,创建元数据对象: Swiftlet cameraPosition = AVCaptureDevice.Position.back // Set to the capture device you used. let metadata = VisionImageMetadata() metadata.orientation = imageOrientation( deviceOrientation: UIDevice.current.orientation, cameraPosition: cameraPosition ) Objective-CFIRVisionImageMetadata *metadata = [[FIRVisionImageMetadata alloc] init]; AVCaptureDevicePosition cameraPosition = AVCaptureDevicePositionBack; // Set to the capture device you used. metadata.orientation = [self imageOrientationFromDeviceOrientation:UIDevice.currentDevice.orientation cameraPosition:cameraPosition]; 
- 使用 CMSampleBufferRef对象和旋转方式元数据创建一个VisionImage对象:Swiftlet image = VisionImage(buffer: sampleBuffer) image.metadata = metadata Objective-CFIRVisionImage *image = [[FIRVisionImage alloc] initWithBuffer:sampleBuffer]; image.metadata = metadata; 
 
- 在必要时旋转图片,以使其 
- 将 - VisionImage传递给对象检测器的图片处理方法之一。您可以使用异步的- process(image:)方法或同步的- results()方法。- 要异步检测对象,请运行以下代码: - Swift- objectDetector.process(image) { detectedObjects, error in guard error == nil else { // Error. return } guard let detectedObjects = detectedObjects, !detectedObjects.isEmpty else { // No objects detected. return } // Success. Get object info here. // ... }- Objective-C- [objectDetector processImage:image completion:^(NSArray<FIRVisionObject *> * _Nullable objects, NSError * _Nullable error) { if (error == nil) { return; } if (objects == nil | objects.count == 0) { // No objects detected. return; } // Success. Get object info here. // ... }];- 要同步检测对象,请运行以下代码: - Swift- var results: [VisionObject]? = nil do { results = try objectDetector.results(in: image) } catch let error { print("Failed to detect object with error: \(error.localizedDescription).") return } guard let detectedObjects = results, !detectedObjects.isEmpty else { print("Object detector returned no results.") return } // ...- Objective-C- NSError *error; NSArray<FIRVisionObject *> *objects = [objectDetector resultsInImage:image error:&error]; if (error == nil) { return; } if (objects == nil | objects.count == 0) { // No objects detected. return; } // Success. Get object info here. // ...
- 如果对图片处理器的调用成功完成,则系统会将 - VisionObject列表传递给完成处理程序或返回该列表,具体取决于您调用的是异步方法还是同步方法。- 每个 - VisionObject包含以下属性:- frame- 一个 - CGRect,指示图片中对象的位置。- trackingID- 一个整数,用于跨图片标识对象。在单图片模式下为 nil。 - classificationCategory- 对象的粗类别。如果对象检测器未启用分类,则该属性始终为 - .unknown。- confidence- 对象分类的置信度值。如果对象检测器未启用分类或对象归类为未知类别,则该属性为 - nil。- Swift- // detectedObjects contains one item if multiple object detection wasn't enabled. for obj in detectedObjects { let bounds = obj.frame let id = obj.trackingID // If classification was enabled: let category = obj.classificationCategory let confidence = obj.confidence }- Objective-C- // The list of detected objects contains one item if multiple // object detection wasn't enabled. for (FIRVisionObject *obj in objects) { CGRect bounds = obj.frame; if (obj.trackingID) { NSInteger id = obj.trackingID.integerValue; } // If classification was enabled: FIRVisionObjectCategory category = obj.classificationCategory; float confidence = obj.confidence.floatValue; }
提高易用性和性能
如需获得最佳用户体验,请在您的应用中遵循以下准则:
- 对象检测成功与否取决于对象的视觉复杂性。具有较少视觉特征的对象可能需要占据待检测图片的较大部分区域。您应为用户提供有关捕获输入的指导,该输入应适用于您要检测的对象类型。
- 使用分类时,如果您要检测不完全归于受支持类别的对象,请对未知对象执行特殊处理。
另请参阅 [机器学习套件 Material Design 展示应用][showcase-link]{: .external } 和适用于机器学习所支持功能集的 Material Design 模式。
在实时应用中使用流式传输模式时,请遵循以下准则以实现最佳帧速率:
- 请勿在流式传输模式下使用多个对象检测,因为大多数设备无法产生足够高的帧速率。 
- 如果您不需要,请停用分类。 
- 限制检测器的调用次数。如果在检测器运行时有新的视频帧可用,请丢弃该帧。
- 如果要将检测器的输出作为图形叠加在输入图片上,请先从机器学习套件获取结果,然后在一个步骤中完成图片的呈现和叠加。采用这一方法,每个输入帧只需在显示表面呈现一次。如需查看示例,请参阅示例应用中的 previewOverlayView 和 FIRDetectionOverlayView 类。