Python 的物件偵測指南

MediaPipe 物件偵測工具工作可讓您偵測多個物件類別是否存在,以及其位置。以下操作說明將示範如何在 Python 中使用物件偵測工具工作。您可以前往 GitHub 取得這些操作說明中提及的程式碼範例。

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

程式碼範例

物件偵測工具的程式碼範例提供 Python 中這項工作的完整實作供您參考。這個程式碼可協助您測試這項工作,並開始建構您自己的文字分類應用程式。您可以使用網路瀏覽器來檢視、執行及編輯物件偵測工具範例程式碼

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

設定

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

套裝組合

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

$ python -m pip install mediapipe

匯入

匯入下列類別即可存取物件偵測工具工作函式:

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:單一圖片輸入的模式。

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

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

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

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