Android 圖片分類指南

MediaPipe 圖片分類器工作可讓您對圖片進行分類。您可以利用這項工作,在訓練時定義的一組類別中,找出圖片所代表的意義。這些操作說明會示範如何搭配 Android 應用程式使用圖片分類器。您可在 GitHub 找到本操作說明中所述的程式碼範例。

如要查看這項工作的實際操作方式,請參閱 Web 示範。 如要進一步瞭解此工作的功能、模型和設定選項,請參閱「總覽」一文。

程式碼範例

MediaPipe Tasks 範例程式碼是適用於 Android 的圖片分類器應用程式的簡易實作,這個例子使用實體 Android 裝置上的相機將物件持續分類,您也可以使用裝置圖片庫中的圖片和影片,將物件靜態分類。

您可以將該應用程式做為自己的 Android 應用程式起點,在修改現有應用程式時也可以參考該應用程式。Image Classifier 程式碼範例會在 GitHub 上託管。

下載程式碼

下列操作說明說明如何使用 git 指令列工具建立程式碼範例的本機副本。

如要下載範例程式碼,請按照下列步驟操作:

  1. 使用下列指令複製 git 存放區:
    git clone https://github.com/google-ai-edge/mediapipe-samples
    
  2. 您也可以選擇設定 Git 執行個體來使用稀疏結帳功能,這樣就只會擁有 Image Classifier 範例應用程式的檔案:
    cd mediapipe
    git sparse-checkout init --cone
    git sparse-checkout set examples/image_classification/android
    

建立範例程式碼的本機版本後,您可以將專案匯入 Android Studio 並執行應用程式。如需操作說明,請參閱 Android 設定指南

重要元件

下列檔案包含這個圖片分類範例應用程式的重要程式碼:

設定

本節說明設定開發環境,以及的程式碼專案使用 Image Classifier 的重要步驟。如需使用 MediaPipe 工作設定開發環境的一般資訊 (包括平台版本要求),請參閱 Android 設定指南

依附元件

圖片分類器使用 com.google.mediapipe:tasks-vision 程式庫。將此依附元件新增至 Android 應用程式開發專案的 build.gradle 檔案。使用下列程式碼匯入必要的依附元件:

dependencies {
    ...
    implementation 'com.google.mediapipe:tasks-vision:latest.release'
}

模型

MediaPipe Image Classifier 工作需要與這項工作相容的已訓練模型。如要進一步瞭解圖片分類器可用的已訓練模型,請參閱工作總覽的「模型」一節

選取並下載模型,然後將模型儲存在專案目錄中:

<dev-project-root>/src/main/assets

使用 BaseOptions.Builder.setModelAssetPath() 方法指定模型使用的路徑。下一節的程式碼範例介紹此方法。

在圖片分類器的程式碼範例中,模型是在 ImageClassifierHelper.kt 檔案中定義。

建立工作

您可以使用 createFromOptions 函式建立工作。createFromOptions 函式接受設定選項,包括執行模式、顯示名稱語言代碼、結果數量上限、可信度門檻,以及類別允許清單或拒絕清單。如要進一步瞭解設定選項,請參閱設定總覽

圖片分類器工作支援 3 種輸入資料類型:靜態圖片、影片檔案和直播影片串流。建立工作時,您必須指定與輸入資料類型相對應的執行模式。選擇與輸入資料類型相對應的分頁標籤,即可查看建立工作和執行推論的方式。

圖片

ImageClassifierOptions options =
  ImageClassifierOptions.builder()
    .setBaseOptions(
      BaseOptions.builder().setModelAssetPath("model.tflite").build())
    .setRunningMode(RunningMode.IMAGE)
    .setMaxResults(5)
    .build();
imageClassifier = ImageClassifier.createFromOptions(context, options);
    

影片

