Python 的臉部偵測指南

MediaPipe 臉部偵測器工作可讓你偵測圖片或影片中的臉孔。您可以使用這項工作找出影格中的臉孔和臉部特徵。這項工作使用的機器學習 (ML) 模型搭配單一圖片或連續圖片串流。這項工作會輸出臉部位置和下列臉部關鍵點:左眼、右眼、鼻子小費、嘴巴、左眼腹部和右眼對焦。

您可以前往 GitHub 取得這些操作說明中提及的程式碼範例。如要進一步瞭解這項工作的功能、模型和設定選項,請參閱總覽

程式碼範例

臉部偵測器的範例程式碼提供這項工作的完整實作在 Python 中供您參考。這段程式碼可協助您測試這項工作,並開始建構自己的臉部偵測工具。您可以使用網路瀏覽器來查看、執行及編輯臉部偵測器範例程式碼

如果您要實作 Raspberry Pi 的臉部偵測器,請參閱 Raspberry Pi 範例應用程式

設定

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

套裝組合

MediaPipe 臉部偵測器工作需要 mediapipe PyPI 套件。 您可以使用下列程式碼安裝並匯入這些依附元件:

$ 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/face_detector.task'

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

建立工作

MediaPipe 臉部偵測器工作會使用 create_from_options 函式設定工作。create_from_options 函式可接受設定選項值來處理。如要進一步瞭解設定選項,請參閱「設定選項」一文。

下列程式碼示範如何建構及設定這項工作。

這些範例也會顯示圖片、影片檔案和直播工作建構的變化。

圖片

import mediapipe as mp

BaseOptions = mp.tasks.BaseOptions
FaceDetector = mp.tasks.vision.FaceDetector
FaceDetectorOptions = mp.tasks.vision.FaceDetectorOptions
VisionRunningMode = mp.tasks.vision.RunningMode

# Create a face detector instance with the image mode:
options = FaceDetectorOptions(
    base_options=BaseOptions(model_asset_path='/path/to/model.task'),
    running_mode=VisionRunningMode.IMAGE)
with FaceDetector.create_from_options(options) as detector:
  # The detector is initialized. Use it here.
  # ...
    

影片

import mediapipe as mp

BaseOptions = mp.tasks.BaseOptions
FaceDetector = mp.tasks.vision.FaceDetector
FaceDetectorOptions = mp.tasks.vision.FaceDetectorOptions
VisionRunningMode = mp.tasks.vision.RunningMode

# Create a face detector instance with the video mode:
options = FaceDetectorOptions(
    base_options=BaseOptions(model_asset_path='/path/to/model.task'),
    running_mode=VisionRunningMode.VIDEO)
with FaceDetector.create_from_options(options) as detector:
  # The detector is initialized. Use it here.
  # ...
    

直播

import mediapipe as mp

BaseOptions = mp.tasks.BaseOptions
FaceDetector = mp.tasks.vision.FaceDetector
FaceDetectorOptions = mp.tasks.vision.FaceDetectorOptions
FaceDetectorResult = mp.tasks.vision.FaceDetectorResult
VisionRunningMode = mp.tasks.vision.RunningMode

# Create a face detector instance with the live stream mode:
def print_result(result: FaceDetectorResult, output_image: mp.Image, timestamp_ms: int):
    print('face detector result: {}'.format(result))

options = FaceDetectorOptions(
    base_options=BaseOptions(model_asset_path='/path/to/model.task'),
    running_mode=VisionRunningMode.LIVE_STREAM,
    result_callback=print_result)
with FaceDetector.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
min_detection_confidence 系統會將臉部偵測判定為成功的最低可信度分數。 Float [0,1] 0.5
min_suppression_threshold 系統會將臉部偵測判定為重疊的非最大抑制門檻。 Float [0,1] 0.3
result_callback 設定結果事件監聽器,在臉部偵測器處於直播模式時,以非同步方式接收偵測結果。只能在執行模式設為 LIVE_STREAM 時使用。 N/A Not set

準備資料

將輸入準備為圖片檔或 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)
    

執行工作

臉部偵測器會使用 detectdetect_for_videodetect_async 函式觸發推論。進行臉部偵測時,這包括預先處理輸入資料,以及偵測圖片中的臉孔。

下列程式碼示範如何使用工作模型執行處理作業。

圖片

# Perform face detection on the provided single image.
# The face detector must be created with the image mode.
face_detector_result = detector.detect(mp_image)
    

影片

# Perform face detection on the provided single image.
# The face detector must be created with the video mode.
face_detector_result = detector.detect_for_video(mp_image, frame_timestamp_ms)
    

直播

# Send live image data to perform face detection.
# The results are accessible via the `result_callback` provided in
# the `FaceDetectorOptions` object.
# The face detector must be created with the live stream mode.
detector.detect_async(mp_image, frame_timestamp_ms)
    

注意事項:

  • 以影片模式或直播模式執行時,請一併為臉部偵測器工作提供輸入影格的時間戳記。
  • 在圖片或影片模型中執行時,臉部偵測器工作會封鎖目前的執行緒,直到處理完成輸入圖片或影格為止。
  • 以直播模式執行時,臉部偵測器工作會立即回傳,且不會封鎖目前的執行緒。每當它處理完輸入影格時,就會透過偵測結果叫用結果監聽器。如果臉部偵測器工作正在忙於處理其他影格時呼叫偵測功能,則任務會忽略新的輸入影格。

如需對圖片執行臉部偵測器的完整範例,請參閱程式碼範例

處理並顯示結果

臉部偵測器每次執行時,都會傳回 FaceDetectorResult 物件。結果物件會包含偵測到的臉孔的定界框,以及每個偵測到的臉孔可信度分數。

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

FaceDetectionResult:
  Detections:
    Detection #0:
      BoundingBox:
        origin_x: 126
        origin_y: 100
        width: 463
        height: 463
      Categories:
        Category #0:
          index: 0
          score: 0.9729152917861938
      NormalizedKeypoints:
        NormalizedKeypoint #0:
          x: 0.18298381567001343
          y: 0.2961040139198303
        NormalizedKeypoint #1:
          x: 0.3302789330482483
          y: 0.29289937019348145
        ... (6 keypoints for each face)
    Detection #1:
      BoundingBox:
        origin_x: 616
        origin_y: 193
        width: 430
        height: 430
      Categories:
        Category #0:
          index: 0
          score: 0.9251380562782288
      NormalizedKeypoints:
        NormalizedKeypoint #0:
          x: 0.6151331663131714
          y: 0.3713381886482239
        NormalizedKeypoint #1:
          x: 0.7460576295852661
          y: 0.38825345039367676
        ... (6 keypoints for each face)

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

如果圖片沒有定界框,請參閱原始圖片

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