您可以使用机器学习套件检测和跟踪连续的视频帧中的对象。
当您将图片传递给机器学习套件时,它会检测图片中的最多 5 个对象以及图片中每个对象的位置。检测视频流中的对象时,每个对象都有一个唯一 ID,可用于逐帧跟踪对象。您还可以选择启用粗略对象分类,即使用宽泛的类别描述标记对象。
试试看
- 试用示例应用,查看此 API 的示例用法。
- 如需了解此 API 的端到端实现,请参阅 Material Design 展示应用。
准备工作
- 在 Podfile 中添加以下机器学习套件 pod:
pod 'GoogleMLKit/ObjectDetection', '3.2.0'
- 安装或更新项目的 Pod 之后,请使用 Xcode 项目的
.xcworkspace
打开该项目。Xcode 12.4 版或更高版本支持机器学习套件。
1. 配置对象检测器
如需检测和跟踪对象,请先创建一个 ObjectDetector
实例,并视需要更改检测器默认设置。
使用
ObjectDetectorOptions
对象为您的使用场景配置对象检测器。您可以更改以下设置:对象检测器设置 检测模式 .stream
(默认)|.singleImage
在流模式下(默认),对象检测器以极低的延迟运行,但在前几次调用检测器时可能会产生不完整的结果(例如未指定的边界框或类别)。此外,在流模式下,检测器会为对象分配跟踪 ID,您可以用该 ID 来跨帧跟踪对象。如果您想要跟踪对象,或者对延迟有要求(例如在实时处理视频流时),请使用此模式。
在单图片模式下,对象检测器会在确定对象的边界框后返回结果。如果您还启用了分类,则边界框和类别标签都可用后,它就会返回结果。因此,此模式下的检测延迟可能较高。此外,在单图片模式下,不会分配跟踪 ID。如果不计较延迟高低,且不想处理不完整的结果,请使用此模式。
检测和跟踪多个对象 false
(默认)|true
是检测和跟踪最多五个对象,还是仅检测和跟踪最突出的对象(默认)。
将对象分类 false
(默认)|true
是否对检测到的对象进行粗分类。启用后,对象检测器会将对象分为以下类别:时尚商品、食品、家居用品、地点和植物。
对象检测和跟踪 API 针对以下两个核心用例进行了优化:
- 实时检测和跟踪相机取景器中最突出的对象。
- 检测静态图片中的多个对象。
如需为这些用例配置 API,请执行以下操作:
Swift
// Live detection and tracking let options = ObjectDetectorOptions() options.shouldEnableClassification = true // Multiple object detection in static images let options = ObjectDetectorOptions() options.detectorMode = .singleImage options.shouldEnableMultipleObjects = true options.shouldEnableClassification = true
Objective-C
// Live detection and tracking MLKObjectDetectorOptions *options = [[MLKObjectDetectorOptions alloc] init]; options.shouldEnableClassification = YES; // Multiple object detection in static images MLKObjectDetectorOptions *options = [[MLKOptions alloc] init]; options.detectorMode = MLKObjectDetectorModeSingleImage; options.shouldEnableMultipleObjects = YES; options.shouldEnableClassification = YES;
- 获取
ObjectDetector
的一个实例:
Swift
let objectDetector = ObjectDetector.objectDetector() // Or, to change the default settings: let objectDetector = ObjectDetector.objectDetector(options: options)
Objective-C
MLKObjectDetector *objectDetector = [MLKObjectDetector objectDetector]; // Or, to change the default settings: MLKObjectDetector *objectDetector = [MLKObjectDetector objectDetectorWithOptions:options];
2. 准备输入图片
如需检测和跟踪对象,请对每个图片或视频帧执行以下操作。
如果您启用了流模式,则必须从 CMSampleBuffer
创建 VisionImage
对象。
使用 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. 处理图片
将VisionImage
传递给对象检测器的图片处理方法之一。您可以使用异步 process(image:)
方法或同步 results()
方法。
如需异步检测对象,请执行以下操作:
Swift
objectDetector.process(image) { objects, error in guard error == nil else { // Error. return } guard !objects.isEmpty else { // No objects detected. return } // Success. Get object info here. // ... }
Objective-C
[objectDetector processImage:image completion:^(NSArray* _Nullable objects, NSError * _Nullable error) { if (error == nil) { return; } if (objects.count == 0) { // No objects detected. return; } // Success. Get object info here. }];
要同步检测对象,请执行以下操作:
Swift
var objects: [Object] do { objects = try objectDetector.results(in: image) } catch let error { print("Failed to detect object with error: \(error.localizedDescription).") return } guard !objects.isEmpty else { print("Object detector returned no results.") return } // Success. Get object info here.
Objective-C
NSError *error; NSArray*objects = [objectDetector resultsInImage:image error:&error]; if (error == nil) { return; } if (objects.count == 0) { // No objects detected. return; } // Success. Get object info here.
4. 获取有关检测到的对象的信息
如果对图片处理器的调用成功,它会将Object
列表传递给完成处理程序或返回该列表,具体取决于您调用的是异步方法还是同步方法。
每个 Object
都包含以下属性:
frame |
一个 CGRect ,用于指示图片中对象的位置。 |
trackingID |
一个整数,用于跨图片标识对象,或在单图片模式下标识“nil”。 |
labels |
描述检测器返回对象的标签数组。
如果检测器选项 shouldEnableClassification 设置为 false ,则该属性为空。
|
Swift
// objects contains one item if multiple object detection wasn't enabled. for object in objects { let frame = object.frame let trackingID = object.trackingID // If classification was enabled: let description = object.labels.enumerated().map { (index, label) in "Label \(index): \(label.text), \(label.confidence)" }.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 适用于机器学习所支持功能的格式。
在实时应用中使用流式传输模式时,请遵循以下准则以实现最佳帧速率:
- 请勿在流式传输模式下使用多个对象检测,因为大多数设备无法产生足够的帧速率。
- 如果您不需要,请停用分类。
- 如需处理视频帧,请使用检测器的
results(in:)
同步 API。从AVCaptureVideoDataOutputSampleBufferDelegate
的captureOutput(_, didOutput:from:)
函数调用此方法,以从指定视频帧同步获取结果。将AVCaptureVideoDataOutput
的alwaysDiscardsLateVideoFrames
保留为true
,以限制对检测器的调用。如果在检测器运行时有新视频帧可用,该帧将被丢弃。 - 如果要将检测器的输出作为图形叠加在输入图片上,请先从机器学习套件获取结果,然后在一个步骤中完成图片的呈现和叠加。采用这一方法,每个已处理的输入帧只需在显示表面呈现一次。如需查看示例,请参阅机器学习套件快速入门示例中的 updatePreviewOverlayViewWithLastFrame。