ImageClassifierOptions options =
  ImageClassifierOptions.builder()
    .setBaseOptions(
      BaseOptions.builder().setModelAssetPath("model.tflite").build())
    .setRunningMode(RunningMode.VIDEO)
    .setMaxResults(5)
    .build();
imageClassifier = ImageClassifier.createFromOptions(context, options);
    

直播

ImageClassifierOptions options =
  ImageClassifierOptions.builder()
    .setBaseOptions(
      BaseOptions.builder().setModelAssetPath("model.tflite").build())
    .setRunningMode(RunningMode.LIVE_STREAM)
    .setMaxResults(5)
    .setResultListener((result, inputImage) -> {
         // Process the classification result here.
    })
    .setErrorListener((result, inputImage) -> {
         // Process the classification errors here.
    })
    .build()
imageClassifier = ImageClassifier.createFromOptions(context, options)
    

實作圖片分類器程式碼範例後,使用者即可切換處理模式。這個方法會讓工作建立程式碼變得更複雜,可能不適合您的用途。您可以在 ImageClassifierHelper.kt 檔案的 setupImageClassifier() 函式中查看這個程式碼。

設定選項

這項工作有下列 Android 應用程式設定選項:

選項名稱 說明 值範圍 預設值
runningMode 設定任務的執行模式。有三種模式:

圖片:單一圖片輸入模式。

影片:影片已解碼影格的模式。

LIVE_STREAM:串流輸入資料的模式,例如相機。在這個模式下,您必須呼叫 resultListener,才能設定以非同步方式接收結果的事件監聽器。
{IMAGE, VIDEO, LIVE_STREAM} IMAGE
displayNamesLocale 設定工作模型中繼資料提供的顯示名稱 (如有) 要使用的標籤語言。預設值為 en (英文)。您可以使用 TensorFlow Lite Metadata Writer API,將本地化的標籤新增至自訂模型的中繼資料 語言代碼 en
maxResults 設定要傳回的最高分數分類結果數量上限。如果小於 0,會傳回所有可用的結果。 任何正數 -1
scoreThreshold 設定預測分數門檻,以覆寫模型中繼資料 (如有) 中提供的分數值。低於這個值的結果遭到拒絕。 任何浮點值 未設定
categoryAllowlist 設定允許使用的類別名稱清單 (選用)。如果非空白,則不在這個集合中的類別名稱分類結果會被篩除。系統會忽略重複或不明的類別名稱。這個選項與 categoryDenylist 互斥,且使用兩者都會導致錯誤。 任何字串 未設定
categoryDenylist 設定不允許使用的類別名稱清單 (選填)。如果非空白,則會篩除這個集中的類別名稱的分類結果。系統會忽略重複或不明的類別名稱。這個選項與 categoryAllowlist 互斥,且同時使用這兩種做法會導致錯誤。 任何字串 未設定
resultListener 設定結果事件監聽器,以便在圖片分類器處於直播模式時,以非同步方式接收分類結果。只有在執行模式設為「LIVE_STREAM」時才能使用 不適用 未設定
errorListener 設定選用的錯誤事件監聽器。 不適用 未設定

準備資料

「圖片分類器」適用於圖片、影片檔案和直播影片。該工作會處理資料輸入預先處理作業,包括調整大小、旋轉和值正規化。

您必須先將輸入圖片或影格轉換為 com.google.mediapipe.framework.image.MPImage 物件,才能將其傳遞至圖片分類器。

圖片

import com.google.mediapipe.framework.image.BitmapImageBuilder;
import com.google.mediapipe.framework.image.MPImage;

// Load an image on the user’s device as a Bitmap object using BitmapFactory.

// Convert an Android’s Bitmap object to a MediaPipe’s Image object.
Image mpImage = new BitmapImageBuilder(bitmap).build();
    

影片

import com.google.mediapipe.framework.image.BitmapImageBuilder;
import com.google.mediapipe.framework.image.MPImage;

// Load a video file on the user's device using MediaMetadataRetriever

