在 Android 上使用以 AutoML 訓練的模型偵測圖片中的物件

使用 AutoML Vision Edge 自行訓練模型後, 即可在應用程式中使用圖片來偵測圖片中的物件

有兩種方法可以整合透過 AutoML Vision Edge 訓練的模型:您可以 將模型放置於應用程式的素材資源資料夾內 以便從 Firebase 動態下載

模型組合選項
在應用程式中封裝
  • 這個模型是應用程式 APK 的一部分
  • 可立即使用型號,即使 Android 裝置離線也沒問題
  • 不需要 Firebase 專案
由 Firebase 代管
  • 將模型上傳至 Firebase 機器學習
  • 縮減 APK 大小
  • 模型會隨選下載
  • 不必重新發布應用程式即可推送模型更新
  • 使用 Firebase 遠端設定輕鬆進行 A/B 測試
  • 需要 Firebase 專案

事前準備

  1. 如要下載模型,請務必 將 Firebase 新增至您的 Android 專案, 如果尚未建立當您要組合模型時,不必做出任何動作。

  2. 將 TensorFlow Lite Task 程式庫的依附元件新增至模組的 應用程式層級的 Gradle 檔案,通常為 app/build.gradle

    將模型與應用程式綁定:

    dependencies {
      // ...
      // Object detection with a bundled Auto ML model
      implementation 'org.tensorflow:tensorflow-lite-task-vision:0.0.0-nightly-SNAPSHOT'
    }
    

    如要從 Firebase 動態下載模型,請一併新增 Firebase ML 依附元件:

    dependencies {
      // ...
      // Object detection with an Auto ML model deployed to Firebase
      implementation platform('com.google.firebase:firebase-bom:26.1.1')
      implementation 'com.google.firebase:firebase-ml-model-interpreter'
    
      implementation 'org.tensorflow:tensorflow-lite-task-vision:0.0.0-nightly'
    }
    

1. 載入模型

設定本機模型來源

將模型與應用程式組合如下:

  1. 從您從 存取 Google Cloud 控制台
  2. 將模型納入應用程式套件:
    1. 如果專案沒有素材資源資料夾,請按照 在 app/ 資料夾上按一下滑鼠右鍵,然後點選 新增 >資料夾 >素材資源資料夾
    2. 將含有內嵌中繼資料的 tflite 模型檔案複製到資產中 資料夾。
  3. 請將以下內容新增至應用程式的 build.gradle 檔案,確保 Gradle 不會在建構應用程式時壓縮模型檔案:

    android {
        // ...
        aaptOptions {
            noCompress "tflite"
        }
    }
    

    模型檔案會包含在應用程式套件中 做為原始素材資源

設定 Firebase 託管的模型來源

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

Java

// Specify the name you assigned when you deployed the model.
FirebaseCustomRemoteModel remoteModel =
        new FirebaseCustomRemoteModel.Builder("your_model").build();

Kotlin

// Specify the name you assigned when you deployed the model.
val remoteModel =
    FirebaseCustomRemoteModel.Builder("your_model_name").build()

接著,啟動模型下載工作,並指定在 您要允許下載的應用程式。如果裝置上沒有該型號,或者是新型號 就能以非同步方式下載該模型 建立 Vertex AI 模型

Java

DownloadConditions downloadConditions = new DownloadConditions.Builder()
        .requireWifi()
        .build();
RemoteModelManager.getInstance().download(remoteModel, downloadConditions)
        .addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(@NonNull Task<Void> task) {
                // Success.
            }
        });

Kotlin

val downloadConditions = DownloadConditions.Builder()
    .requireWifi()
    .build()
RemoteModelManager.getInstance().download(remoteModel, downloadConditions)
    .addOnSuccessListener {
        // Success.
    }

許多應用程式會在初始化程式碼中啟動下載工作,但您 這個模型會在您需要使用模型前執行

從模型建立物件偵測工具

設定模型來源後,請從該模型建立 ObjectDetector 物件 我們很快就會深入探討 所以目前先概略介紹

如果您只有本機組合模型,只要從 定義該模型檔案的可信度分數 要求的門檻 (請參閱評估模型):

Java

// Initialization
ObjectDetectorOptions options = ObjectDetectorOptions.builder()
    .setScoreThreshold(0)  // Evaluate your model in the Google Cloud console
                           // to determine an appropriate value.
    .build();
