Android 物件偵測指南

物件偵測工具工作可讓您偵測多個物件類別是否存在,以及其位置。舉例來說,物件偵測工具可以找出圖片中的狗。以下操作說明將說明如何在 Android 上使用物件偵測器工作。您可以前往 GitHub 取得這些操作說明中提及的程式碼範例。如要查看這項工作的實際運作情形,請參閱這個網頁示範。如要進一步瞭解這項工作的功能、模型和設定選項,請參閱總覽

程式碼範例

MediaPipe Tasks 範例程式碼是 Android 物件偵測工具應用程式的簡易實作方式。這個範例使用實體 Android 裝置的相機持續偵測物件,也能使用裝置圖片庫中的圖片和影片,以靜態方式偵測物件。

您可以將該應用程式做為開發 Android 應用程式的起點,也可以在修改現有應用程式時參照。物件偵測工具範例程式碼由 GitHub 代管。

下載程式碼

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

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

  1. 使用下列指令複製 Git 存放區:
    git clone https://github.com/google-ai-edge/mediapipe-samples
    
  2. 您可以選擇將 Git 執行個體設為使用稀疏檢查,因此只有物件偵測工具範例應用程式的檔案:
    cd mediapipe
    git sparse-checkout init --cone
    git sparse-checkout set examples/object_detection/android
    

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

重要元件

下列檔案包含物件偵測工具範例應用程式的重要程式碼:

設定

本節說明設定開發環境及程式碼專案以使用物件偵測工具的重要步驟。如需瞭解如何設定開發環境以使用 MediaPipe 工作 (包括平台版本需求),請參閱「Android 設定指南」。

依附元件

物件偵測工具使用 com.google.mediapipe:tasks-vision 程式庫。將這個依附元件新增至 Android 應用程式開發專案的 build.gradle 檔案。使用下列程式碼匯入必要的依附元件:

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

型號

MediaPipe 物件偵測工具工作需要與這項工作相容的已訓練模型。如要進一步瞭解物件偵測工具的可用已訓練模型,請參閱工作總覽一節。

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

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

請使用 BaseOptions.Builder.setModelAssetPath() 方法指定模型使用的路徑。如需程式碼範例,請參閱下一節。

建立工作

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

物件偵測工具工作支援 3 種輸入資料類型:靜態圖片、影片檔案和即時影片串流。您在建立工作時,需要指定與輸入資料類型相對應的執行模式。請選擇與輸入資料類型對應的分頁標籤,瞭解如何建立工作並執行推論。

圖片

ObjectDetectorOptions options =
  ObjectDetectorOptions.builder()
    .setBaseOptions(BaseOptions.builder().setModelAssetPath(‘model.tflite’).build())
    .setRunningMode(RunningMode.IMAGE)
    .setMaxResults(5)
    .build();
objectDetector = ObjectDetector.createFromOptions(context, options);
    

影片

ObjectDetectorOptions options =
  ObjectDetectorOptions.builder()
    .setBaseOptions(BaseOptions.builder().setModelAssetPath(‘model.tflite’).build())
    .setRunningMode(RunningMode.VIDEO)
    .setMaxResults(5)
    .build();
objectDetector = ObjectDetector.createFromOptions(context, options);
    

直播

ObjectDetectorOptions options =
  ObjectDetectorOptions.builder()
    .setBaseOptions(BaseOptions.builder().setModelAssetPath(‘model.tflite’).build())
    .setRunningMode(RunningMode.LIVE_STREAM)
    .setMaxResults(5)
    .setResultListener((result, inputImage) -> {
      // Process the detection result here.
    })
    .setErrorListener((result, inputImage) -> {
      // Process the classification errors here.
    })
   .build();
objectDetector = ObjectDetector.createFromOptions(context, options);
    

物件偵測工具的程式碼範例可讓使用者切換處理模式。這種做法會讓工作建立程式碼變得更加複雜,並且可能不適合您的用途。您可以在 ObjectDetectorHelper 類別 setupObjectDetector() 函式中看到此程式碼。

設定選項

這項工作的 Android 應用程式設定選項如下:

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

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

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

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

準備資料

您必須先將輸入圖片或框架轉換為 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 values. Use these values
// 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()
MPImage mpImage = new MediaImageBuilder(mediaImage).build();
    

在物件偵測工具範例程式碼中,資料準備是在 detectImage()detectVideoFile()detectLivestreamFrame() 函式的 ObjectDetectorHelper 類別中處理。

執行工作

視處理的資料類型而定,請使用該資料類型專屬的 ObjectDetector.detect...() 方法。針對個別圖片使用 detect()detectForVideo() 用於影片檔案中的影格,detectAsync() 用於影片串流。在影片串流中執行偵測時,請務必在另一個執行緒上執行偵測,以免封鎖使用者介面執行緒。

以下程式碼範例顯示如何在不同的資料模式中執行物件偵測工具:

圖片

ObjectDetectorResult detectionResult = objectDetector.detect(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.
ObjectDetectorResult detectionResult =
    objectDetector.detectForVideo(image, frameTimestampMs);
    

直播

// Run inference on the frame. The detection results will be available
// via the `resultListener` provided in the `ObjectDetectorOptions` when
// the object detector was created.
objectDetector.detectAsync(image, frameTimestampMs);
    

物件偵測工具程式碼範例會詳細說明 detect()detectVideoFile()detectAsync() 等各模式的實作方式。範例程式碼可讓使用者切換不同的處理模式,但您的用途可能不需要這些模式。

注意事項:

  • 以影片模式或直播模式執行時,您也必須向物件偵測工具工作提供輸入影格的時間戳記。
  • 以圖片或影片模式執行時,物件偵測工具工作會封鎖目前的執行緒,直到完成輸入圖片或影格的處理為止。為避免封鎖目前的執行緒,請在背景執行緒中執行處理作業。
  • 以直播模式執行時,物件偵測器工作不會封鎖目前的執行緒,但會立即傳回。每當它處理完輸入影格時,就會透過偵測結果叫用結果監聽器。當物件偵測工具工作忙於處理其他影格時,呼叫了偵測函式時,系統會忽略新的輸入影格。

處理並顯示結果

執行推論時,物件偵測工具工作會傳回 ObjectDetectorResult 物件,說明它在輸入圖片中找到的物件。

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

ObjectDetectorResult:
 Detection #0:
  Box: (x: 355, y: 133, w: 190, h: 206)
  Categories:
   index       : 17
   score       : 0.73828
   class name  : dog
 Detection #1:
  Box: (x: 103, y: 15, w: 138, h: 369)
  Categories:
   index       : 17
   score       : 0.73047
   class name  : dog

下圖以視覺化方式呈現工作輸出內容:

物件偵測工具範例程式碼示範如何顯示工作傳回的偵測結果,詳情請參閱 OverlayView 類別。