Catch up on highlights from Firebase at Google I/O 2023. Learn more

Gắn nhãn hình ảnh bằng mô hình được đào tạo bởi AutoML trên các nền tảng của Apple

Sau khi bạn đào tạo mô hình của riêng mình bằng AutoML Vision Edge , bạn có thể sử dụng nó trong ứng dụng của mình để gắn nhãn hình ảnh.

Có hai cách để tích hợp các mô hình được đào tạo từ AutoML Vision Edge. Bạn có thể gói mô hình bằng cách sao chép các tệp của mô hình vào dự án Xcode của mình hoặc bạn có thể tự động tải xuống từ Firebase.

Tùy chọn gói mô hình
Gói trong ứng dụng của bạn
  • Mô hình là một phần của gói
  • Mô hình có sẵn ngay lập tức, ngay cả khi thiết bị Apple ngoại tuyến
  • Không cần dự án Firebase
Được lưu trữ với Firebase
  • Lưu trữ mô hình bằng cách tải nó lên Firebase Machine Learning
  • Giảm kích thước gói ứng dụng
  • Mô hình được tải xuống theo yêu cầu
  • Đẩy các bản cập nhật mô hình mà không xuất bản lại ứng dụng của bạn
  • Thử nghiệm A/B dễ dàng với Firebase Remote Config
  • Yêu cầu một dự án Firebase

Trước khi bắt đầu

  1. Bao gồm các thư viện ML Kit trong Podfile của bạn:

    Để gói một mô hình với ứng dụng của bạn:

    pod 'GoogleMLKit/ImageLabelingCustom'
    

    Để tự động tải xuống một mô hình từ Firebase, hãy thêm phần phụ thuộc LinkFirebase :

    pod 'GoogleMLKit/ImageLabelingCustom'
    pod 'GoogleMLKit/LinkFirebase'
    
  2. Sau khi bạn cài đặt hoặc cập nhật Pods của dự án, hãy mở dự án Xcode của bạn bằng cách sử dụng .xcworkspace của nó. ML Kit được hỗ trợ trong Xcode phiên bản 12.2 trở lên.

  3. Nếu bạn muốn tải xuống một mô hình , hãy đảm bảo rằng bạn đã thêm Firebase vào dự án Android của mình , nếu bạn chưa làm như vậy. Điều này là không cần thiết khi bạn đóng gói mô hình.

1. Tải mô hình

Định cấu hình nguồn mô hình cục bộ

Để gói mô hình với ứng dụng của bạn:

  1. Trích xuất mô hình và siêu dữ liệu của nó từ kho lưu trữ zip mà bạn đã tải xuống từ bảng điều khiển Firebase vào một thư mục:

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

    Tất cả ba tệp phải nằm trong cùng một thư mục. Chúng tôi khuyên bạn nên sử dụng các tệp khi bạn đã tải chúng xuống mà không sửa đổi (bao gồm cả tên tệp).

  2. Sao chép thư mục vào dự án Xcode của bạn, cẩn thận chọn Tạo tham chiếu thư mục khi bạn làm như vậy. Tệp mô hình và siêu dữ liệu sẽ được bao gồm trong gói ứng dụng và có sẵn cho ML Kit.

  3. Tạo đối tượng LocalModel , chỉ định đường dẫn đến tệp kê khai mô hình:

    Nhanh

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

    Mục tiêu-C

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

Định cấu hình nguồn mô hình được lưu trữ trên Firebase

Để sử dụng mô hình được lưu trữ từ xa, hãy tạo một đối tượng CustomRemoteModel , chỉ định tên mà bạn đã gán cho mô hình khi xuất bản:

Nhanh

// 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)

Mục tiêu-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];

Sau đó, bắt đầu tác vụ tải xuống mô hình, chỉ định các điều kiện mà bạn muốn cho phép tải xuống. Nếu mô hình không có trên thiết bị hoặc nếu có phiên bản mới hơn của mô hình, tác vụ sẽ tải xuống mô hình từ Firebase một cách không đồng bộ:

Nhanh

let downloadConditions = ModelDownloadConditions(
  allowsCellularAccess: true,
  allowsBackgroundDownloading: true
)

let downloadProgress = ModelManager.modelManager().download(
  remoteModel,
  conditions: downloadConditions
)

Mục tiêu-C

MLKModelDownloadConditions *downloadConditions =
    [[MLKModelDownloadConditions alloc] initWithAllowsCellularAccess:YES
                                         allowsBackgroundDownloading:YES];

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

Nhiều ứng dụng bắt đầu tác vụ tải xuống trong mã khởi tạo của chúng nhưng bạn có thể thực hiện việc này bất kỳ lúc nào trước khi cần sử dụng mô hình.

Tạo nhãn hình ảnh từ mô hình của bạn

Sau khi bạn định cấu hình các nguồn mô hình của mình, hãy tạo một đối tượng ImageLabeler từ một trong số chúng.

Nếu bạn chỉ có một mô hình gói cục bộ, chỉ cần tạo một nhãn từ đối tượng LocalModel của bạn và định cấu hình ngưỡng điểm tin cậy mà bạn muốn yêu cầu (xem Đánh giá mô hình của bạn ):

