在 iOS 中使用 AutoML 訓練模型為圖片加上標籤

使用 AutoML Vision Edge 訓練自己的模型後,即可在應用程式中使用它來為圖片加上標籤。

有兩種方式可以整合透過 AutoML Vision Edge 訓練的模型。您可以將模型檔案複製到 Xcode 專案來封裝模型,也可以從 Firebase 動態下載。

模型組合選項
應用程式套件
  • 模型是套裝組合的一部分
  • 即使 iOS 裝置離線,也能立即使用該型號
  • 不需要 Firebase 專案
透過 Firebase 代管
  • 將模型上傳至 Firebase Machine Learning 來託管模型
  • 縮減應用程式套件大小
  • 模型按需求下載
  • 不必重新發布應用程式即可推送模型更新
  • 使用 Firebase 遠端設定輕鬆進行 A/B 測試
  • 需要 Firebase 專案

立即體驗

事前準備

1. 在 Podfile 中加入 ML Kit 程式庫:

如要將模型與應用程式組合在一起:
    pod 'GoogleMLKit/ImageLabelingAutoML'
    
如要從 Firebase 動態下載模型,請新增 LinkFirebase 依附元件:
    pod 'GoogleMLKit/ImageLabelingAutoML'
    pod 'GoogleMLKit/LinkFirebase'
    
2. 安裝或更新專案的 Pod 後,請使用其 .xcworkspacecode> 開啟 Xcode 專案。Xcode 13.2.1 以上版本支援 ML Kit。3. 如要下載模型,請務必將 Firebase 新增至 iOS 專案 (如果尚未新增)。加入模型組合時不需要這項操作。

1. 載入模型

設定本機模型來源

如要將模型與應用程式整合,請按照下列步驟操作:

1. 從您從 Firebase 控制台下載的 ZIP 封存檔中,將模型及其中繼資料擷取到資料夾:
    your_model_directory
      |____dict.txt
      |____manifest.json
      |____model.tflite
    
這三個檔案都必須位於同一個資料夾中。建議您在未經修改的情況下直接使用下載檔案 (包括檔案名稱)。

2. 將資料夾複製到 Xcode 專案,並在建立時選取「建立資料夾參照」。模型檔案和中繼資料將包含在應用程式套件中,可供 ML Kit 使用。

3. 建立 AutoMLImageLabelerLocalModel 物件,指定模型資訊清單檔案的路徑:

Swift

guard let manifestPath = Bundle.main.path(
    forResource: "manifest",
    ofType: "json",
    inDirectory: "your_model_directory"
) else { return }
let localModel = AutoMLImageLabelerLocalModel(manifestPath: manifestPath)

Objective-C

NSString *manifestPath =
    [NSBundle.mainBundle pathForResource:@"manifest"
                                  ofType:@"json"
                             inDirectory:@"your_model_directory"];
MLKAutoMLImageLabelerLocalModel *localModel =
    [[MLKAutoMLImageLabelerLocalModel alloc] initWithManifestPath:manifestPath];

設定 Firebase 託管的模型來源

如要使用遠端託管模型,請建立 AutoMLImageLabelerRemoteModel 物件,指定您發布模型時為其指派的名稱:

Swift

let remoteModel = AutoMLImageLabelerRemoteModel(
    name: "your_remote_model"  // The name you assigned in
                               // the Firebase console.
)

Objective-C

MLKAutoMLImageLabelerRemoteModel *remoteModel =
    [[MLKAutoMLImageLabelerRemoteModel alloc]
        initWithName:@"your_remote_model"];  // The name you assigned in
                                             // the Firebase console.

接著,啟動模型下載工作,指定您允許下載的條件。如果裝置上沒有模型,或是可使用新版模型,工作就會以非同步方式從 Firebase 下載模型:

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];

許多應用程式會在初始化程式碼中啟動下載工作,但您也可以在需要使用模型之前隨時執行下載作業。

使用模型建立圖片標籤器

設定模型來源後,請從其中一個來源建立 ImageLabeler 物件。

