برچسبگذاری تصاویر با مدل آموزشدیده AutoML در iOS
پساز اینکه مدل خودتان را بااستفاده از AutoML Vision Edge آموزش دادید، میتوانید از آن در برنامهتان برای برچسبگذاری تصاویر استفاده کنید.
دو روش برای ادغام مدلهای آموزشدیده از AutoML Vision Edge وجود دارد. میتوانید مدل را با کپی کردن فایلهای مدل در پروژه Xcode خود بستهبندی کنید، یا میتوانید آن را بهصورت پویا از Firebase بارگیری کنید.
| گزینههای بستهبندی مدل | |
|---|---|
| در برنامهتان دستهبندی شده است |
|
| میزبانیشده با Firebase |
|
امتحان کنید
- با برنامه نمونه کار کنید تا نمونهای از کاربرد این API را ببینید.
قبلاز شروع
۱. کتابخانههای ML Kit را در Podfile خود اضافه کنید:برای بستهبندی مدل با برنامهتان:
pod 'GoogleMLKit/ImageLabelingAutoML'
LinkFirebase را اضافه کنید:
pod 'GoogleMLKit/ImageLabelingAutoML'
pod 'GoogleMLKit/LinkFirebase'
.xcworkspacecode> آن باز کنید. ML Kit در Xcode نسخه ۱۳.۲.۱ یا بالاتر پشتیبانی میشود.
۳. اگر میخواهید مدلی را بارگیری کنید، حتماً
Firebase را به پروژه iOS خود اضافه کنید،
اگر قبلاً این کار را نکردهاید. این کار هنگام بستهبندی مدل لازم نیست.
۱. بار کردن مدل
پیکربندی منبع مدل محلی
برای بستهبندی مدل با برنامهتان:۱. مدل و فراداده آن را از بایگانی zip که از کنسول Firebase بارگیری کردهاید در پوشهای استخراج کنید:
your_model_directory
|____dict.txt
|____manifest.json
|____model.tflite
۲. پوشه را در پروژه Xcode خود کپی کنید و دقت کنید که هنگام انجام این کار، ایجاد ارجاعات پوشه را انتخاب کنید. فایل مدل و فراداده در بسته برنامه گنجانده خواهد شد و برای ML Kit دردسترس خواهد بود.
۳. شیء
AutoMLImageLabelerLocalModel را ایجاد کنید و مسیر فایل مانیفست مدل را مشخص کنید:
Swift
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];
پیکربندی منبع مدل میزبانیشده در Firebase
برای استفاده از مدل میزبانیشده ازراهدور، یک شیء AutoMLImageLabelerRemoteModel
ایجاد کنید و نامی را که هنگام انتشار مدل به آن اختصاص دادهاید مشخص کنید:
Swift
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.
سپس، تکلیف بارگیری مدل را شروع کنید و شرایطی را که میخواهید بارگیری تحت آن مجاز باشد مشخص کنید. اگر مدل در دستگاه نباشد، یا اگر نسخه جدیدتری از مدل دردسترس باشد، تکلیف بهصورت ناهمگام مدل را از Firebase بارگیری خواهد کرد:
Swift
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];
بسیاری از برنامهها تکلیف بارگیری را در کد مقداردهی اولیه خود شروع میکنند، اما شما میتوانید این کار را در هر نقطهای قبلاز نیاز به استفاده از مدل انجام دهید.
ایجاد برچسبزن تصویر از مدل شما
پساز پیکربندی منابع مدل، یک شیء ImageLabeler از یکی از آنها ایجاد کنید.
اگر فقط مدل بستهبندیشده محلی دارید، کافی است برچسبزنی از شیء AutoMLImageLabelerLocalModel خود ایجاد کنید و آستانه امتیاز اطمینانی را که میخواهید الزامی باشد پیکربندی کنید (ارزیابی حالت را ببینید:
Swift
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];
اگر مدل با میزبانی از راه دور دارید، باید قبلاز اجرای آن بررسی کنید که بارگیری شده باشد. میتوانید وضعیت تکلیف بارگیری مدل را بااستفاده از روش isModelDownloaded(remoteModel:) مدیر مدل بررسی کنید.
اگرچه فقط باید این را قبلاز اجرای برچسبزن تأیید کنید، اگر هم مدل میزبانیشده از راه دور و هم مدل بستهبندیشده محلی دارید، ممکن است منطقی باشد که این بررسی را هنگام نمونهسازی ImageLabeler انجام دهید: اگر مدل از راه دور بارگیری شده است، برچسبزن را از آن ایجاد کنید، و درغیراینصورت از مدل محلی ایجاد کنید.
Swift
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];
اگر فقط مدل میزبانیشده ازراهدور دارید، باید عملکرد مربوط به مدل را غیرفعال کنید (مثلاً بخشی از میانای کاربر را خاکستری یا پنهان کنید) تا زمانی که تأیید کنید مدل بارگیری شده است.
میتوانید با پیوست کردن ناظران به «مرکز اعلانها»ی پیشفرض، وضعیت بارگیری مدل را دریافت کنید. حتماً از ارجاع ضعیف به self در بلوک ناظر استفاده کنید، زیرا بارگیریها ممکن است مدتی طول بکشد و شیء مبدأ ممکن است تا زمان اتمام بارگیری آزاد شود. برای مثال:
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] // ... }
آبجکتیو-سی
__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]; }];
۲. آماده کردن تصویر ورودی
بااستفاده از UIImage یا CMSampleBuffer، شیء VisionImage ایجاد کنید.
اگر از UIImage استفاده میکنید، این مراحل را دنبال کنید:
- یک شیء
VisionImageباUIImageایجاد کن. حتماً.orientationصحیح را مشخص کنید.Swift
let image = VisionImage(image: UIImage) visionImage.orientation = image.imageOrientation
آبجکتیو-سی
MLKVisionImage *visionImage = [[MLKVisionImage alloc] initWithImage:image]; visionImage.orientation = image.imageOrientation;
اگر از CMSampleBuffer استفاده میکنید، این مراحل را دنبال کنید:
-
جهت دادههای تصویر موجود در
CMSampleBufferرا مشخص کنید.برای دریافت جهت تصویر:
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 } }
آبجکتیو-سی
- (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; } }
- ایجاد شیء
VisionImageبااستفاده از شیءCMSampleBufferو جهت:Swift
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];
۳. اجرای برچسبزن تصویر
ناهمگام:
Swift
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. }];
همزمان:
Swift
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.
۴. دریافت اطلاعات درباره اشیای برچسبگذاریشده
اگر عملیات برچسبگذاری تصویر موفقیتآمیز باشد، آرایهای ازImageLabel را برمیگرداند. هر ImageLabel نشاندهنده چیزی است که در تصویر برچسبگذاری شده است. میتوانید شرح نوشتاری هر برچسب (درصورت وجود در فراداده فایل مدل TensorFlow Lite)، امتیاز اطمینان، و نمایه را دریافت کنید.
برای مثال:
Swift
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; }
نکاتی برای بهبود عملکرد همزمان
اگر میخواهید تصاویر را در یک برنامه همزمان برچسبگذاری کنید، این دستورالعملها را دنبال کنید تا به بهترین نرخ فریم دست یابید:
- برای پردازش فریمهای ویدیو، از
results(in:)API همگام آشکارساز استفاده کنید. این روش را از تابعcaptureOutput(_, didOutput:from:)مربوط بهAVCaptureVideoDataOutputSampleBufferDelegateفراخوانی کنید تا نتایج را بهصورت همگام از فریم ویدیو دادهشده دریافت کنید. KeepAVCaptureVideoDataOutput'salwaysDiscardsLateVideoFramesastrueto throttle calls to the detector. اگر درحین اجرای آشکارساز، فریم ویدیویی جدیدی دردسترس قرار گیرد، آن فریم حذف خواهد شد. - اگر از خروجی آشکارساز برای همپوشانی گرافیک روی تصویر ورودی استفاده میکنید، ابتدا نتیجه را از ML Kit دریافت کنید، سپس تصویر و همپوشانی را در یک مرحله رندر کنید. با انجام این کار، فقط یک بار برای هر فریم ورودی پردازششده، به سطح نمایشگر رندر میکنید. برای نمونه، updatePreviewOverlayViewWithLastFrame را در نمونه شروع سریع ML Kit ببینید.