Gắn nhãn hình ảnh bằng mô hình được huấn luyện bằng AutoML trên iOS
Sau khi huấn luyện mô hình của riêng mình bằng AutoML Vision Edge, bạn có thể sử dụng mô hình đó 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 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 tải mô hình xuống một cách linh động từ Firebase.
Tuỳ chọn gói mô hình | |
---|---|
Được đóng gói trong ứng dụng |
|
Được lưu trữ bằng Firebase |
|
Dùng thử
- Hãy thử nghiệm với ứng dụng mẫu để xem ví dụ về cách sử dụng API này.
Trước khi bắt đầu
1. Đưa các thư viện Bộ công cụ học máy vào tệp Podfile:Cách đóng gói mô hình với ứng dụng:
pod 'GoogleMLKit/ImageLabelingAutoML'
LinkFirebase
:
pod 'GoogleMLKit/ImageLabelingAutoML' pod 'GoogleMLKit/LinkFirebase'
.xcworkspace
code>. 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, hãy nhớ thêm Firebase vào dự án iOS nếu bạn chưa thực hiện việc này. Bạn không cần thực hiện việc này khi đó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ộ
Cách gói mô hình với ứng dụng:1. Giải nén 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
2. Sao chép thư mục vào dự án Xcode, nhớ chọn Create folder references (Tạo tệp tham chiếu thư mục) khi bạn thực hiện việc này. Tệp mô hình và siêu dữ liệu sẽ được đưa vào gói ứng dụng và có sẵn cho Bộ công cụ học máy.
3. Tạo đối tượng
AutoMLImageLabelerLocalModel
, chỉ định đường dẫn đến tệp kê khai mô hình:
guard let manifestPath = Bundle.main.path( forResource: "manifest", ofType: "json", inDirectory: "your_model_directory" ) else { return } let localModel = AutoMLImageLabelerLocalModel(manifestPath: manifestPath)
NSString *manifestPath = [NSBundle.mainBundle pathForResource:@"manifest" ofType:@"json" inDirectory:@"your_model_directory"]; MLKAutoMLImageLabelerLocalModel *localModel = [[MLKAutoMLImageLabelerLocalModel alloc] initWithManifestPath:manifestPath];
Định cấu hình nguồn mô hình do Firebase lưu trữ
Để sử dụng mô hình được lưu trữ từ xa, hãy tạo một đối tượng AutoMLImageLabelerRemoteModel
, chỉ định tên mà bạn đã gán cho mô hình khi phát hành:
let remoteModel = AutoMLImageLabelerRemoteModel( name: "your_remote_model" // The name you assigned in // the Firebase console. )
MLKAutoMLImageLabelerRemoteModel *remoteModel = [[MLKAutoMLImageLabelerRemoteModel alloc] initWithName:@"your_remote_model"]; // The name you assigned in // the Firebase console.
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ô hình mới hơn, thì tác vụ sẽ tải mô hình xuống không đồng bộ từ Firebase:
let downloadConditions = ModelDownloadConditions( allowsCellularAccess: true, allowsBackgroundDownloading: true ) let downloadProgress = ModelManager.modelManager().download( remoteModel, conditions: downloadConditions )
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 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 trình gắn nhãn hình ảnh từ mô hì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 đó.
Nếu bạn chỉ có một mô hình được đóng gói cục bộ, bạn chỉ cần tạo một trình gắn nhãn từ đối tượng AutoMLImageLabelerLocalModel
và định cấu hình ngưỡng điểm số tin cậy mà bạn muốn yêu cầu (xem phần Đánh giá chế độ của bạn:
let options = AutoMLImageLabelerOptions(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)
MLKAutoMLImageLabelerOptions *options = [[MLKAutoMLImageLabelerOptions alloc] initWithLocalModel:localModel]; options.confidenceThreshold = @(0.0); // Evaluate your model in the Firebase console // to determine an appropriate value. 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 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ù 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ộ, thì bạn nên thực hiện việc kiểm tra này khi tạo bản sao 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 không.
var options: AutoMLImageLabelerOptions! if (ModelManager.modelManager().isModelDownloaded(remoteModel)) { options = AutoMLImageLabelerOptions(remoteModel: remoteModel) } else { options = AutoMLImageLabelerOptions(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)
MLKAutoMLImageLabelerOptions *options; if ([[MLKModelManager modelManager] isModelDownloaded:remoteModel]) { options = [[MLKAutoMLImageLabelerOptions alloc] initWithRemoteModel:remoteModel]; } else { options = [[MLKAutoMLImageLabelerOptions alloc] initWithLocalModel:localModel]; } options.confidenceThreshold = @(0.0); // Evaluate your model in the Firebase console // to determine an appropriate value. MLKImageLabeler *imageLabeler = [MLKImageLabeler imageLabelerWithOptions:options];
Nếu chỉ có 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ụ: 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.
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 khối trình quan sát, vì quá trình tải xuống có thể 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ụ:
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] // ... }
__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ằngUIImage
. Hãy nhớ chỉ định đúng.orientation
.let image = VisionImage(image: UIImage) visionImage.orientation = image.imageOrientation
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 lấy hướng hình ảnh:
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 } }
- (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 và hướngCMSampleBuffer
:let image = VisionImage(buffer: sampleBuffer) image.orientation = imageOrientation( deviceOrientation: UIDevice.current.orientation, cameraPosition: cameraPosition)
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
Không đồng bộ:
imageLabeler.process(image) { labels, error in guard error == nil, let labels = labels, !labels.isEmpty else { // Handle the error. return } // Show results. }
[imageLabeler processImage:image completion:^(NSArray*_Nullable labels, NSError *_Nullable error) { if (labels.count == 0) { // Handle the error. return; } // Show results. }];
Đồng bộ:
var labels: [ImageLabel] do { labels = try imageLabeler.results(in: image) } catch let error { // Handle the error. return } // Show results.
NSError *error; NSArray*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 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ảngImageLabel
. Mỗi ImageLabel
đại diện cho một đối tượng đượ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ỉ mục.
Ví dụ:
for label in labels { let labelText = label.text let confidence = label.confidence let index = label.index }
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 hình video, hãy sử 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àmcaptureOutput(_, didOutput:from:)
củaAVCaptureVideoDataOutputSampleBufferDelegate
để đồng bộ nhận kết quả từ khung video đã cho. GiữalwaysDiscardsLateVideoFrames
củaAVCaptureVideoDataOutput
ở dạngtrue
để điều tiết các lệnh gọi đến trình phát hiện. Nếu có khung video mới trong khi trình phát hiện đang chạy, khung video đó sẽ bị loại bỏ. - Nếu bạn sử dụng kết quả của trình phát hiện để phủ hình ảnh đồ 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à phủ trong một bước. Bằng cách này, bạn chỉ kết xuất một lần cho mỗi khung đầu vào đã xử lý trên bề mặt hiển thị. 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ụ.