如果您只有本機組合模型,請直接透過 AutoMLImageLabelerLocalModel 物件建立標籤工具,並設定所需的可信度分數門檻 (請參閱「評估模式」一節:

Swift

let options = AutoMLImageLabelerOptions(localModel: localModel)
options.confidenceThreshold = NSNumber(value: 0.0)  // Evaluate your model in the Firebase console
                                                    // to determine an appropriate value.
let imageLabeler = ImageLabeler.imageLabeler(options: options)

Objective-C

MLKAutoMLImageLabelerOptions *options =
    [[MLKAutoMLImageLabelerOptions alloc] initWithLocalModel:localModel];
options.confidenceThreshold = @(0.0);  // Evaluate your model in the Firebase console
                                       // to determine an appropriate value.
MLKImageLabeler *imageLabeler =
    [MLKImageLabeler imageLabelerWithOptions:options];

如果您有遠端託管的模型,則必須在執行之前先檢查是否已下載該模型。您可以使用模型管理員的 isModelDownloaded(remoteModel:) 方法檢查模型下載工作的狀態。

雖然您只需要在執行標籤器之前確認這一點,但如果您同時擁有遠端託管模型和本機組合模型,則在將 ImageLabeler 執行個體化時,執行這項檢查可能很合理:如果您已下載完畢,就會從遠端模型建立標籤器;若是下載完畢,則從本機模型建立標籤器。

Swift

var options: AutoMLImageLabelerOptions!
if (ModelManager.modelManager().isModelDownloaded(remoteModel)) {
  options = AutoMLImageLabelerOptions(remoteModel: remoteModel)
} else {
  options = AutoMLImageLabelerOptions(localModel: localModel)
}
options.confidenceThreshold = NSNumber(value: 0.0)  // Evaluate your model in the Firebase console
                                                    // to determine an appropriate value.
let imageLabeler = ImageLabeler.imageLabeler(options: options)

Objective-C

MLKAutoMLImageLabelerOptions *options;
if ([[MLKModelManager modelManager] isModelDownloaded:remoteModel]) {
  options = [[MLKAutoMLImageLabelerOptions alloc] initWithRemoteModel:remoteModel];
} else {
  options = [[MLKAutoMLImageLabelerOptions alloc] initWithLocalModel:localModel];
}
options.confidenceThreshold = @(0.0);  // Evaluate your model in the Firebase console
                                       // to determine an appropriate value.
MLKImageLabeler *imageLabeler =
    [MLKImageLabeler imageLabelerWithOptions:options];

如果您只有遠端託管模型,請停用模型相關功能 (例如顯示為灰色或隱藏部分 UI),直到確認模型下載完畢為止。

將觀察器附加至預設通知中心,即可取得模型下載狀態。由於下載作業可能需要一些時間,您可以在下載完成後將來源物件釋出,因此請務必在觀察器區塊中使用低強度的 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];
            }];

2. 準備輸入圖片

使用 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. 執行映像檔標籤工具

非同步:

Swift

imageLabeler.process(image) { labels, error in
    guard error == nil, let labels = labels, !labels.isEmpty else {
        // Handle the error.
        return
    }
    // Show results.
}

Objective-C

[imageLabeler
    processImage:image
      completion:^(NSArray *_Nullable labels,
                   NSError *_Nullable error) {
        if (labels.count == 0) {
            // Handle the error.
            return;
        }
        // Show results.
     }];

同步:

Swift

var labels: [ImageLabel]
do {
    labels = try imageLabeler.results(in: image)
} catch let error {
    // Handle the error.
    return
}
// Show results.

Objective-C

NSError *error;
NSArray *labels =
    [imageLabeler resultsInImage:image error:&error];
// Show results or handle the error.

4. 取得已加上標籤物件的相關資訊

如果圖片標籤作業成功,就會傳回 ImageLabel 的陣列。每個 ImageLabel 都代表映像檔中已加上標籤的項目。您可以取得每個標籤的文字說明 (如果 TensorFlow Lite 模型檔案的中繼資料有這項資訊)、可信度分數和索引,例如:

Swift

for label in labels {
  let labelText = label.text
  let confidence = label.confidence
  let index = label.index
}

Objective-C

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

改善即時成效的訣竅

如要在即時應用程式中為圖片加上標籤,請按照下列指南操作,以達到最佳影格速率: