使用自定义模型给图片加标签 (iOS)

您可以使用机器学习套件识别图片中的实体并添加标签。 此 API 支持各种自定义图片分类模型。请 如需获得以下指导,请参阅使用机器学习套件的自定义模型 模型兼容性要求、在何处找到预训练模型, 以及如何训练自己的模型。

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

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

试试看

准备工作

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

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

    pod 'GoogleMLKit/ImageLabelingCustom', '15.5.0'

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

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

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

1. 加载模型

配置本地模型来源

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

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

  2. 创建 LocalModel 对象,指定模型文件的路径:

    SwiftObjective-C
    let localModel = LocalModel(path: localModelFilePath)
    MLKLocalModel *localModel =
       
    [[MLKLocalModel alloc] initWithPath:localModelFilePath];

配置 Firebase 托管的模型来源

如需使用远程托管的模型,请创建一个 RemoteModel 对象,并指定 您在发布模型时为其分配的名称:

SwiftObjective-C
let firebaseModelSource = FirebaseModelSource(
    name
: "your_remote_model") // The name you assigned in
                               // the Firebase console.
let remoteModel = CustomRemoteModel(remoteModelSource: firebaseModelSource)
MLKFirebaseModelSource *firebaseModelSource =
   
[[MLKFirebaseModelSource alloc]
        initWithName
:@"your_remote_model"]; // The name you assigned in
                                           
// the Firebase console.
MLKCustomRemoteModel *remoteModel =
   
[[MLKCustomRemoteModel alloc]
        initWithRemoteModelSource
:firebaseModelSource];

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

SwiftObjective-C
let downloadConditions = ModelDownloadConditions(
  allowsCellularAccess
: true,
  allowsBackgroundDownloading
: true
)

let downloadProgress = ModelManager.modelManager().download(
  remoteModel
,
  conditions
: downloadConditions
)
MLKModelDownloadConditions *downloadConditions =
   
[[MLKModelDownloadConditions alloc] initWithAllowsCellularAccess:YES
                                         allowsBackgroundDownloading
:YES];

NSProgress *downloadProgress =
   
[[MLKModelManager modelManager] downloadModel:remoteModel
                                       conditions
:downloadConditions];

许多应用会通过其初始化代码启动下载任务,但 可以在需要使用该模型之前随时执行此操作。

配置图片标记器

配置模型来源后,根据模型来源创建 ImageLabeler 对象 。

提供的选项如下:

选项
confidenceThreshold

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

maxResultCount

要返回的标签数上限。如果未设置,则系统将使用默认值 将使用 10。

如果您只有本地捆绑的模型,只需根据 LocalModel 对象:

SwiftObjective-C
let options = CustomImageLabelerOptions(localModel: localModel)
options
.confidenceThreshold = NSNumber(value: 0.0)
let imageLabeler = ImageLabeler.imageLabeler(options: options)
MLKCustomImageLabelerOptions *options =
   
[[MLKCustomImageLabelerOptions alloc] initWithLocalModel:localModel];
options
.confidenceThreshold = @(0.0);
MLKImageLabeler *imageLabeler =
   
[MLKImageLabeler imageLabelerWithOptions:options];

如果您有远程托管的模型,则必须检查该模型 下载应用您可以检查模型下载的状态 使用模型管理器的 isModelDownloaded(remoteModel:) 方法完成任务。

虽然您只需在运行标签添加者之前确认这一点, 同时具有远程托管的模型和本地捆绑的模型, 最好在实例化 ImageLabeler 时执行此检查: 从远程模型添加标签(如果已下载),从本地模型添加 否则。

SwiftObjective-C
var options: CustomImageLabelerOptions!
if (ModelManager.modelManager().isModelDownloaded(remoteModel)) {
  options
= CustomImageLabelerOptions(remoteModel: remoteModel)
} else {
  options
= CustomImageLabelerOptions(localModel: localModel)
}
options
.confidenceThreshold = NSNumber(value: 0.0)
let imageLabeler = ImageLabeler.imageLabeler(options: options)
MLKCustomImageLabelerOptions *options;
if ([[MLKModelManager modelManager] isModelDownloaded:remoteModel]) {
  options
= [[MLKCustomImageLabelerOptions alloc] initWithRemoteModel:remoteModel];
} else {
  options
= [[MLKCustomImageLabelerOptions alloc] initWithLocalModel:localModel];
}
options
.confidenceThreshold = @(0.0);
MLKImageLabeler *imageLabeler =
   
[MLKImageLabeler imageLabelerWithOptions:options];

如果您只有远程托管的模型,则应停用与模型相关的 部分功能(如灰显或隐藏界面的某一部分),直到 您可以确认模型已下载。

您可以将观察者附加到默认值,以获取模型下载状态 通知中心。请务必在观察器中使用对 self 的弱引用 因为下载可能需要一些时间 在下载完成时释放例如:

SwiftObjective-C
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]
   
// ...
}
__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];
           
}];

2. 准备输入图片

使用 UIImageVisionImage CMSampleBuffer

如果您使用 UIImage,请按以下步骤操作:

  • 使用 UIImage 创建一个 VisionImage 对象。请务必指定正确的 .orientation
    SwiftObjective-C
    let image = VisionImage(image: UIImage)
    visionImage
    .orientation = image.imageOrientation
    MLKVisionImage *visionImage = [[MLKVisionImage alloc] initWithImage:image];
    visionImage
    .orientation = image.imageOrientation;

如果您使用 CMSampleBuffer,请按以下步骤操作:

  • 指定 CMSampleBuffer

    如需获取图片方向,请执行以下操作:

    SwiftObjective-C
    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
     
    }
    }
         
    - (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 对象和方向:
    SwiftObjective-C
    let image = VisionImage(buffer: sampleBuffer)
    image
    .orientation = imageOrientation(
      deviceOrientation
    : UIDevice.current.orientation,
      cameraPosition
    : cameraPosition)
     MLKVisionImage *image = [[MLKVisionImage alloc] initWithBuffer:sampleBuffer];
     image
    .orientation =
       
    [self imageOrientationFromDeviceOrientation:UIDevice.currentDevice.orientation
                                    cameraPosition
    :cameraPosition];

3. 运行图片标记器

如需给图片中的对象加标签,请将 image 对象传递给 ImageLabelerprocess() 方法。

异步:

SwiftObjective-C
imageLabeler.process(image) { labels, error in
    guard error
== nil, let labels = labels, !labels.isEmpty else {
       
// Handle the error.
        return
   
}
   
// Show results.
}
[imageLabeler
    processImage
:image
      completion
:^(NSArray

同步:

SwiftObjective-C
var labels: [ImageLabel]
do {
    labels
= try imageLabeler.results(in: image)
} catch let error {
   
// Handle the error.
    return
}
// Show results.
NSError *error;
NSArray

4. 获取已加标签的实体的相关信息

如果给图片加标签操作成功,它会返回 ImageLabel。每个 ImageLabel 都代表 标签。您可以获取每个标签的文本说明(如果有 TensorFlow Lite 模型文件的元数据)、置信度分数和索引。 例如:

SwiftObjective-C
for label in labels {
 
let labelText = label.text
 
let confidence = label.confidence
 
let index = label.index
}
for (MLKImageLabel *label in labels) {
 
NSString *labelText = label.text;
 
float confidence = label.confidence;
 
NSInteger index = label.index;
}

提高实时性能的相关提示

如果要在实时应用中给图片加标签,请遵循以下做法 实现最佳帧速率的准则: