Gắn nhãn hình ảnh bằng mô hình tùy chỉnh trên iOS

Bạn có thể dùng Bộ công cụ học máy để nhận dạng các thực thể trong hình ảnh và gắn nhãn cho các thực thể đó. API này hỗ trợ nhiều mô hình phân loại hình ảnh tuỳ chỉnh. Hãy tham khảo bài viết Mô hình tuỳ chỉnh bằng Bộ công cụ học máy để biết hướng dẫn về các yêu cầu về khả năng tương thích của mô hình, nơi tìm các mô hình được huấn luyện trước, và cách huấn luyện mô hình của riêng bạn.

Có 2 cách để tích hợp mô hình tuỳ chỉnh. Bạn có thể gói mô hình bằng cách đặt mô hình đó vào thư mục tài sản của ứng dụng hoặc bạn có thể tải mô hình đó xuống một cách linh hoạt từ Cloud Storage. Bảng sau đây so sánh 2 lựa chọn này.

Mô hình được gói Mô hình được lưu trữ
Mô hình này là một phần của APK ứng dụng, làm tăng kích thước của APK. Mô hình này không phải là một phần của APK. Mô hình này được lưu trữ bằng cách tải lên Cloud Storage. Bạn nên dùng Cloud Storage cho Firebase.
Mô hình này có sẵn ngay lập tức, ngay cả khi thiết bị Android không kết nối mạng Ứng dụng của bạn phải có mã để tải mô hình xuống theo yêu cầu
Không cần dự án Firebase Yêu cầu dự án Firebase (nếu dùng Cloud Storage cho Firebase).
Bạn phải phát hành lại ứng dụng để cập nhật mô hình Đẩy các bản cập nhật mô hình mà không cần phát hành lại ứng dụng
Không có tính năng thử nghiệm A/B tích hợp Thử nghiệm A/B bằng Cấu hình từ xa Firebase

Dùng thử

Trước khi bắt đầu

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

    pod 'GoogleMLKit/ImageLabelingCustom', '8.0.0'
    
  2. Sau khi cài đặt hoặc cập nhật Pod của dự án, hãy mở dự án Xcode bằng .xcworkspace. Bộ công cụ học máy được hỗ trợ trong Xcode phiên bản 13.2.1 trở lên.

  3. Nếu bạn muốn tải mô hình xuống bằng Cloud Storage cho Firebase, hãy nhớ thêm Firebase vào dự án iOS, nếu bạn chưa làm việc này. Bạn không cần làm việc này khi gói mô hình.

1. Tải mô hình

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

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

  1. Sao chép tệp mô hình (thường kết thúc bằng .tflite hoặc .lite) vào dự án Xcode, nhớ chọn Copy bundle resources khi bạn làm việc này. Tệp mô hình sẽ được đưa vào gói ứng dụng và có sẵn cho Bộ công cụ học máy.

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

    Swift

    let localModel = LocalModel(path: localModelFilePath)

    Objective-C

    MLKLocalModel *localModel =
        [[MLKLocalModel alloc] initWithPath:localModelFilePath];

Định cấu hình nguồn mô hình được lưu trữ từ xa

Để sử dụng mô hình được lưu trữ từ xa, bạn phải tải tệp mô hình xuống bộ nhớ cục bộ của thiết bị bằng logic ứng dụng của riêng bạn, sau đó tải tệp đó dưới dạng mô hình cục bộ. Bạn nên dùng Cloud Storage cho Firebase để lưu trữ mô hình. Để biết thông tin chi tiết về cách triển khai, hãy xem hướng dẫn di chuyển từ Firebase ML sang Cloud Storage.

Định cấu hình trình gắn nhãn hình ảnh

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

Bạn có các tuỳ chọn sau đây:

Tùy chọn
confidenceThreshold

