使用机器学习套件检测和跟踪对象 (iOS)

您可以使用机器学习套件检测和跟踪连续视频帧中的对象。

当您将图片传递给机器学习套件时,机器学习套件会检测图片中的最多五个对象以及图片中每个对象的位置。检测视频流中的对象时,每个对象都有一个唯一 ID,您可以使用该 ID 逐帧跟踪对象。您还可以选择启用粗略对象分类,即使用宽泛的类别描述给对象加标签。

试试看

准备工作

  1. 在您的 Podfile 中添加以下机器学习套件 Pod:
    pod 'GoogleMLKit/ObjectDetection', '3.2.0'
    
  2. 安装或更新项目的 Pod 之后,请使用 Xcode 项目的 .xcworkspace 来打开项目。Xcode 12.4 版或更高版本支持机器学习套件。

1. 配置对象检测器

如需检测和跟踪对象,请先创建一个 ObjectDetector 实例,并视需要更改检测器默认设置。

  1. 使用 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;
  1. 获取 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 对象。

使用 UIImageCMSampleBuffer 创建一个 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