物件偵測器工作可讓您偵測多個物件類別是否存在,以及這些物件的位置。舉例來說,物件偵測器可在圖片中找出狗。這些操作說明會說明如何在 Android 上使用物件偵測器工作。您可以在 GitHub 上找到這些操作說明中所述的程式碼範例。您可以觀看這個網頁示範,瞭解這項工作的實際運作情形。如要進一步瞭解這項工作的功能、模型和設定選項,請參閱總覽。
程式碼範例
MediaPipe Tasks 範例程式碼是 Android 物件偵測器應用程式的簡單實作方式。這個範例會使用實體 Android 裝置的相機持續偵測物件,也可以使用裝置相片庫中的圖片和影片,以靜態方式偵測物件。
您可以使用這個應用程式做為自有 Android 應用程式的起點,或是在修改現有應用程式時參考。物體偵測器範例程式碼託管於 GitHub 上。
下載程式碼
以下操作說明說明如何使用 git 指令列工具,建立範例程式碼的本機副本。
下載程式碼範例:
- 使用下列指令複製 Git 存放區:
git clone https://github.com/google-ai-edge/mediapipe-samples
- 您可以選擇將 Git 例項設定為使用稀疏檢查,這樣就只會取得 Object Detector 範例應用程式的檔案:
cd mediapipe git sparse-checkout init --cone git sparse-checkout set examples/object_detection/android
建立本機版本的範例程式碼後,您可以將專案匯入 Android Studio 並執行應用程式。如需操作說明,請參閱 Android 設定指南。
重要元件
下列檔案包含物件偵測器範例應用程式的關鍵程式碼:
- ObjectDetectorHelper.kt - 初始化物件偵測器,並處理模型和委派函式選項
- MainActivity.kt:實作應用程式並組合使用者介面元件
- OverlayView.kt:處理並顯示結果
設定
本節將說明設定開發環境和程式碼專案以使用物體偵測器的關鍵步驟。如要進一步瞭解如何設定開發環境以使用 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:單一圖片輸入模式。 VIDEO:影片解碼影格模式。 LIVE_STREAM:輸入資料 (例如來自攝影機的資料) 的直播模式。在這個模式中,必須呼叫 resultListener,才能設定事件監聽器,以非同步方式接收結果。 |
{IMAGE, VIDEO, LIVE_STREAM } |
IMAGE |
displayNamesLocales |
設定標籤語言,用於工作模型中繼資料中提供的顯示名稱 (如有)。預設值為英文的 en 。您可以使用 TensorFlow Lite Metadata Writer API,在自訂模型的中繼資料中新增本地化標籤。 |
語言代碼 | en |
maxResults |
設定要傳回的最高分數偵測結果選用數量上限。 | 任何正數 | -1 (傳回所有結果) |
scoreThreshold |
設定預測分數門檻,覆寫模型中繼資料中提供的門檻 (如果有)。低於這個值的結果會遭到拒絕。 | 任何浮點 | 未設定 |
categoryAllowlist |
設定允許的選項類別名稱清單。如果不為空白,則偵測結果的類別名稱若不在這個集合中,就會篩除。系統會忽略重複或不明的類別名稱。這個選項與 categoryDenylist 互斥,如果同時使用這兩個選項,系統會傳回錯誤。 |
任何字串 | 未設定 |
categoryDenylist |
設定選用的不允許類別名稱清單。如果不為空白,系統會篩除偵測結果中類別名稱屬於這個集合的結果。系統會忽略重複或不明的類別名稱。這個選項與 categoryAllowlist 互斥,如果同時使用這兩個選項,會導致錯誤。 |
任何字串 | 未設定 |
resultListener |
在物件偵測器處於即時串流模式時,將結果事件監聽器設為以非同步方式接收偵測結果。只有在將 runningMode 設為 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()
用於影片串流。在影片串流上執行偵測作業時,請務必在個別執行緒上執行偵測作業,以免阻斷使用者介面執行緒。
以下程式碼範例提供簡單的範例,說明如何在這些不同資料模式下執行 Object Detector:
圖片
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
類別。