ObjectDetector objectDetector = ObjectDetector.createFromFileAndOptions(context, modelFile, options);

Kotlin

// Initialization
val options = ObjectDetectorOptions.builder()
    .setScoreThreshold(0)  // Evaluate your model in the Google Cloud console
                           // to determine an appropriate value.
    .build()
val objectDetector = ObjectDetector.createFromFileAndOptions(context, modelFile, options)

如果您使用的是遠端託管的模型,則須檢查該模型是否已 執行前已下載完成您可以查看模型下載狀態 使用模型管理員的 isModelDownloaded() 方法完成任務

雖然您不必在執行物件偵測器之前確認 同時擁有遠端託管和本機封裝模型 要在將物件偵測工具執行個體化時執行這項檢查:請建立 從遠端模型下載的物件偵測工具 反之。

Java

FirebaseModelManager.getInstance().isModelDownloaded(remoteModel)
        .addOnSuccessListener(new OnSuccessListener<Boolean>() {
            @Override
            public void onSuccess(Boolean isDownloaded) {
            }
        });

Kotlin

FirebaseModelManager.getInstance().isModelDownloaded(remoteModel)
        .addOnSuccessListener { success ->

        }

如果只有遠端託管的模型,請停用模型相關 或隱藏部分 UI,直到 您確認模型已下載完成附加監聽器即可 設為模型管理工具的 download() 方法

確定下載好模型後,請在 模型檔案:

Java

FirebaseModelManager.getInstance().getLatestModelFile(remoteModel)
        .addOnCompleteListener(new OnCompleteListener<File>() {
            @Override
            public void onComplete(@NonNull Task<File> task) {
                File modelFile = task.getResult();
                if (modelFile != null) {
                    ObjectDetectorOptions options = ObjectDetectorOptions.builder()
                            .setScoreThreshold(0)
                            .build();
                    objectDetector = ObjectDetector.createFromFileAndOptions(
                            getApplicationContext(), modelFile.getPath(), options);
                }
            }
        });

Kotlin

FirebaseModelManager.getInstance().getLatestModelFile(remoteModel)
        .addOnSuccessListener { modelFile ->
            val options = ObjectDetectorOptions.builder()
                    .setScoreThreshold(0f)
                    .build()
            objectDetector = ObjectDetector.createFromFileAndOptions(
                    applicationContext, modelFile.path, options)
        }

2. 準備輸入圖片

然後,針對要加上標籤的每張圖片,從TensorImage 圖片。您可以使用TensorImageBitmap fromBitmap 方法:

Java

TensorImage image = TensorImage.fromBitmap(bitmap);

Kotlin

val image = TensorImage.fromBitmap(bitmap)

如果圖片資料不在 Bitmap 中,您可以載入像素陣列,如下所示: TensorFlow Lite 說明文件

3. 執行物件偵測工具

如要偵測圖片中的物件,請將 TensorImage 物件傳遞至 ObjectDetectordetect() 方法。

Java

List<Detection> results = objectDetector.detect(image);

Kotlin

val results = objectDetector.detect(image)

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

如果物件偵測作業成功,則會傳回 Detection 清單 如需儲存大量結構化物件 建議使用 Cloud Bigtable每個 Detection 物件都代表系統在 圖片。您可以取得每個物件的定界框及其標籤。

例如:

Java

for (Detection result : results) {
    RectF bounds = result.getBoundingBox();
    List<Category> labels = result.getCategories();
}

Kotlin

for (result in results) {
    val bounds = result.getBoundingBox()
    val labels = result.getCategories()
}

即時效能改善訣竅

如要在即時應用程式中為圖片加上標籤,請按照下列步驟操作: 實現最佳影格速率:

  • 限制對圖片標籤人員的呼叫。如果新的影片影格 請在圖片標籤工具執行期間捨棄頁框。請參閱 VisionProcessorBase 類別的範例。
  • 如果您使用圖片標籤人員的輸出內容,將圖像重疊 會先取得結果,然後算繪圖像 並疊加單一步驟這麼一來,您的應用程式就會算繪到顯示途徑 每個輸入影格只能建立一次請參閱 CameraSourcePreview GraphicOverlay 類別, 範例。
  • 如果你使用 Camera2 API, ImageFormat.YUV_420_888 格式。

    如果使用舊版 Camera API,請以 ImageFormat.NV21 格式。