AutoML でトレーニングされたモデルを使用して画像にラベルを付ける(iOS)
AutoML Vision Edge を使用して独自のモデルをトレーニングしたら、 そのモデルをアプリで使用して画像にラベルを付けることができます。
AutoML Vision Edge からトレーニングされたモデルを統合するには、モデルのファイルを Xcode プロジェクトにコピーしてバンドルする方法と、Firebase から動的にダウンロードする方法があります。
| モデルのバンドル オプション | |
|---|---|
| アプリにバンドル済み |
|
| Firebase でホストする |
|
試してみる
- サンプルアプリで この API の使用例を確認してください。
始める前に
1. Podfile に ML Kit ライブラリを含めます。モデルをアプリにバンドルする場合:
pod 'GoogleMLKit/ImageLabelingAutoML'
LinkFirebase
依存関係を追加します:
pod 'GoogleMLKit/ImageLabelingAutoML'
pod 'GoogleMLKit/LinkFirebase'
.xcworkspacecode> を使用して Xcode プロジェクトを開きます。ML Kit は Xcode
バージョン 13.2.1 以降でサポートされています。
3. モデルをダウンロードする場合は、
Firebase を iOS プロジェクトに追加します(
まだ行っていない場合)。これは、
モデルをバンドルする場合には必要ありません。
1. モデルを読み込む
ローカル モデルソースを構成する
モデルをアプリにバンドルするには:1. Firebase コンソールからダウンロードした zip アーカイブからモデルとそのメタデータをフォルダに抽出します。
your_model_directory
|____dict.txt
|____manifest.json
|____model.tflite
2. フォルダを Xcode プロジェクトにコピーします。その際、 [Create folder references] を選択するように注意してください。モデルファイルとメタデータ は App Bundle に含まれ、ML Kit で利用できます。
3.
AutoMLImageLabelerLocalModel オブジェクトを作成し、モデル マニフェスト ファイルへのパスを指定します。Swift
guard let manifestPath = Bundle.main.path( forResource: "manifest", ofType: "json", inDirectory: "your_model_directory" ) else { return } let localModel = AutoMLImageLabelerLocalModel(manifestPath: manifestPath)
Objective-C
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. )
Objective-C
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 )
Objective-C
MLKModelDownloadConditions *downloadConditions = [[MLKModelDownloadConditions alloc] initWithAllowsCellularAccess:YES allowsBackgroundDownloading:YES]; NSProgress *downloadProgress = [[MLKModelManager modelManager] downloadModel:remoteModel conditions:downloadConditions];
多くのアプリは、初期化コードでモデルのダウンロード タスクを開始しますが、モデルを使用する前に開始することもできます。
モデルから画像ラベラーを作成する
モデルソースを構成したら、そのソースのいずれか 1 つから 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)
Objective-C
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)
Objective-C
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];
リモートでホストされるモデルのみがある場合は、モデルがダウンロード済みであることを確認するまで、モデルに関連する機能(UI の一部をグレー表示または非表示にするなど)を無効にする必要があります。
オブザーバをデフォルトの通知センターに接続して、モデルのダウンロード ステータスを取得できます。ダウンロードに時間がかかり、ダウンロードが終了するまでに元のオブジェクトが解放される可能性があります。このため、observer ブロックでは 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] // ... }
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. 入力画像を準備する
UIImage または
CMSampleBuffer を使用して VisionImage オブジェクトを作成します。
UIImage を使用する場合は、次の手順を行います。
VisionImageオブジェクトをUIImageで作成します。必ず正しい.orientationを指定してください。Swift
let image = VisionImage(image: UIImage) visionImage.orientation = image.imageOrientation
Objective-C
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 } }
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; } }
VisionImageオブジェクトと向きを使用して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. 画像ラベラーを実行する
非同期:
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 (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.
Objective-C
NSError *error; NSArray*labels = [imageLabeler resultsInImage:image error:&error]; // Show results or handle the error.
4. ラベル付きオブジェクトに関する情報を取得する
画像のラベル付けオペレーションが成功すると、ImageLabel の配列が返されます。各 ImageLabel は画像内でラベル付けされたものを表します。各ラベルのテキストの説明(TensorFlow Lite モデルファイルのメタデータで使用できる場合)、信頼スコア、インデックスを取得できます。
次に例を示します。
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; }
リアルタイムのパフォーマンスを改善するためのヒント
リアルタイムのアプリケーションで画像にラベルを付ける場合は、次の ガイドラインに従って適切なフレームレートを得てください。
- 動画フレームを処理するには、検出機能の
results(in:)同期 API を使用します。このメソッドをAVCaptureVideoDataOutputSampleBufferDelegateのcaptureOutput(_, didOutput:from:)関数から呼び出して、指定された動画 フレームから結果を同期的に取得します。検出器への呼び出しをスロットルするために、AVCaptureVideoDataOutputのalwaysDiscardsLateVideoFramesをtrueにしておきます。検出器の実行中に新しい 動画フレームが使用可能になった場合は、そのフレームはドロップされます。 - 検出器の出力を使用して入力画像の上にグラフィックスをオーバーレイする場合は、まず ML Kit から検出結果を取得し、画像とオーバーレイを 1 つのステップでレンダリングします。これにより、ディスプレイ サーフェスへのレンダリングは、処理された入力フレームごとに 1 回で済みます。例については、ML Kit クイックスタート サンプルの updatePreviewOverlayViewWithLastFrame をご覧ください。