Python 的物件偵測指南

您可以使用 MediaPipe 物件偵測器工作,偵測多個物件類別的存在情形和位置。這些操作說明將說明如何在 Python 中使用物件偵測器工作。您可以在 GitHub 上找到這些操作說明中所述的程式碼範例。

您可以查看網頁示範,瞭解這項工作的實際運作情形。如要進一步瞭解這項工作的功能、模型和設定選項,請參閱總覽

程式碼範例

物件偵測器的範例程式碼提供了 Python 中此工作的完整實作方式,供您參考。這個程式碼可協助您測試此工作,並開始建構自己的文字分類應用程式。您只需使用網路瀏覽器,即可查看、執行及編輯物體偵測器範例程式碼

如果您要為 Raspberry Pi 實作物件偵測器,請參閱 Raspberry Pi 範例應用程式

設定

本節將說明如何設定開發環境和程式碼專案,以便使用物體偵測器。如要進一步瞭解如何設定開發環境以使用 MediaPipe 工作,包括平台版本需求,請參閱 Python 設定指南

套件

物件偵測器工作需要使用 mediapipe pip 套件。您可以使用下列指令安裝必要套件:

$ python -m pip install mediapipe

匯入

匯入下列類別,存取 Object Detector 工作函式:

import mediapipe as mp
from mediapipe.tasks import python
from mediapipe.tasks.python import vision

型號

MediaPipe 物件偵測器工作需要訓練的模型,且該模型必須與此工作相容。如要進一步瞭解物件偵測器可用的訓練模型,請參閱任務總覽的「模型」一節。

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

model_path = '/absolute/path/to/lite-model_efficientdet_lite0_detection_metadata_1.tflite'

使用 BaseOptions 物件的 model_asset_path 參數,指定要使用的模型路徑。如需程式碼範例,請參閱下一節。

建立工作

使用 create_from_options 函式建立工作。create_from_options 函式可接受設定選項,包括執行模式、顯示名稱語言代碼、結果數量上限、信心閾值、類別許可清單和拒絕清單。如果您未設定設定選項,工作會使用預設值。如要進一步瞭解設定選項,請參閱「設定選項」一節。

物件偵測器工作支援多種輸入資料類型:靜態圖片、影片檔案和即時影片串流。請選擇對應於輸入資料類型的分頁,瞭解如何建立工作並執行推論。

圖片

import mediapipe as mp

BaseOptions = mp.tasks.BaseOptions
ObjectDetector = mp.tasks.vision.ObjectDetector
ObjectDetectorOptions = mp.tasks.vision.ObjectDetectorOptions
VisionRunningMode = mp.tasks.vision.RunningMode

options = ObjectDetectorOptions(
    base_options=BaseOptions(model_asset_path='/path/to/model.tflite'),
    max_results=5,
    running_mode=VisionRunningMode.IMAGE)

with ObjectDetector.create_from_options(options) as detector:
  # The detector is initialized. Use it here.
  # ...
    

影片

import mediapipe as mp

BaseOptions = mp.tasks.BaseOptions
ObjectDetector = mp.tasks.vision.ObjectDetector
ObjectDetectorOptions = mp.tasks.vision.ObjectDetectorOptions
VisionRunningMode = mp.tasks.vision.RunningMode

options = ObjectDetectorOptions(
    base_options=BaseOptions(model_asset_path='/path/to/model.tflite'),
    max_results=5,
    running_mode=VisionRunningMode.VIDEO)

with ObjectDetector.create_from_options(options) as detector:
  # The detector is initialized. Use it here.
  # ...
    

直播

import mediapipe as mp

BaseOptions = mp.tasks.BaseOptions
DetectionResult = mp.tasks.components.containers.detections.DetectionResult
ObjectDetector = mp.tasks.vision.ObjectDetector
ObjectDetectorOptions = mp.tasks.vision.ObjectDetectorOptions
VisionRunningMode = mp.tasks.vision.RunningMode

def print_result(result: DetectionResult, output_image: mp.Image, timestamp_ms: int):
    print('detection result: {}'.format(result))

options = ObjectDetectorOptions(
    base_options=BaseOptions(model_asset_path='/path/to/model.tflite'),
    running_mode=VisionRunningMode.LIVE_STREAM,
    max_results=5,
    result_callback=print_result)

with ObjectDetector.create_from_options(options) as detector:
  # The detector is initialized. Use it here.
  # ...
    

如需建立物件偵測器的完整範例,以便搭配圖片使用,請參閱程式碼範例

設定選項

此工作包含下列 Python 應用程式的設定選項:

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

IMAGE:單一圖片輸入模式。

VIDEO:影片解碼影格模式。

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

準備資料

將輸入內容設為圖片檔案或 Numpy 陣列,然後轉換為 mediapipe.Image 物件。如果輸入內容是網路攝影機的影片檔案或直播內容,您可以使用 OpenCV 等外部程式庫,將輸入影格載入為 Numpy 陣列。

以下範例說明如何為每種可用資料類型準備處理資料:

圖片

import mediapipe as mp

# Load the input image from an image file.
mp_image = mp.Image.create_from_file('/path/to/image')

# Load the input image from a numpy array.
mp_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=numpy_image)
    

影片

import mediapipe as mp

# Use OpenCV’s VideoCapture to load the input video.

# Load the frame rate of the video using OpenCV’s CV_CAP_PROP_FPS
# You’ll need it to calculate the timestamp for each frame.

# Loop through each frame in the video using VideoCapture#read()

# Convert the frame received from OpenCV to a MediaPipe’s Image object.
mp_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=numpy_frame_from_opencv)
    

直播

import mediapipe as mp

# Use OpenCV’s VideoCapture to start capturing from the webcam.

# Create a loop to read the latest frame from the camera using VideoCapture#read()

# Convert the frame received from OpenCV to a MediaPipe’s Image object.
mp_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=numpy_frame_from_opencv)
    

執行工作

您可以呼叫其中一個偵測函式來觸發推論。物件偵測器工作會傳回輸入圖片或影格中偵測到的物件。

圖片

# Perform object detection on the provided single image.
detection_result = detector.detect(mp_image)
    

影片

# Calculate the timestamp of the current frame
frame_timestamp_ms = 1000 * frame_index / video_file_fps

# Perform object detection on the video frame.
detection_result = detector.detect_for_video(mp_image, frame_timestamp_ms)
    

直播

# Send the latest frame to perform object detection.
# Results are sent to the `result_callback` provided in the `ObjectDetectorOptions`.
detector.detect_async(mp_image, frame_timestamp_ms)
    

如需在圖片上執行物體偵測器的完整範例,請參閱程式碼範例

注意事項:

  • 在影片模式或直播模式下執行時,您也必須為物件偵測器工作提供輸入影格時間戳記。
  • 在圖片或影片模型中執行時,物件偵測器工作會阻斷目前執行緒,直到處理完輸入圖片或影格為止。
  • 在直播模式下執行時,物件偵測器工作不會封鎖目前的執行緒,而是會立即傳回。每次處理完輸入影格後,它都會使用偵測結果叫用結果監聽器。如果在物件偵測器工作忙於處理另一個影格時呼叫偵測函式,系統會忽略新的輸入影格。

處理及顯示結果

執行推論後,物件偵測器工作會傳回 ObjectDetectionResult 物件,該物件會描述在輸入圖片中找到的物件。

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

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

下圖是工作輸出內容的視覺化呈現:

兩隻狗以定界框標示

物體偵測器範例程式碼示範如何顯示工作傳回的偵測結果,詳情請參閱程式碼範例