使用自定义分类模型检测、跟踪和分类对象 (iOS)

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

当您将图片传递给机器学习套件时,机器学习套件最多可检测图片中的 5 个对象 以及图像中每个对象的位置。当在 视频流,每个对象都有一个唯一 ID,可用于跟踪 帧的呈现方式

您可以使用自定义图片分类模型来对 。如需了解更多详情,请参阅使用机器学习套件的自定义模型 模型兼容性要求方面的指南、在哪里可以找到预训练模型, 以及如何训练自己的模型。

您可以通过两种方式集成自定义模型。你可以通过以下方式捆绑模型: 将其放入应用的资源文件夹中,也可以动态下载 。下表对这两个选项进行了比较。

捆绑模型 托管的模型
该模型是应用的 .ipa 文件的一部分, 增大其大小 该模型不是应用的 .ipa 文件的一部分。时间是 由上传到 Firebase 机器学习
即使 Android 设备处于离线状态,模型也可立即使用 按需下载模型
无需 Firebase 项目 需要 Firebase 项目
您必须重新发布应用才能更新模型 无需重新发布应用即可推送模型更新
没有内置 A/B 测试 使用 Firebase Remote Config 轻松进行 A/B 测试

试试看

准备工作

  1. 在 Podfile 中添加机器学习套件库:

    如需将模型与应用捆绑,请执行以下操作:

    pod 'GoogleMLKit/ObjectDetectionCustom', '3.2.0'
    

    如需从 Firebase 动态下载模型,请添加 LinkFirebase 依赖项:

    pod 'GoogleMLKit/ObjectDetectionCustom', '3.2.0'
    pod 'GoogleMLKit/LinkFirebase', '3.2.0'
    
  2. 安装或更新项目的 Pod 之后,请打开您的 Xcode 项目 使用其 .xcworkspace。Xcode 13.2.1 版支持机器学习套件 或更高版本。

  3. 如果您想下载模型,请确保 将 Firebase 添加到您的 iOS 项目, (如果您尚未这样做)。将 模型。

1. 加载模型

配置本地模型来源

如需将模型与您的应用捆绑在一起,请执行以下操作:

  1. 将模型文件(通常以 .tflite.lite 结尾)复制到您的 Xcode 项目中,执行此操作时请务必选择 Copy bundle resources。通过 模型文件将包含在应用软件包中,并提供给机器学习套件使用。

  2. 创建 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];

然后,启动模型下载任务,指定 来允许下载如果该设备上没有该型号,或者版本较新的 模型可用时,任务会异步下载 模型:

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

STREAM_MODE(默认)下,对象检测器会运行 但可能会生成不完整的结果(例如 未指定的边界框或类别标签) 检测器的调用。此外,在 STREAM_MODE 中, 检测器会为对象分配跟踪 ID,供您用来 来跨帧跟踪对象。当您想要追踪活动时,可以使用此模式 或者对低延迟很重要,例如在处理 实时流式传输视频。

SINGLE_IMAGE_MODE 中,对象检测器会返回 确定对象的边界框后的结果。如果您 也会启用分类,它会返回 框和类别标签均可使用。因此 检测延迟时间可能更长。此外,在 SINGLE_IMAGE_MODE,未分配跟踪 ID。使用 如果延迟时间不重要,并且您不希望处理 部分结果。

检测和跟踪多个对象 false(默认)|true

是检测和跟踪最多五个对象,还是仅检测和跟踪最多五个对象 醒目对象(默认)。

对对象进行分类 false(默认)|true

是否使用提供的 自定义分类器模型。要使用自定义分类 模型,则需要将其设为 true

分类置信度阈值

已检测到的标签的最低置信度分数。如果未设置,任何 系统将使用模型元数据指定的分类器阈值。 如果模型不包含任何元数据或元数据不包含 则默认阈值为 0.0, 。

每个对象的标签数上限

检测器将为每个对象设置的标签数量上限 return。如果未设置,系统将使用默认值 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. 准备输入图片

使用 UIImageVisionImage CMSampleBuffer

如果您使用 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;
      }
    }
          
  • 使用VisionImage CMSampleBuffer 对象和方向:

    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. 创建并运行对象检测器

  1. 创建新的对象检测器:

    Swift

    let objectDetector = ObjectDetector.objectDetector(options: options)

    Objective-C

    MLKObjectDetector *objectDetector = [MLKObjectDetector objectDetectorWithOptions:options];
  2. 然后,使用检测器:

    异步:

    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 一个整数,用于跨图片标识对象;如果使用的是 `nil`, SINGLE_IMAGE_MODE。
labels
label.text 标签的文本说明。仅当 TensorFlow 加载 精简版模型的元数据包含标签说明。
label.index 标签在 分类器。
label.confidence 对象分类的置信度值。

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 机器学习驱动的特征的模式集合。

提高性能

如果要在实时应用中使用对象检测,请遵循以下 实现最佳帧速率的准则: