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. Vui lòng tham khảo 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 với mô hình, nơi tìm các mô hình đã 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 này bằng cách đặt mô hình vào trong thư mục thành phần của ứng dụng, hoặc bạn có thể tự động tải mô hình xuống từ Firebase. Bảng sau đây so sánh hai tuỳ chọn.

Mô hình theo gói Mô hình được lưu trữ
Mô hình này là một phần của APK của ứng dụng, giúp tăng kích thước của ứng dụng. Mô hình này không phải là một phần của tệp APK. Dữ liệu này được lưu trữ bằng cách tải lên Công nghệ học máy của Firebase.
Mô hình có sẵn ngay lập tức, ngay cả khi thiết bị Android không có kết nối mạng Mô hình được tải xuống theo yêu cầu
Không cần dự án Firebase Cần có một dự án Firebase
Bạn phải phát hành lại ứng dụng để cập nhật mô hình này Đẩy 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ó thử nghiệm A/B được tích hợp sẵn Dễ dàng 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 thư viện Bộ công cụ học máy vào Podfile:

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

    pod 'GoogleMLKit/ImageLabelingCustom', '3.2.0'
    

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

    pod 'GoogleMLKit/ImageLabelingCustom', '3.2.0'
    pod 'GoogleMLKit/LinkFirebase', '3.2.0'
    
  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 bằng .xcworkspace của dự án. 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 muốn tải một mô hình xuống, hãy nhớ thêm Firebase vào dự án iOS (nếu bạn chưa thực hiện). Bạn không bắt buộc phải 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:

  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 của bạn, hãy nhớ chọn Copy bundle resources khi thực hiện. 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ữ trên Firebase

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

Swift

let firebaseModelSource = FirebaseModelSource(
    name: "your_remote_model") // The name you assigned in
                               // the Firebase console.
let remoteModel = CustomRemoteModel(remoteModelSource: firebaseModelSource)

Objective-C

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

Sau đó, hãy bắt đầu tác vụ tải mô hình xuống, 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 mô hình xuống không đồng bộ 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] downloadModel:remoteModel
                                       conditions:downloadConditions];

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

Định cấu hình công cụ gắn nhãn hình ảnh

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

Bạn có thể chọn trong các phương án sau đây:

Tùy chọn
confidenceThreshold

Điểm số tin cậy tối thiểu của các nhãn đã phát hiện. Nếu bạn không đặt chính sách này, hệ thống sẽ sử dụng mọi ngưỡng của thuật toán phân loại mà siêu dữ liệu của mô hình chỉ định. Nếu mô hình không chứa siêu dữ liệu nào 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 sử dụng.

maxResultCount

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

Nếu chỉ có một mô hình theo gói cục bộ, bạn chỉ cần 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ột mô hình được lưu trữ từ xa, bạn sẽ phải kiểm tra để đảm bảo rằng mô hình đó đã được tải xuống trước khi chạy. Bạn có thể kiểm tra trạng thái của tác vụ tải mô hình xuống bằng phương thức isModelDownloaded(remoteModel:) của trình quản lý mô hình.

Mặc dù 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 gói cục bộ, thì bạn nên thực hiện bước kiểm tra này khi tạo thực thể cho ImageLabeler: tạo trình gắn nhãn từ mô hình từ xa nếu mô hình từ xa đã được tải xuống, ngược lại từ mô hình cục bộ.

Swift

var options: CustomImageLabelerOptions!
if (ModelManager.modelManager().isModelDownloaded(remoteModel)) {
  options = CustomImageLabelerOptions(remoteModel: remoteModel)
} else {
  options = CustomImageLabelerOptions(localModel: localModel)
}
options.confidenceThreshold = NSNumber(value: 0.0)
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.0);
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 chức năng liên quan đến mô hình (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 xác nhận mô hình đã được tải xuống.

Bạn có thể biết trạng thái tải mô hình xuống bằng cách đính kèm đối tượng tiếp nhận dữ liệu vào Trung tâm thông báo mặc định. Hãy nhớ sử dụng tham chiếu yếu đến self trong khối 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 ban đầu có thể được giải phóng khi quá trình tải xuống hoàn tất. Ví dụ:

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. 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 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 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 CMSampleBuffer.

    Cách tải hướng của 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 cách sử dụng đối tượng và hướng CMSampleBuffer:

    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

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

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