// From the video’s metadata, load the METADATA_KEY_DURATION and
// METADATA_KEY_VIDEO_FRAME_COUNT value. You’ll need them
// to calculate the timestamp of each frame later.

// Loop through the video and load each frame as a Bitmap object.

// Convert the Android’s Bitmap object to a MediaPipe’s Image object.
Image mpImage = new BitmapImageBuilder(frame).build();
    

直播

import com.google.mediapipe.framework.image.MediaImageBuilder;
import com.google.mediapipe.framework.image.MPImage;

// Create a CameraX’s ImageAnalysis to continuously receive frames 
// from the device’s camera. Configure it to output frames in RGBA_8888
// format to match with what is required by the model.

// For each Android’s ImageProxy object received from the ImageAnalysis, 
// extract the encapsulated Android’s Image object and convert it to 
// a MediaPipe’s Image object.
android.media.Image mediaImage = imageProxy.getImage()
Image mpImage = new MediaImageBuilder(mediaImage).build();
    

在圖片分類器範例程式碼中,資料準備會在 ImageClassifierHelper.kt 檔案中處理。

執行工作

您可以呼叫與執行模式相對應的 classify 函式來觸發推論。Image Classifier API 會在輸入圖片或頁框中傳回物件的可能類別。

圖片

ImageClassifierResult classifierResult = imageClassifier.classify(image);
    

影片

// Calculate the timestamp in milliseconds of the current frame.
long frame_timestamp_ms = 1000 * video_duration * frame_index / frame_count;

// Run inference on the frame.
ImageClassifierResult classifierResult =
    imageClassifier.classifyForVideo(image, frameTimestampMs);
    

直播


// Run inference on the frame. The classifications results will be available 
// via the `resultListener` provided in the `ImageClassifierOptions` when 
// the image classifier was created.
imageClassifier.classifyAsync(image, frameTimestampMs);
    

注意事項:

  • 以影片模式或直播模式執行時,您也必須為圖片分類器工作提供輸入影格的時間戳記。
  • 以圖片或影片模式執行時,圖片分類器工作會封鎖目前的執行緒,直到處理輸入圖片或畫面為止。為避免封鎖使用者介面,請在背景執行緒中執行處理作業。
  • 在直播模式下執行時,圖片分類器工作不會封鎖目前的執行緒,但會立即傳回。每次完成處理輸入影格時,它都會叫用結果監聽器和偵測結果。如果在圖片分類器工作正忙於處理另一個影格時呼叫 classifyAsync 函式,則該工作會忽略新的輸入影格。

在圖片分類器程式碼範例中,classify 函式是在 ImageClassifierHelper.kt 檔案中定義。

處理及顯示結果

執行推論時,圖片分類器工作會傳回 ImageClassifierResult 物件,其中包含輸入圖片或頁框中物件的可能類別清單。

以下範例顯示這項工作的輸出資料範例:

ImageClassifierResult:
 Classifications #0 (single classification head):
  head index: 0
  category #0:
   category name: "/m/01bwb9"
   display name: "Passer domesticus"
   score: 0.91406
   index: 671
  category #1:
   category name: "/m/01bwbt"
   display name: "Passer montanus"
   score: 0.00391
   index: 670

以下裝置會執行 Bird Classifier 來取得這個結果:

在圖片分類器範例程式碼中,ClassificationResultsAdapter.kt 檔案中的 ClassificationResultsAdapter 類別會處理結果:

fun updateResults(imageClassifierResult: ImageClassifierResult? = null) {
    categories = MutableList(adapterSize) { null }
    if (imageClassifierResult != null) {
        val sortedCategories = imageClassifierResult.classificationResult()
            .classifications()[0].categories().sortedBy { it.index() }
        val min = kotlin.math.min(sortedCategories.size, categories.size)
        for (i in 0 until min) {
            categories[i] = sortedCategories[i]
        }
    }
}