Gắn nhãn hình ảnh bằng mô hình được huấn luyện bằng AutoML trên các nền tảng của Apple

Sau khi bạn huấn luyện mô hình của mình bằng AutoML Vision Edge, bạn có thể dùng mẫu này trong ứng dụng của mình để gắn nhãn cho hình ảnh.

Có hai cách để tích hợp các mô hình được huấn luyện 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 hoặc bạn có thể tự động tải ứng dụng đó xuống từ Firebase.

Tuỳ chọn nhóm mô hình
Được tích hợp trong ứng dụng của bạn
  • Mô hình nằm trong gói
  • Mẫu sản phẩm sẽ dùng được ngay lập tức, ngay cả khi thiết bị Apple không kết nối mạng
  • Không cần tạo dự án Firebase
Được lưu trữ bằng Firebase
  • Lưu trữ mô hình bằng cách tải mô hình lên Công nghệ học máy của Firebase
  • Giảm kích thước gói ứng dụng
  • Mô hình này được tải xuống theo yêu cầu
  • Cập nhật mô hình mà không cần xuất bản lại ứng dụng
  • Dễ dàng thử nghiệm A/B bằng Cấu hình từ xa Firebase
  • Cần có một dự án Firebase

Trước khi bắt đầu

  1. Thêm các thư viện Bộ công cụ học máy vào Podfile của bạn:

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

    pod 'GoogleMLKit/ImageLabelingCustom'
    

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

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

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

1. Tải mô hình

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

Cách đóng gói mô hình với ứng dụng:

  1. Trích xuất mô hình và siêu dữ liệu của mô hình từ tệp 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
    

    Cả 3 tệp phải nằm trong cùng một thư mục. Bạn nên dùng những tệp này khi bạn tải xuống mà không sửa đổi (bao gồm tên tệp).

  2. Sao chép thư mục vào dự án Xcode của bạn, nhớ chọn Tạo tệp 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ó trong gói ứng dụng và được cung cấp trong Bộ công cụ học máy.

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

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

Đị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 CustomRemoteModel , chỉ định tên mà bạn đã chỉ định cho mô hình khi xuất bản:

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

Sau đó, bắt đầu tác vụ tải mô hình xuống, chỉ định các điều kiện mà theo đó mà bạn muốn cho phép tải xuống. Nếu kiểu máy này không có trên thiết bị hoặc nếu là kiểu máy mới hơn phiên bản của mô hình sẵn có, tác vụ sẽ tải xuống không đồng bộ mô hình từ 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];

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

Tạo công cụ gắn 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, hãy tạo đối tượng ImageLabeler từ một đối tượng trong số chúng.

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

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

Nếu có mô hình được lưu trữ từ xa, bạn sẽ phải kiểm tra xem mô hình đó đã được tải xuống trước khi chạy nó. Bạn có thể kiểm tra trạng thái tải mô hình xuống bằng cách sử dụ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 nhãn, nếu bạn có cả mô hình được lưu trữ từ xa và mô hình được gói cục bộ, ý nghĩa để thực hiện bước ki��m tra này khi tạo thực thể cho ImageLabeler: tạo một công cụ gắn nhãn từ mô hình từ xa nếu mô hình đã được t��i xuống và từ mô hình cục bộ nếu không.

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

Nếu chỉ có một mô hình được lưu trữ từ xa, bạn nên tắt tính năng liên quan đến mô hình đó chức năng (ví dụ: chuyển sang màu xám hoặc ẩn một phần giao diện người dùng) 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 mô hình xuống bằng cách đính kèm trình quan sát vào Trung tâm thông báo mặc định. Hãy nhớ sử dụng tệp tham chiếu yếu đến self trong trình 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 gốc có thể được giải phóng vào thời điểm hoàn tất tải xuống. Ví dụ:

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. Chuẩn bị hình ảnh đầu vào

Tạo đối tượng VisionImage bằ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 bằng UIImage. Hãy nhớ chỉ định đúng .orientation.

    Swift

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

    Objective-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 Vùng đệm CMSampleBufferRef.

    Cách lấy hướng ảnh:

    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;
      }
    }
          
  • Tạo đối tượng VisionImage bằng Đối tượng và hướng CMSampleBufferRef:

    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. Chạy công cụ gắn nhãn hình ảnh

Không đồng bộ:

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

Đồng bộ:

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. Nhận thông tin về đối tượng được gắn nhãn

Nếu thành công, thao tác gắn nhãn hình ảnh sẽ trả về một mảng ImageLabel. Mỗi ImageLabel đại diện cho một nội dung nào đó được gắn nhãn trong hình ảnh. Bạn có thể xem nội dung mô tả bằng 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ỉ số. Ví dụ:

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

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

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

  • Điều tiết lệnh gọi đến trình phát hiện. Nếu một khung video mới trong khi trình phát hiện đang chạy, hãy thả khung hình.
  • Nếu bạn đang sử dụng đầu ra của trình phát hiện để phủ đồ hoạ lê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à phủ lên trên trong một bước duy nhất. Nhờ vậy, bạn sẽ kết xuất lên giao diện màn hình một lần cho mỗi khung đầu vào. Xem previewOverlayViewFIRDetectionOverlayView trong ứng dụng mẫu Showcase.