ML Kit を使用して画像にラベルを付ける(Android)

ML Kit を使用すると、画像内で認識されたオブジェクトにラベルを付けることができます。デフォルト モデルは、 ML Kit は 400 種類以上のラベルをサポートしています。

<ph type="x-smartling-placeholder">
機能バンドルされていませんバンドル
実装モデルは Google Play 開発者サービスを介して動的にダウンロードされます。モデルは、ビルド時に静的にリンクされます。
アプリのサイズ約 200 KB のサイズ増加。サイズが約 5.7 MB 増加します。
初期化時間初めて使用するには、モデルがダウンロードされるのを待たなければならない場合があります。モデルはすぐに使用できます

試してみる

始める前に

<ph type="x-smartling-placeholder">
  1. プロジェクト レベルの build.gradle ファイルに、Google の buildscript セクションと allprojects セクションの両方に Maven リポジトリ

  2. ML Kit Android ライブラリの依存関係をモジュールの アプリレベルの Gradle ファイル(通常は app/build.gradle)。次のいずれかを選択 必要に応じて次の依存関係を追加します。

    モデルをアプリにバンドルする場合:

    dependencies {
      // ...
      // Use this dependency to bundle the model with your app
      implementation 'com.google.mlkit:image-labeling:17.0.8'
    }
    

    Google Play 開発者サービスでモデルを使用する場合:

    dependencies {
      // ...
      // Use this dependency to use the dynamically downloaded model in Google Play Services
      implementation 'com.google.android.gms:play-services-mlkit-image-labeling:16.0.8'
    }
    
  3. Google Play 開発者サービスでモデルを使用することを選択した場合、 アプリがダウンロードされると、モデルが自動的にデバイスにダウンロードされるようになります。 ダウンロードする必要があります。そのためには、次の宣言を アプリの AndroidManifest.xml ファイルを次のように変更します。

    <application ...>
          ...
          <meta-data
              android:name="com.google.mlkit.vision.DEPENDENCIES"
              android:value="ica" >
          <!-- To use multiple models: android:value="ica,model2,model3" -->
    </application>
    

    モデルの提供状況を明示的に確認し、 Google Play 開発者サービスの ModuleInstallClient API

    インストール時のモデルのダウンロードを有効にしない場合、または明示的なダウンロードをリクエストしない場合、 モデルは初回のラベラー実行時にダウンロードされます。お客様が行うリクエスト 結果が返されないことに注意してください。

これで、画像にラベルを付ける準備が整いました。

1. 入力画像を準備する

画像から InputImage オブジェクトを作成します。 Bitmap を使用するか、 camera2 API、YUV_420_888 media.Image: 考えています

InputImage を作成できます。 異なるソースからのオブジェクトについて、以下で説明します。

media.Image の使用

InputImage を作成するには: media.Image オブジェクトからオブジェクトをキャプチャします。たとえば、 渡すには、media.Image オブジェクトと画像の InputImage.fromMediaImage() に変更します。

「 <ph type="x-smartling-placeholder"></ph> CameraX ライブラリ、OnImageCapturedListenerImageAnalysis.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 を 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 の使用

InputImage を作成するには: 作成するには、まず画像を計算してByteBufferByteArray 前述の 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 の使用

InputImage を作成するには: Bitmap オブジェクトから呼び出す場合は、次のように宣言します。

Kotlin

val image = InputImage.fromBitmap(bitmap, 0)

Java

InputImage image = InputImage.fromBitmap(bitmap, rotationDegree);

画像は、Bitmap オブジェクトと回転角度で表されます。

2. 画像ラベラーを構成して実行する

画像内のオブジェクトにラベルを付けるには、InputImage オブジェクトを ImageLabelerprocess メソッド。

  1. まず、インスタンスの ImageLabeler

    デバイス上の画像ラベラーを使用する場合は、次の操作を行います。 宣言:

Kotlin

// To use default options:
val labeler = ImageLabeling.getClient(ImageLabelerOptions.DEFAULT_OPTIONS)

// Or, to set the minimum confidence required:
// val options = ImageLabelerOptions.Builder()
//     .setConfidenceThreshold(0.7f)
//     .build()
// val labeler = ImageLabeling.getClient(options)

Java

// To use default options:
ImageLabeler labeler = ImageLabeling.getClient(ImageLabelerOptions.DEFAULT_OPTIONS);

// Or, to set the minimum confidence required:
// ImageLabelerOptions options =
//     new ImageLabelerOptions.Builder()
//         .setConfidenceThreshold(0.7f)
//         .build();
// ImageLabeler labeler = ImageLabeling.getClient(options);
  1. 次に、画像を process() メソッドに渡します。

Kotlin

labeler.process(image)
        .addOnSuccessListener { labels ->
            // Task completed successfully
            // ...
        }
        .addOnFailureListener { e ->
            // Task failed with an exception
            // ...
        }

Java

labeler.process(image)
        .addOnSuccessListener(new OnSuccessListener<List<ImageLabel>>() {
            @Override
            public void onSuccess(List<ImageLabel> labels) {
                // Task completed successfully
                // ...
            }
        })
        .addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                // Task failed with an exception
                // ...
            }
        });
<ph type="x-smartling-placeholder">

3. ラベル付きオブジェクトに関する情報を取得する

画像のラベル付けオペレーションが成功すると、 ImageLabel オブジェクトが成功リスナーに渡されます。各 ImageLabel オブジェクトは、画像内でラベル付けされたものを表します。ベース モデルは 400 以上のラベルをサポートしています。 各ラベルのテキストの説明を取得したり、 一致の信頼スコアが含まれます。例:

Kotlin

for (label in labels) {
    val text = label.text
    val confidence = label.confidence
    val index = label.index
}

Java

for (ImageLabel label : labels) {
    String text = label.getText();
    float confidence = label.getConfidence();
    int index = label.getIndex();
}

リアルタイムのパフォーマンスを改善するためのヒント

リアルタイム アプリケーションで画像にラベルを付ける場合は、 実現するためのガイドラインは次のとおりです。

  • Camera または camera2 API、 スロットル呼び出しを行います。新しい動画が 画像ラベラーの実行中に利用可能になったら、そのフレームをドロップします。詳しくは、 <ph type="x-smartling-placeholder"></ph> VisionProcessorBase クラスをご覧ください。
  • CameraX API を使用する場合は、 バックプレッシャー戦略がデフォルト値に ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST。 これにより、分析のために一度に 1 つの画像のみが配信されるようになります。もしより多くの画像が 生成された場合、自動的に破棄され、 提供します。次の呼び出しによって分析中の画像を閉じたら、 ImageProxy.close() が呼び出されると、次に最新の画像が配信されます。
  • 画像ラベラーの出力を使用してグラフィックを まず ML Kit から結果を取得してから、画像をレンダリングする 1 ステップでオーバーレイできますこれにより、ディスプレイ サーフェスにレンダリングされます。 入力フレームごとに 1 回だけです。詳しくは、 <ph type="x-smartling-placeholder"></ph> CameraSourcePreview および GraphicOverlay クラスをご覧ください。
  • Camera2 API を使用する場合は、 ImageFormat.YUV_420_888 形式。古い Camera API を使用する場合は、 ImageFormat.NV21 形式。