Nhanh

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)

Mục tiêu-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];

Nếu bạn có một mô hình được lưu trữ từ xa, bạn sẽ phải kiểm tra xem nó đã được tải xuống chưa trước khi chạy. Bạn có thể kiểm tra trạng thái của tác vụ tải xuống mô hình bằng phương thức isModelDownloaded(remoteModel:) của trình quản lý mô hình.

Mặc dù bạn chỉ phải xác nhận điều này trước khi chạy trình gắn nhãn, nhưng nếu bạn có cả mô hình được lưu trữ từ xa và mô hình được đóng gói cục bộ, bạn nên thực hiện kiểm tra này khi khởi tạo ImageLabeler : tạo một trình gắn nhãn từ mô hình từ xa nếu đó là đã được tải xuống và từ mô hình cục bộ nếu không.

Nhanh

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)

Mục tiêu-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];

Nếu bạn chỉ có một mô hình được lưu trữ từ xa, thì bạn nên tắt chức năng liên quan đến mô hình—ví dụ: tô xám hoặc ẩn một phần giao diện người dùng của bạn—cho đến khi bạn xác nhận mô hình đã được tải xuống.

Bạn có thể nhận trạng thái tải xuống mô hình bằng cách đính kèm trình quan sát vào Trung tâm thông báo mặc định. Đảm bảo sử dụng một tham chiếu yếu đến self trong khối người quan sát, vì quá trình tải xuống có thể mất một chút thời gian và đối tượng ban đầu có thể được giải phóng khi quá trình tải xuống kết thúc. Ví dụ:

Nhanh

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]
    // ...
}

Mục tiêu-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. Chuẩn bị ảnh đầu vào

Tạo đối tượng VisionImage bằng cách sử dụng UIImage hoặc CMSampleBufferRef .

Nếu bạn sử dụng UIImage , hãy làm theo các bước sau:

  • Tạo đối tượng VisionImage với UIImage . Đảm bảo chỉ định đúng .orientation .

    Nhanh

    let image = VisionImage(image: uiImage)
    visionImage.orientation = image.imageOrientation

    Mục tiêu-C

    MLKVisionImage *visionImage = [[MLKVisionImage alloc] initWithImage:image];
    visionImage.orientation = image.imageOrientation;

Nếu bạn sử dụng CMSampleBufferRef , hãy làm theo các bước sau:

  • Chỉ định hướng của dữ liệu hình ảnh có trong bộ đệm CMSampleBufferRef .

    Để có được hướng hình ảnh:

    Nhanh

    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
      }
    }
          

    Mục tiêu-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;
      }
    }
          
  • Tạo một đối tượng VisionImage bằng cách sử dụng đối tượng và hướng CMSampleBufferRef :

    Nhanh

    let image = VisionImage(buffer: sampleBuffer)
    image.orientation = imageOrientation(
      deviceOrientation: UIDevice.current.orientation,
      cameraPosition: cameraPosition)

    Mục tiêu-C

     MLKVisionImage *image = [[MLKVisionImage alloc] initWithBuffer:sampleBuffer];
     image.orientation =
       [self imageOrientationFromDeviceOrientation:UIDevice.currentDevice.orientation
                                    cameraPosition:cameraPosition];

3. Chạy trình dán nhãn hình ảnh

không đồng bộ:

Nhanh

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

Mục tiêu-C

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

đồng bộ:

Nhanh

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

Mục tiêu-C

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

4. Nhận thông tin về các đối tượng được dán nhãn

Nếu thao tác ghi nhãn hình ảnh thành công, nó sẽ trả về một mảng ImageLabel . Mỗi ImageLabel đại diện cho một cái gì đó đã được gắn nhãn trong hình ảnh. Bạn có thể nhận mô tả văn bản của từng nhãn (nếu có trong siêu dữ liệu của tệp mô hình TensorFlow Lite), điểm tin cậy và chỉ mục. Ví dụ:

Nhanh

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

Mục tiêu-C

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

Mẹo để cải thiện hiệu suất thời gian thực

Nếu bạn muốn gắn nhãn hình ảnh trong ứng dụng thời gian thực, hãy làm theo các hướng dẫn sau để đạt được tốc độ khung hình tốt nhất:

  • Van tiết lưu gọi đến máy dò. Nếu khung hình video mới khả dụng trong khi trình phát hiện đang chạy, hãy bỏ khung hình đó.
  • Nếu bạn đang sử dụng đầu ra của bộ phát hiện để tạo lớp phủ đồ họa trên hình ảnh đầu vào, trước tiên hãy lấy kết quả, sau đó kết xuất hình ảnh và lớp phủ trong một bước duy nhất. Bằng cách đó, bạn chỉ hiển thị lên bề mặt hiển thị một lần cho mỗi khung hình đầu vào. Xem các lớp previewOverlayViewFIRDetectionOverlayView trong ứng dụng mẫu giới thiệu để biết ví dụ.