在 Android 中使用 AutoML 訓練模型為圖片加上標籤

使用 AutoML Vision Edge 訓練自己的模型之後,即可在應用程式中使用該模型為圖片加上標籤。有兩種方法可整合透過 AutoML Vision Edge 訓練的模型:您可以將模型放入應用程式的資產資料夾中,藉此封裝模型,或者從 Firebase 動態下載。
模型組合選項
應用程式套件
  • 模型是應用程式 APK 的一部分
  • 即使 Android 裝置離線,也能立即使用模型
  • 不需要 Firebase 專案
透過 Firebase 代管
  • 將模型上傳至 Firebase Machine Learning 來託管模型
  • 縮減 APK 大小
  • 模型按需求下載
  • 不必重新發布應用程式即可推送模型更新
  • 使用 Firebase 遠端設定輕鬆進行 A/B 測試
  • 需要 Firebase 專案

立即體驗

事前準備

1. 在專案層級的 build.gradle 檔案中,請務必在 buildscriptallprojects 區段中加入 Google 的 Maven 存放區。

2. 將 ML Kit Android 程式庫的依附元件新增至模組的應用程式層級 Gradle 檔案 (通常是 app/build.gradle): 如要將模型與應用程式組合在一起:
    dependencies {
      // ...
      // Image labeling feature with bundled automl model
      implementation 'com.google.mlkit:image-labeling-automl:16.2.1'
    }
    
如要從 Firebase 動態下載模型,請新增 linkFirebase 依附元件:
    dependencies {
      // ...
      // Image labeling feature with automl model downloaded
      // from firebase
      implementation 'com.google.mlkit:image-labeling-automl:16.2.1'
      implementation 'com.google.mlkit:linkfirebase:16.0.1'
    }
    
3. 如要下載模型,請務必將 Firebase 新增至 Android 專案 (如果尚未新增)。加入模型組合時不需要。

1. 載入模型

設定本機模型來源

如要將模型與應用程式整合,請按照下列步驟操作:

1. 從您從 Firebase 控制台下載的 ZIP 封存檔中擷取模型及其中繼資料。建議您在未經修改的情況下直接使用下載檔案 (包括檔案名稱)。

2. 在應用程式套件中加入模型及其中繼資料檔案:

a. 如果專案中沒有素材資源資料夾,請在 app/ 資料夾上按一下滑鼠右鍵,然後依序點選「New」>「Folder」>「Assets Folder」,即可建立資料夾。

b. 在素材資源資料夾下建立子資料夾,以便存放模型檔案。

c. 將 model.tflitedict.txtmanifest.json 檔案複製到子資料夾 (這三個檔案均須位於同一個資料夾)。

3. 請將以下內容新增至應用程式的 build.gradle 檔案,確保 Gradle 在建構應用程式時不會壓縮模型檔案:
    android {
        // ...
        aaptOptions {
            noCompress "tflite"
        }
    }
    
模型檔案會納入應用程式套件中,並以原始素材資源的形式提供給 ML Kit。

注意:自 Android Gradle 外掛程式 4.1 版起,.tflite 預設會加入 noCompress 清單,且不再需要。

4. 建立 LocalModel 物件,指定模型資訊清單檔案的路徑:

Kotlin

val localModel = AutoMLImageLabelerLocalModel.Builder()
        .setAssetFilePath("manifest.json")
        // or .setAbsoluteFilePath(absolute file path to manifest file)
        .build()

Java

AutoMLImageLabelerLocalModel localModel =
    new AutoMLImageLabelerLocalModel.Builder()
        .setAssetFilePath("manifest.json")
        // or .setAbsoluteFilePath(absolute file path to manifest file)
        .build();

設定 Firebase 託管的模型來源

如要使用遠端託管模型,請建立 RemoteModel 物件,指定您發布模型時為其指派的名稱:

Kotlin

// Specify the name you assigned in the Firebase console.
val remoteModel =
    AutoMLImageLabelerRemoteModel.Builder("your_model_name").build()

Java

// Specify the name you assigned in the Firebase console.
AutoMLImageLabelerRemoteModel remoteModel =
    new AutoMLImageLabelerRemoteModel.Builder("your_model_name").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.
            }
        });

許多應用程式會在初始化程式碼中啟動下載工作,但您也可以在需要使用模型之前隨時執行下載作業。

使用模型建立圖片標籤器

設定模型來源後,請從其中一個來源建立 ImageLabeler 物件。

如果您只有本機組合模型,請直接透過 AutoMLImageLabelerLocalModel 物件建立標籤工具,並設定所需的可信度分數門檻 (請參閱「評估模型」一節):

Kotlin

val autoMLImageLabelerOptions = AutoMLImageLabelerOptions.Builder(localModel)
    .setConfidenceThreshold(0)  // Evaluate your model in the Firebase console
                                // to determine an appropriate value.
    .build()
val labeler = ImageLabeling.getClient(autoMLImageLabelerOptions)

Java

