ML Kit を使用すると、画像内のエンティティを認識してラベル付けできます。この API は、さまざまなカスタム画像分類モデルをサポートしています。モデルの互換性要件、事前トレーニング済みモデルの場所、独自のモデルのトレーニング方法については、ML Kit によるカスタムモデルをご覧ください。
カスタムモデルを統合するには、2 つの方法があります。モデルは、アプリのアセット フォルダ内に配置してバンドルすることも、Firebase から動的にダウンロードすることもできます。次の表は、2 つのオプションを比較したものです。
バンドルモデル | ホストされているモデル |
---|---|
このモデルはアプリの APK の一部であるため、サイズが大きくなります。 | モデルは APK の一部ではありません。これは、Firebase Machine Learning にアップロードすることでホストされます。 |
Android デバイスがオフラインの場合でも、モデルをすぐに利用できます | モデルがオンデマンドでダウンロードされる |
Firebase プロジェクトは不要 | Firebase プロジェクトが必要 |
モデルを更新するにはアプリを再公開する必要があります | アプリを再公開することなくモデルの更新を push できる |
組み込みの A/B テストなし | Firebase Remote Config による簡単な A/B テスト |
試してみる
- バンドルされたモデルの使用例については、Vision クイックスタート アプリをご覧ください。ホストされているモデルの使用例については、automl クイックスタート アプリをご覧ください。
始める前に
Podfile に ML Kit ライブラリを含めます。
モデルをアプリにバンドルする場合:
pod 'GoogleMLKit/ImageLabelingCustom', '3.2.0'
Firebase からモデルを動的にダウンロードするには、
LinkFirebase
依存関係を追加します。pod 'GoogleMLKit/ImageLabelingCustom', '3.2.0' pod 'GoogleMLKit/LinkFirebase', '3.2.0'
プロジェクトの Pod をインストールまたは更新したら、
.xcworkspace
を使用して Xcode プロジェクトを開きます。ML Kit は Xcode バージョン 13.2.1 以降でサポートされています。モデルをダウンロードする場合は、Firebase を iOS プロジェクトに追加します(まだ行っていない場合)。これは、モデルをバンドルする場合には必要ありません。
1. モデルを読み込む
ローカル モデルソースを構成する
モデルをアプリにバンドルするには:
モデルファイル(拡張子は通常
.tflite
または.lite
)を Xcode プロジェクトにコピーします。その際、Copy bundle resources
を選択してください。モデルファイルは App Bundle に含まれ、ML Kit から使用できます。モデルファイルへのパスを指定して
LocalModel
オブジェクトを作成します。Swift
let localModel = LocalModel(path: localModelFilePath)
Objective-C
MLKLocalModel *localModel = [[MLKLocalModel alloc] initWithPath:localModelFilePath];
Firebase によってホストされるモデルソースを構成する
リモートでホストされるモデルを使用するには、RemoteModel
オブジェクトを作成します。その際に、モデルを公開したときに割り当てた名前を指定します。
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];
次に、ダウンロードを許可する条件を指定してモデルのダウンロード タスクを開始します。モデルがデバイスにない場合、または新しいバージョンのモデルが使用可能な場合、このタスクは 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
オブジェクトを作成します。
以下のオプションを使用できます。
オプション | |
---|---|
confidenceThreshold
|
検出されたラベルの最小信頼スコア。設定されていない場合は、モデルのメタデータで指定された分類子のしきい値が使用されます。 モデルにメタデータが含まれていない場合、またはメタデータで分類器のしきい値が指定されていない場合は、デフォルトのしきい値 0.0 が使用されます。 |
maxResultCount
|
返されるラベルの最大数。設定しない場合は、デフォルト値の 10 が使用されます。 |
ローカル バンドルモデルのみがある場合は、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];
リモートでホストされるモデルがある場合は、実行する前にモデルがダウンロードされていることを確認する必要があります。モデルのダウンロード タスクのステータスは、モデル マネージャーの isModelDownloaded(remoteModel:)
メソッドを使用して確認できます。
ラベラーを実行する前に確認するだけで済みますが、リモートでホストされるモデルとローカル バンドル モデルの両方がある場合は、ImageLabeler
をインスタンス化する際にこのチェックを行うことが適切な場合があります。ラベラーがダウンロードされている場合はリモートモデルから、ラベラーがダウンロードされていない場合はローカルモデルから作成します。
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];
リモートでホストされるモデルのみがある場合は、モデルがダウンロード済みであることを確認するまで、モデルに関連する機能を無効にする必要があります(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
を使用する場合は、次の操作を行います。
UIImage
を使用してVisionImage
オブジェクトを作成します。正しい.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; } }
CMSampleBuffer
オブジェクトと画面の向きを使用して、VisionImage
オブジェクトを作成します。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. 画像ラベラーを実行する
画像内のオブジェクトにラベルを付けるには、image
オブジェクトを ImageLabeler
の process()
メソッドに渡します。
非同期:
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. }];
同期:
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 をご覧ください。