在 Apple 平台上使用 AutoML 訓練的模型為圖片加上標籤

使用 AutoML Vision Edge 訓練專屬模型後,即可在應用程式中使用該模型為圖片加上標籤。

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

模型搭售方案
應用程式內建
  • 模型是套裝組合的一部分
  • 即使 Apple 裝置離線,也能立即使用模型
  • 不需要 Firebase 專案
託管於 Firebase
  • 將模型上傳至 Firebase Machine Learning,即可代管模型
  • 縮減 App Bundle 大小
  • 模型會視需要下載
  • 無須重新發布應用程式,即可推送模型更新
  • 使用 Firebase 遠端設定輕鬆進行 A/B 測試
  • 需要 Firebase 專案

事前準備

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

    如要將模型與應用程式組合:

    pod 'GoogleMLKit/ImageLabelingCustom'
    

    如要從 Firebase 動態下載模型,請新增LinkFirebase 依附元件:

    pod 'GoogleMLKit/ImageLabelingCustom'
    pod 'GoogleMLKit/LinkFirebase'
    
  2. 安裝或更新專案的 Pod 後,請使用 .xcworkspace 開啟 Xcode 專案。Xcode 12.2 以上版本支援 ML Kit。

  3. 如要下載模型,請務必將 Firebase 新增至 Android 專案 (如果尚未新增)。如果將模型套裝組合,則不需要這麼做。

1. 載入模型

設定本機模型來源

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

  1. 從您從 Firebase 控制台下載的 ZIP 封存檔中,將模型及其相關中繼資料解壓縮至資料夾:

    your_model_directory
      |____dict.txt
      |____manifest.json
      |____model.tflite
    

    這三個檔案必須位於同一個資料夾中。建議您使用下載的檔案,不要修改檔案 (包括檔案名稱)。

  2. 將資料夾複製到 Xcode 專案,並務必選取「Create folder references」(建立資料夾參照)。模型檔案和中繼資料會納入應用程式套件,供 ML Kit 使用。

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

    Swift

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

    Objective-C

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

設定 Firebase 託管的模型來源

如要使用遠端代管模型,請建立 CustomRemoteModel 物件,並指定您發布模型時指派的名稱:

Swift

// Initialize the model source with the name you assigned in
// the Firebase console.
let remoteModelSource = FirebaseModelSource(name: "your_remote_model")
let remoteModel = CustomRemoteModel(remoteModelSource: remoteModelSource)

Objective-C

// Initialize the model source with the name you assigned in
// the Firebase console.
MLKFirebaseModelSource *firebaseModelSource =
    [[MLKFirebaseModelSource alloc] initWithName:@"your_remote_model"];
MLKCustomRemoteModel *remoteModel =
    [[MLKCustomRemoteModel alloc] initWithRemoteModelSource:firebaseModelSource];

接著啟動模型下載工作,並指定允許下載的條件。如果裝置上沒有模型,或是有更新版本的模型可用,工作會從 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] downloadRemoteModel:remoteModel
                                             conditions:downloadConditions];

許多應用程式會在初始化程式碼中啟動下載工作,但您可以在需要使用模型前的任何時間點執行這項操作。

從模型建立圖片標籤器

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

如果您只有在本機封裝的模型,只要從 LocalModel 物件建立標籤器,並設定您想要求的信賴度分數門檻即可 (請參閱「評估模型」):

Swift

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

Objective-C

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

如果您使用遠端代管模型,請務必先檢查模型是否已下載,再執行模型。您可以使用模型管理工具的 isModelDownloaded(remoteModel:) 方法,檢查模型下載工作的狀態。

雖然您只需要在執行標籤器前確認這項設定,但如果您同時有遠端代管模型和本機模型,在例項化 ImageLabeler 時執行這項檢查可能會有意義:如果已下載遠端模型,請從遠端模型建立標籤器,否則請從本機模型建立。

Swift

var options: CustomImageLabelerOptions
if (ModelManager.modelManager().isModelDownloaded(remoteModel)) {
  options = CustomImageLabelerOptions(remoteModel: remoteModel)
} else {
  options = CustomImageLabelerOptions(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

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

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

您可以將觀察器附加至預設的通知中心,取得模型下載狀態。請務必在觀察器區塊中使用對 self 的弱參照,因為下載作業可能需要一些時間,而原始物件可能會在下載完成前釋出。例如:

Swift

NotificationCenter.default.addObserver(
    forName: .mlkitMLModelDownloadDidSucceed,
    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: .mlkitMLModelDownloadDidFail,
    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. 準備輸入圖片

使用 UIImageCMSampleBufferRef 建立 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;

如果你使用 CMSampleBufferRef,請按照下列步驟操作:

  • 指定 CMSampleBufferRef 緩衝區中圖片資料的方向。

    如要取得圖片方向,請執行下列操作:

    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 position == AVCaptureDevicePositionFront ? UIImageOrientationLeftMirrored
                                                          : UIImageOrientationRight;
    
        case UIDeviceOrientationLandscapeLeft:
          return position == AVCaptureDevicePositionFront ? UIImageOrientationDownMirrored
                                                          : UIImageOrientationUp;
        case UIDeviceOrientationPortraitUpsideDown:
          return position == AVCaptureDevicePositionFront ? UIImageOrientationRightMirrored
                                                          : UIImageOrientationLeft;
        case UIDeviceOrientationLandscapeRight:
          return position == AVCaptureDevicePositionFront ? UIImageOrientationUpMirrored
                                                          : UIImageOrientationDown;
        case UIDeviceOrientationUnknown:
        case UIDeviceOrientationFaceUp:
        case UIDeviceOrientationFaceDown:
          return UIImageOrientationUp;
      }
    }
          
  • 使用 CMSampleBufferRef 物件和方向建立 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<MLKImageLabel *> *_Nullable labels,
                   NSError *_Nullable error) {
        if (label.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<MLKImageLabel *> *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;
}

提升即時成效的訣竅

如要在即時應用程式中標記圖片,請按照下列規範操作,以達到最佳影格速率:

  • 節流對偵測器的呼叫。如果偵測器執行期間有新的影片影格可用,請捨棄該影格。
  • 如果您要使用偵測器的輸出內容,在輸入圖片上疊加圖像,請先取得結果,然後在單一步驟中算繪圖片並疊加圖像。這樣做的話,每個輸入影格只會轉譯到顯示表面一次。如需範例,請參閱展示範例應用程式中的 previewOverlayViewFIRDetectionOverlayView 類別。