Điểm tin cậy tối thiểu của các nhãn được phát hiện. Nếu bạn không đặt điểm này, thì ngưỡng phân loại do siêu dữ liệu của mô hình chỉ định sẽ được dùng. Nếu mô hình không chứa siêu dữ liệu hoặc siêu dữ liệu không chỉ định ngưỡng phân loại, thì ngưỡng mặc định là 0.0 sẽ được dùng.

maxResultCount

Số lượng nhãn tối đa cần trả về. Nếu bạn không đặt số này, thì giá trị mặc định là 10 sẽ được dùng.

Nếu bạn chỉ có một mô hình được gói cục bộ, hãy tạo một trình gắn nhãn từ đối tượng LocalModel:

Swift

let options = CustomImageLabelerOptions(localModel: localModel)
options.confidenceThreshold = NSNumber(value: 0.0)
let imageLabeler = ImageLabeler.imageLabeler(options: options)

Objective-C

MLKCustomImageLabelerOptions *options =
    [[MLKCustomImageLabelerOptions alloc] initWithLocalModel:localModel];
options.confidenceThreshold = @(0.0);
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 hay chưa trước khi chạy.

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 có cả mô hình được lưu trữ từ xa và mô hình được gói cục bộ, thì bạn nên thực hiện bước kiểm tra này khi khởi tạo ImageLabeler: tạo trình 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 chưa.

Swift

// Path where your download logic saves the model
let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let localModelURL = documentDirectory.appendingPathComponent("my_remote_model.tflite")

let model: LocalModel
if FileManager.default.fileExists(atPath: localModelURL.path) {
  // Use the downloaded model
  model = LocalModel(path: localModelURL.path)
} else {
  // Fall back to bundled model
  guard let bundledModelPath = Bundle.main.path(forResource: "model", ofType: "tflite") else { return }
  model = LocalModel(path: bundledModelPath)
}

let options = CustomImageLabelerOptions(localModel: model)
let imageLabeler = ImageLabeler.imageLabeler(options: options)

Objective-C

NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSString *localModelPath = [documentsDirectory stringByAppendingPathComponent:@"my_remote_model.tflite"];

MLKLocalModel *model;
if ([NSFileManager.defaultManager fileExistsAtPath:localModelPath]) {
  // Use the downloaded model
  model = [[MLKLocalModel alloc] initWithPath:localModelPath];
} else {
  // Fall back to bundled model
  NSString *bundledModelPath = [NSBundle.mainBundle pathForResource:@"model" ofType:@"tflite"];
  model = [[MLKLocalModel alloc] initWithPath:bundledModelPath];
}

MLKCustomImageLabelerOptions *options = [[MLKCustomImageLabelerOptions alloc] initWithLocalModel:model];
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ụ: làm mờ hoặc ẩn một phần giao diện người dùng) cho đến khi xác nhận mô hình đã được tải xuống.

Swift

let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let localModelURL = documentDirectory.appendingPathComponent("my_remote_model.tflite")
if FileManager.default.fileExists(atPath: localModelURL.path) {
  // Model is already cached, initialize immediately
  self.initializeLabeler(with: localModelURL)
} else {
  // Model is not yet available, show loading UI and start download
  self.showLoadingUI()
  let storage = Storage.storage()
  let modelRef = storage.reference(forURL: "gs://YOUR_BUCKET/path/to/model.tflite")
  modelRef.write(toFile: localModelURL) { url, error in
    self.hideLoadingUI()
    if let error = error {
      // Handle download error
      self.showErrorUI()
    } else if let modelURL = url {
      // Download success, initialize labeler
      self.initializeLabeler(with: modelURL)
    }
  }
}

func initializeLabeler(with modelURL: URL) {
  let localModel = LocalModel(path: modelURL.path)
  let options = CustomImageLabelerOptions(localModel: localModel)
  self.imageLabeler = ImageLabeler.imageLabeler(options: options)
  // Enable ML-related UI features here
  self.enableMLFeatures()
}

Objective-C

NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSString *localModelPath = [documentsDirectory stringByAppendingPathComponent:@"my_remote_model.tflite"];
NSURL *localModelURL = [NSURL fileURLWithPath:localModelPath];

if ([NSFileManager.defaultManager fileExistsAtPath:localModelPath]) {
  // Model is already cached, initialize immediately
  [self initializeLabelerWithURL:localModelURL];
} else {
  // Model is not yet available, show loading UI and start download
  [self showLoadingUI];

  FIRStorage *storage = [FIRStorage storage];
  FIRStorageReference *modelRef = [storage referenceForURL:@"gs://YOUR_BUCKET/path/to/model.tflite"];

  [modelRef writeToFile:localModelURL
             completion:^(NSURL * _Nullable URL, NSError * _Nullable error) {
               [self hideLoadingUI];
               if (error != nil) {
                 // Handle download error
                 [self showErrorUI];
               } else {
                 // Download success, initialize labeler
                 [self initializeLabelerWithURL:URL];
               }
             }];
}

- (void)initializeLabelerWithURL:(NSURL *)modelURL {
  MLKLocalModel *localModel = [[MLKLocalModel alloc] initWithPath:modelURL.path];
  MLKCustomImageLabelerOptions *options = [[MLKCustomImageLabelerOptions alloc] initWithLocalModel:localModel];
  self.imageLabeler = [MLKImageLabeler imageLabelerWithOptions:options];

  // Enable ML-related UI features here
  [self enableMLFeatures];
}

2. Chuẩn bị hình ảnh đầu vào

Tạo đối tượng VisionImage bằng UIImage hoặc CMSampleBuffer.

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

  • Tạo đối tượng VisionImage bằng UIImage. Nhớ chỉ định .orientation chính xác.

    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 dùng CMSampleBuffer, hãy làm theo các bước sau:

  • Chỉ định hướng của dữ liệu hình ảnh có trong the CMSampleBuffer.

    Cách lấy hướng hình ả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 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;
      }
    }
          
  • Tạo đối tượng VisionImage bằng đối tượng CMSampleBuffer và hướng:

    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 trình gắn nhãn hình ảnh

Để gắn nhãn các đối tượng trong hình ảnh, hãy truyền đối tượng image đến phương thức process() của ImageLabeler.

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 *_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 *labels =
    [imageLabeler resultsInImage:image error:&error];
// Show results or handle the error.

4. Xem thông tin về các thực thể được gắn nhãn

Nếu thao tác gắn nhãn hình ảnh thành công, thì thao tác này sẽ trả về một mảng ImageLabel. Mỗi ImageLabel đại diện cho một nội dung đượ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 LiteRT), điểm tin cậy và chỉ mục. 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 hình ảnh trong ứng dụng theo thời gian thực, hãy làm theo các nguyên tắc sau để đạt được tốc độ khung hình tốt nhất:

  • Để xử lý khung video, hãy dùng API đồng bộ results(in:) của trình phát hiện. Gọi phương thức này từ hàm AVCaptureVideoDataOutputSampleBufferDelegate's captureOutput(_, didOutput:from:) để nhận kết quả một cách đồng bộ từ khung video đã cho. Giữ AVCaptureVideoDataOutput của alwaysDiscardsLateVideoFrames ở trạng thái true để điều tiết các lệnh gọi đến trình phát hiện. Nếu có một khung video mới trong khi trình phát hiện đang chạy, thì khung đó sẽ bị loại bỏ.
  • Nếu bạn dùng kết quả 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ả từ Bộ công cụ học máy, sau đó kết xuất hình ảnh và lớp phủ trong một bước. Bằng cách này, bạn chỉ kết xuất vào bề mặt hiển thị một lần cho mỗi khung đầu vào đã xử lý. Hãy xem updatePreviewOverlayViewWithLastFrame trong mẫu bắt đầu nhanh của Bộ công cụ học máy để biết ví dụ.