ML Kit に渡すと、画像内の最大 5 つのオブジェクトと画像内の各オブジェクトの位置が検出されます。動画ストリーム内のオブジェクトを検出する場合、各オブジェクトには一意の ID があります。この ID を使用して、フレーム間でオブジェクトをトラックできます。
カスタム画像分類モデルを使用して、検出されたオブジェクトを分類できます。モデルの互換性要件、事前トレーニング済みモデルの場所、独自のモデルをトレーニングする方法については、ML Kit のカスタムモデルをご覧ください。
カスタムモデルを統合するには、次の 2 つの方法があります。モデルをアプリのアセット フォルダに入れてモデルをバンドルすることも、Firebase から動的にダウンロードすることもできます。次の表は、2 つのオプションを比較したものです。
バンドルモデル | ホストされているモデル |
---|---|
モデルがアプリの APK の一部であるため、サイズが大きくなります。 | モデルは APK に含まれていません。Firebase Machine Learning にアップロードすることでホストされます。 |
このモデルは、Android デバイスがオフラインのときでもすぐに利用できます。 | モデルがオンデマンドでダウンロードされる |
Firebase プロジェクトは不要 | Firebase プロジェクトが必要 |
モデルを更新するにはアプリを再公開する必要があります | アプリを再公開することなくモデルの更新を push できる |
組み込みの A/B テストなし | Firebase Remote Config による簡単な A/B テスト |
試してみる
- バンドルされたモデルの使用例については、Vision クイックスタート アプリをご覧ください。ホストされるモデルの使用例については、automl クイックスタート アプリをご覧ください。
- この API のエンドツーエンドの実装については、マテリアル デザインのショーケース アプリをご覧ください。
始める前に
プロジェクト レベルの
build.gradle
ファイルのbuildscript
セクションとallprojects
セクションの両方に Google の Maven リポジトリを組み込みます。ML Kit Android ライブラリの依存関係をモジュールのアプリレベルの Gradle ファイル(通常は
app/build.gradle
)に追加します。モデルをアプリにバンドルする場合:
dependencies { // ... // Object detection & tracking feature with custom bundled model implementation 'com.google.mlkit:object-detection-custom:17.0.0' }
Firebase からモデルを動的にダウンロードするには、
linkFirebase
の依存関係を追加します。dependencies { // ... // Object detection & tracking feature with model downloaded // from firebase implementation 'com.google.mlkit:object-detection-custom:17.0.0' implementation 'com.google.mlkit:linkfirebase:17.0.0' }
モデルをダウンロードするには、Firebase を Android プロジェクトに追加します(まだ行っていない場合)。これは、モデルをバンドルする際には必要ありません。
1. モデルを読み込む
ローカルモデル ソースの構成
モデルをアプリにバンドルするには:
モデルファイル(拡張子は通常
.tflite
または.lite
)をアプリのassets/
フォルダにコピーします。(場合によっては、最初にapp/
フォルダを右クリックし、次に [新規] > [フォルダ] > [Assets フォルダ] をクリックします)。次に、アプリのビルド時に Gradle がモデルファイルを圧縮しないように、アプリの
build.gradle
ファイルに以下を追加します。android { // ... aaptOptions { noCompress "tflite" // or noCompress "lite" } }
モデルファイルはアプリ パッケージに含められ、ML Kit から生のアセットとして使用できます。
モデルファイルのパスを指定して、
LocalModel
オブジェクトを作成します。Kotlin
val localModel = LocalModel.Builder() .setAssetFilePath("model.tflite") // or .setAbsoluteFilePath(absolute file path to model file) // or .setUri(URI to model file) .build()
Java
LocalModel localModel = new LocalModel.Builder() .setAssetFilePath("model.tflite") // or .setAbsoluteFilePath(absolute file path to model file) // or .setUri(URI to model file) .build();
Firebase がホストするモデルソースを構成する
リモートでホストされるモデルを使用するには、FirebaseModelSource
までに CustomRemoteModel
オブジェクトを作成します。その際に、モデルを公開したときに割り当てた名前を指定します。
Kotlin
// Specify the name you assigned in the Firebase console. val remoteModel = CustomRemoteModel .Builder(FirebaseModelSource.Builder("your_model_name").build()) .build()
Java
// Specify the name you assigned in the Firebase console. CustomRemoteModel remoteModel = new CustomRemoteModel .Builder(new FirebaseModelSource.Builder("your_model_name").build()) .build();
次に、ダウンロードを許可する条件を指定してモデルのダウンロード タスクを開始します。モデルがデバイスにない場合、または新しいバージョンのモデルが使用可能な場合、このタスクは Firebase から非同期でモデルをダウンロードします。
Kotlin
val downloadConditions = DownloadConditions.Builder() .requireWifi() .build() RemoteModelManager.getInstance().download(remoteModel, downloadConditions) .addOnSuccessListener { // Success. }
Java
DownloadConditions downloadConditions = new DownloadConditions.Builder() .requireWifi() .build(); RemoteModelManager.getInstance().download(remoteModel, downloadConditions) .addOnSuccessListener(new OnSuccessListener() { @Override public void onSuccess(@NonNull Task task) { // Success. } });
多くのアプリは、初期化コードでモデルのダウンロード タスクを開始しますが、モデルを使用する前に開始することもできます。
2. オブジェクト検出を構成する
モデルソースを構成したら、CustomObjectDetectorOptions
オブジェクトを使用して、ユースケースにオブジェクト検出を構成します。次の設定を変更できます。
オブジェクト検出の設定 | |
---|---|
検出モード |
STREAM_MODE (デフォルト)| SINGLE_IMAGE_MODE
|
複数のオブジェクトを検出してトラックする |
false (デフォルト)| true
最大 5 つのオブジェクトを検出してトラックするか、最も目立つオブジェクトのみをトラックするか(デフォルト)。 |
オブジェクトを分類する |
false (デフォルト)| true
提供されたカスタム分類モデルを使用して、検出されたオブジェクトを分類するかどうかを指定します。カスタム分類モデルを使用するには、これを |
分類の信頼度のしきい値 |
検出されたラベルの最小信頼スコア。設定しなかった場合、モデルのメタデータで指定された分類器のしきい値が使用されます。モデルにメタデータが含まれていない場合、またはメタデータが分類器のしきい値を指定していない場合は、デフォルトのしきい値である 0.0 が使用されます。 |
オブジェクトあたりの最大ラベル数 |
検出項目が返すオブジェクトあたりのラベルの最大数。設定しない場合は、デフォルト値の 10 が使用されます。 |
オブジェクトの検出とトラッキングの API は、主に次の 2 つのユースケース用に最適化されています。
- カメラのファインダー内で最も目立つオブジェクトをライブで検出してトラッキングします。
- 静止画像からの複数のオブジェクトの検出。
ローカル バンドル モデルでこれらのユースケースに API を構成するには:
Kotlin
// Live detection and tracking val customObjectDetectorOptions = CustomObjectDetectorOptions.Builder(localModel) .setDetectorMode(CustomObjectDetectorOptions.STREAM_MODE) .enableClassification() .setClassificationConfidenceThreshold(0.5f) .setMaxPerObjectLabelCount(3) .build() // Multiple object detection in static images val customObjectDetectorOptions = CustomObjectDetectorOptions.Builder(localModel) .setDetectorMode(CustomObjectDetectorOptions.SINGLE_IMAGE_MODE) .enableMultipleObjects() .enableClassification() .setClassificationConfidenceThreshold(0.5f) .setMaxPerObjectLabelCount(3) .build() val objectDetector = ObjectDetection.getClient(customObjectDetectorOptions)
Java
// Live detection and tracking CustomObjectDetectorOptions customObjectDetectorOptions = new CustomObjectDetectorOptions.Builder(localModel) .setDetectorMode(CustomObjectDetectorOptions.STREAM_MODE) .enableClassification() .setClassificationConfidenceThreshold(0.5f) .setMaxPerObjectLabelCount(3) .build(); // Multiple object detection in static images CustomObjectDetectorOptions customObjectDetectorOptions = new CustomObjectDetectorOptions.Builder(localModel) .setDetectorMode(CustomObjectDetectorOptions.SINGLE_IMAGE_MODE) .enableMultipleObjects() .enableClassification() .setClassificationConfidenceThreshold(0.5f) .setMaxPerObjectLabelCount(3) .build(); ObjectDetector objectDetector = ObjectDetection.getClient(customObjectDetectorOptions);
リモートでホストされるモデルがある場合は、実行する前にモデルがダウンロードされていることを確認する必要があります。モデルのダウンロード タスクのステータスは、モデル マネージャーの isModelDownloaded()
メソッドを使用して確認できます。
これを確認するのは検出機能を実行する前だけですが、リモートでホストされるモデルとローカル バンドル モデルの両方がある場合は、画像検出機能をインスタンス化するときにこのチェックを実行することをおすすめします。これは、ダウンロードした場合はリモートモデルから検出機能を作成し、それ以外の場合はローカルモデルから検出機能を作成することを意味します。
Kotlin
RemoteModelManager.getInstance().isModelDownloaded(remoteModel) .addOnSuccessListener { isDownloaded -> val optionsBuilder = if (isDownloaded) { CustomObjectDetectorOptions.Builder(remoteModel) } else { CustomObjectDetectorOptions.Builder(localModel) } val customObjectDetectorOptions = optionsBuilder .setDetectorMode(CustomObjectDetectorOptions.SINGLE_IMAGE_MODE) .enableClassification() .setClassificationConfidenceThreshold(0.5f) .setMaxPerObjectLabelCount(3) .build() val objectDetector = ObjectDetection.getClient(customObjectDetectorOptions) }
Java
RemoteModelManager.getInstance().isModelDownloaded(remoteModel) .addOnSuccessListener(new OnSuccessListener() { @Override public void onSuccess(Boolean isDownloaded) { CustomObjectDetectorOptions.Builder optionsBuilder; if (isDownloaded) { optionsBuilder = new CustomObjectDetectorOptions.Builder(remoteModel); } else { optionsBuilder = new CustomObjectDetectorOptions.Builder(localModel); } CustomObjectDetectorOptions customObjectDetectorOptions = optionsBuilder .setDetectorMode(CustomObjectDetectorOptions.SINGLE_IMAGE_MODE) .enableClassification() .setClassificationConfidenceThreshold(0.5f) .setMaxPerObjectLabelCount(3) .build(); ObjectDetector objectDetector = ObjectDetection.getClient(customObjectDetectorOptions); } });
リモートでホストされるモデルのみがある場合は、モデルがダウンロード済みであることを確認するまで、モデルに関連する機能を無効にする必要があります(UI の一部をグレー表示または非表示にするなど)。確認はモデル マネージャーの download()
メソッドにリスナーを接続して行います。
Kotlin
RemoteModelManager.getInstance().download(remoteModel, conditions) .addOnSuccessListener { // Download complete. Depending on your app, you could enable the ML // feature, or switch from the local model to the remote model, etc. }
Java
RemoteModelManager.getInstance().download(remoteModel, conditions) .addOnSuccessListener(new OnSuccessListener() { @Override public void onSuccess(Void v) { // Download complete. Depending on your app, you could enable // the ML feature, or switch from the local model to the remote // model, etc. } });
3.入力画像を準備する
画像からInputImage
オブジェクトを作成します。
オブジェクト検出は、Bitmap
、NV21 ByteBuffer
、または YUV_420_888 media.Image
から直接実行されます。これらのソースのいずれかに直接アクセスできる場合は、これらのソースから InputImage
を作成することをおすすめします。他のソースから InputImage
を作成した場合、変換は内部で処理されるため、効率が低下する可能性があります。
さまざまなソースから InputImage
オブジェクトを作成できます。以下では、この各オブジェクトについて説明します。
media.Image
の使用
media.Image
オブジェクトから InputImage
オブジェクト(デバイスのカメラから画像をキャプチャする場合など)を作成するには、media.Image
オブジェクトと画像の回転を InputImage.fromMediaImage()
に渡します。
CameraX ライブラリを使用する場合は、OnImageCapturedListener
クラスと ImageAnalysis.Analyzer
クラスによって回転値が計算されます。
Kotlin
private class YourImageAnalyzer : ImageAnalysis.Analyzer { override fun analyze(imageProxy: ImageProxy) { val mediaImage = imageProxy.image if (mediaImage != null) { val image = InputImage.fromMediaImage(mediaImage, imageProxy.imageInfo.rotationDegrees) // Pass image to an ML Kit Vision API // ... } } }
Java
private class YourAnalyzer implements ImageAnalysis.Analyzer { @Override public void analyze(ImageProxy imageProxy) { Image mediaImage = imageProxy.getImage(); if (mediaImage != null) { InputImage image = InputImage.fromMediaImage(mediaImage, imageProxy.getImageInfo().getRotationDegrees()); // Pass image to an ML Kit Vision API // ... } } }
画像の回転角度を取得するカメラ ライブラリを使用しない場合は、デバイスの回転角度とデバイス内のカメラセンサーの向きから計算できます。
Kotlin
private val ORIENTATIONS = SparseIntArray() init { ORIENTATIONS.append(Surface.ROTATION_0, 0) ORIENTATIONS.append(Surface.ROTATION_90, 90) ORIENTATIONS.append(Surface.ROTATION_180, 180) ORIENTATIONS.append(Surface.ROTATION_270, 270) } /** * Get the angle by which an image must be rotated given the device's current * orientation. */ @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Throws(CameraAccessException::class) private fun getRotationCompensation(cameraId: String, activity: Activity, isFrontFacing: Boolean): Int { // Get the device's current rotation relative to its "native" orientation. // Then, from the ORIENTATIONS table, look up the angle the image must be // rotated to compensate for the device's rotation. val deviceRotation = activity.windowManager.defaultDisplay.rotation var rotationCompensation = ORIENTATIONS.get(deviceRotation) // Get the device's sensor orientation. val cameraManager = activity.getSystemService(CAMERA_SERVICE) as CameraManager val sensorOrientation = cameraManager .getCameraCharacteristics(cameraId) .get(CameraCharacteristics.SENSOR_ORIENTATION)!! if (isFrontFacing) { rotationCompensation = (sensorOrientation + rotationCompensation) % 360 } else { // back-facing rotationCompensation = (sensorOrientation - rotationCompensation + 360) % 360 } return rotationCompensation }
Java
private static final SparseIntArray ORIENTATIONS = new SparseIntArray(); static { ORIENTATIONS.append(Surface.ROTATION_0, 0); ORIENTATIONS.append(Surface.ROTATION_90, 90); ORIENTATIONS.append(Surface.ROTATION_180, 180); ORIENTATIONS.append(Surface.ROTATION_270, 270); } /** * Get the angle by which an image must be rotated given the device's current * orientation. */ @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) private int getRotationCompensation(String cameraId, Activity activity, boolean isFrontFacing) throws CameraAccessException { // Get the device's current rotation relative to its "native" orientation. // Then, from the ORIENTATIONS table, look up the angle the image must be // rotated to compensate for the device's rotation. int deviceRotation = activity.getWindowManager().getDefaultDisplay().getRotation(); int rotationCompensation = ORIENTATIONS.get(deviceRotation); // Get the device's sensor orientation. CameraManager cameraManager = (CameraManager) activity.getSystemService(CAMERA_SERVICE); int sensorOrientation = cameraManager .getCameraCharacteristics(cameraId) .get(CameraCharacteristics.SENSOR_ORIENTATION); if (isFrontFacing) { rotationCompensation = (sensorOrientation + rotationCompensation) % 360; } else { // back-facing rotationCompensation = (sensorOrientation - rotationCompensation + 360) % 360; } return rotationCompensation; }
次に、media.Image
オブジェクトと回転角度値を InputImage.fromMediaImage()
に渡します。
Kotlin
val image = InputImage.fromMediaImage(mediaImage, rotation)
Java
InputImage image = InputImage.fromMediaImage(mediaImage, rotation);
ファイル URI の使用
InputImage
オブジェクトをファイルの URI から作成するには、アプリのコンテキストとファイルの URI を InputImage.fromFilePath()
に渡します。これは、ACTION_GET_CONTENT
インテントを使用して、ギャラリー アプリから画像を選択するようにユーザーに促すときに便利です。
Kotlin
val image: InputImage try { image = InputImage.fromFilePath(context, uri) } catch (e: IOException) { e.printStackTrace() }
Java
InputImage image; try { image = InputImage.fromFilePath(context, uri); } catch (IOException e) { e.printStackTrace(); }
ByteBuffer
または ByteArray
の使用
ByteBuffer
または ByteArray
から InputImage
オブジェクトを作成するには、まず、media.Image
の入力について前述したように、画像の回転角度を計算します。次に、画像の高さ、幅、カラー エンコード形式、回転角度とともに、バッファまたは配列を含む InputImage
オブジェクトを作成します。
Kotlin
val image = InputImage.fromByteBuffer( byteBuffer, /* image width */ 480, /* image height */ 360, rotationDegrees, InputImage.IMAGE_FORMAT_NV21 // or IMAGE_FORMAT_YV12 ) // Or: val image = InputImage.fromByteArray( byteArray, /* image width */ 480, /* image height */ 360, rotationDegrees, InputImage.IMAGE_FORMAT_NV21 // or IMAGE_FORMAT_YV12 )
Java
InputImage image = InputImage.fromByteBuffer(byteBuffer, /* image width */ 480, /* image height */ 360, rotationDegrees, InputImage.IMAGE_FORMAT_NV21 // or IMAGE_FORMAT_YV12 ); // Or: InputImage image = InputImage.fromByteArray( byteArray, /* image width */480, /* image height */360, rotation, InputImage.IMAGE_FORMAT_NV21 // or IMAGE_FORMAT_YV12 );
Bitmap
の使用
Bitmap
オブジェクトから InputImage
オブジェクトを作成するには、次の宣言を行います。
Kotlin
val image = InputImage.fromBitmap(bitmap, 0)
Java
InputImage image = InputImage.fromBitmap(bitmap, rotationDegree);
画像は Bitmap
オブジェクトと回転角度で表されます。
4. オブジェクト検出を実行する
Kotlin
objectDetector .process(image) .addOnFailureListener(e -> {...}) .addOnSuccessListener(results -> { for (detectedObject in results) { // ... } });
Java
objectDetector .process(image) .addOnFailureListener(e -> {...}) .addOnSuccessListener(results -> { for (DetectedObject detectedObject : results) { // ... } });
5. ラベル付きオブジェクトに関する情報を取得する
process()
の呼び出しが成功すると、DetectedObject
のリストが成功リスナーに渡されます。
各 DetectedObject
には次のプロパティが含まれています。
境界ボックス | 画像内のオブジェクトの位置を示す Rect 。 |
||||||
トラッキング ID | 画像間でオブジェクトを識別する整数。SINGLE_IMAGE_MODE では、null です。 | ||||||
ラベル |
|
Kotlin
// The list of detected objects contains one item if multiple // object detection wasn't enabled. for (detectedObject in results) { val boundingBox = detectedObject.boundingBox val trackingId = detectedObject.trackingId for (label in detectedObject.labels) { val text = label.text val index = label.index val confidence = label.confidence } }
Java
// The list of detected objects contains one item if multiple // object detection wasn't enabled. for (DetectedObject detectedObject : results) { Rect boundingBox = detectedObject.getBoundingBox(); Integer trackingId = detectedObject.getTrackingId(); for (Label label : detectedObject.getLabels()) { String text = label.getText(); int index = label.getIndex(); float confidence = label.getConfidence(); } }
優れたユーザー エクスペリエンスの確保
最高のユーザー エクスペリエンスを提供するため、次のガイドラインに従ってアプリを作成してください。
- オブジェクトの検出に成功するかどうかは、オブジェクトの視覚的な複雑さによります。画像特徴が少ないオブジェクトは、検出されるために画像の大部分を占めることが必要になります。検出するオブジェクトの種類に適した入力をキャプチャするためのガイダンスをユーザーに提供する必要があります。
- 分類を使用するときに、サポート対象のカテゴリに該当しないオブジェクトを検出する場合は、未知のオブジェクトに対して特別な処理を実装します。
また、ML Kit マテリアル デザイン ショーケース アプリと、マテリアル デザインの機械学習を利用した機能のためのパターンのコレクションもご確認ください。
パフォーマンスの向上
リアルタイムのアプリケーションでオブジェクト検出を使用する場合は、適切なフレームレートを得るために次のガイドラインに従ってください。リアルタイム アプリケーションでストリーミング モードを使用する場合は、ほとんどのデバイスで十分なフレームレートを生成できないため、複数のオブジェクト検出を使用しないでください。
Camera
またはcamera2
API を使用する場合、検出器の呼び出しのスロットリングを行います。検出器の実行中に新しい動画フレームが使用可能になった場合は、そのフレームをドロップします。例については、クイックスタート サンプルアプリのVisionProcessorBase
クラスをご覧ください。CameraX
API を使用する場合は、バックプレッシャー戦略がデフォルト値ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST
に設定されていることを確認します。 一度に 1 つのイメージのみが分析のために配信されることが保証されます。アナライザがビジー状態のときにさらに生成されるイメージは、自動的に破棄され、配信のキューに入りません。分析されている画像を ImageProxy.close() で閉じると、次に新しいイメージが配信されます。- 検出器の出力を使用して入力画像の上にグラフィックスをオーバーレイする場合は、まず ML Kit から検出結果を取得し、画像とオーバーレイを 1 つのステップでレンダリングします。これにより、ディスプレイ サーフェスへのレンダリングは入力フレームごとに 1 回で済みます。例については、クイックスタート サンプルアプリの
CameraSourcePreview
クラスとGraphicOverlay
クラスをご覧ください。 - Camera2 API を使用する場合は、
ImageFormat.YUV_420_888
形式で画像をキャプチャします。古い Camera API を使用する場合は、ImageFormat.NV21
形式で画像をキャプチャします。