AutoMLImageLabelerOptions autoMLImageLabelerOptions =
        new AutoMLImageLabelerOptions.Builder(localModel)
                .setConfidenceThreshold(0.0f)  // Evaluate your model in the Firebase console
                                               // to determine an appropriate value.
                .build();
ImageLabeler labeler = ImageLabeling.getClient(autoMLImageLabelerOptions)

如果您有遠端託管的模型,則必須在執行之前先檢查是否已下載該模型。您可以使用模型管理員的 isModelDownloaded() 方法檢查模型下載工作的狀態。

雖然您只需要在執行標籤器之前確認這一點,但如果您同時擁有遠端託管模型和本機套件模型,則在為圖片標籤器執行個體化時,可能十分合理:如果您已下載完畢,請從遠端模型建立標籤器;若是下載完畢,則從本機模型建立標籤器。

Kotlin

RemoteModelManager.getInstance().isModelDownloaded(remoteModel)
    .addOnSuccessListener { isDownloaded -> 
    val optionsBuilder =
        if (isDownloaded) {
            AutoMLImageLabelerOptions.Builder(remoteModel)
        } else {
            AutoMLImageLabelerOptions.Builder(localModel)
        }
    // Evaluate your model in the Firebase console to determine an appropriate threshold.
    val options = optionsBuilder.setConfidenceThreshold(0.0f).build()
    val labeler = ImageLabeling.getClient(options)
}

Java

RemoteModelManager.getInstance().isModelDownloaded(remoteModel)
        .addOnSuccessListener(new OnSuccessListener() {
            @Override
            public void onSuccess(Boolean isDownloaded) {
                AutoMLImageLabelerOptions.Builder optionsBuilder;
                if (isDownloaded) {
                    optionsBuilder = new AutoMLImageLabelerOptions.Builder(remoteModel);
                } else {
                    optionsBuilder = new AutoMLImageLabelerOptions.Builder(localModel);
                }
                AutoMLImageLabelerOptions options = optionsBuilder
                        .setConfidenceThreshold(0.0f)  // Evaluate your model in the Firebase console
                                                       // to determine an appropriate threshold.
                        .build();

                ImageLabeler labeler = ImageLabeling.getClient(options);
            }
        });

如果您只有遠端託管模型,請停用模型相關功能 (例如顯示為灰色或隱藏部分 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.
            }
        });

2. 準備輸入圖片

接著,請為要加上標籤的每張圖片建立 InputImage 物件。使用 Bitmap 時,圖片標籤器的執行速度最快;如果使用的是 camera2 API,則為 YUV_420_888 media.Image,建議您盡可能採用這種做法。

您可以從不同來源建立 InputImage 物件,以下說明每種來源。

使用 media.Image

如要從 media.Image 物件建立 InputImage 物件 (例如從裝置相機拍攝圖片),請將 media.Image 物件和圖片的旋轉角度傳遞至 InputImage.fromMediaImage()

如果您使用 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

如要從檔案 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();
}

使用 ByteBufferByteArray

如要使用 ByteBufferByteArray 建立 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 物件以旋轉度表示。

3. 執行映像檔標籤工具

如要為圖片中的物件加上標籤,請將 image 物件傳遞至 ImageLabelerprocess() 方法。

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
                // ...
            }
        });

4. 取得已加上標籤物件的相關資訊

如果圖片標籤作業成功,系統會將 ImageLabel 物件清單傳遞至成功事件監聽器。每個 ImageLabel 物件都代表圖片中加上標籤的項目。您可以取得每個標籤的文字說明、相符結果的可信度分數,以及相符項目的索引。例如:

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();
}

改善即時成效的訣竅

如想在即時應用程式中為圖片加上標籤,請按照下列指南操作,以達到最佳影格速率:

  • 如果使用 Cameracamera2 API,請限制對圖片標籤器的呼叫。如果圖片標籤人員執行期間有新的影片影格,請捨棄影格。如需範例,請參閱快速入門導覽課程範例應用程式中的 VisionProcessorBase 類別。
  • 如果您使用 CameraX API,請務必將背壓策略設為預設值 ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST。這項功能可確保一次只會傳送一張圖片進行分析。如果分析器忙碌時生成更多圖片,圖片會自動捨棄,不會排入傳送佇列。呼叫 ImageProxy.close() 來關閉要分析的映像檔後,就會傳送下一個映像檔。
  • 如果使用圖片標籤工具的輸出內容,將圖像疊加在輸入圖片上,請先透過 ML Kit 取得結果,然後透過單一步驟算繪圖片和疊加層。這只會針對每個輸入影格算繪至螢幕介面一次。如需範例,請參閱快速入門導覽課程範例應用程式中的 CameraSourcePreview GraphicOverlay 類別。
  • 如果您使用 Camera2 API,請擷取 ImageFormat.YUV_420_888 格式的圖片。如果使用舊版 Camera API,請拍攝 ImageFormat.NV21 格式的圖片。