Python 顔検出ガイド

MediaPipe Face Detector タスクを使用すると、画像や動画内の顔を検出できます。このタスクを使用して、フレーム内の顔や顔の特徴を特定できます。このタスクでは、単一の画像または画像の連続ストリームを操作する機械学習(ML)モデルを使用します。このタスクは、顔の位置と、顔のキーポイント(左目、右目、鼻先、口、左目による悲惨、右目の悲劇)を出力します。

この手順で説明されているコードサンプルは、GitHub で入手できます。このタスクの機能、モデル、構成オプションの詳細については、概要をご覧ください。

サンプルコード

Face Detector のサンプルコードでは、参考までにこのタスクの Python での完全な実装が提供されています。このコードは、このタスクをテストして独自の顔検出器の作成を開始するうえで役立ちます。ウェブブラウザを使用して、顔検出ツールのサンプルコードを表示、実行、編集できます。

Raspberry Pi 用の顔検出機能を実装する場合は、Raspberry Pi サンプルアプリをご覧ください。

セットアップ

このセクションでは、顔検出機能を使用するための開発環境とコード プロジェクトを設定する際の主な手順について説明します。プラットフォームのバージョン要件など、MediaPipe タスクを使用するための開発環境の設定に関する一般的な情報については、Python の設定ガイドをご覧ください。

パッケージ

MediaPipe Face Detector タスクには 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 Face Detector タスクは、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 タスクの実行モードを設定します。モードは 3 つあります。

IMAGE: 単一の画像入力のモード。

VIDEO: 動画のデコードされたフレームのモード。

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 Face Detector がライブ ストリーム モードのときに検出結果を非同期で受け取るように結果リスナーを設定します。実行モードが 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)

次の図は、タスク出力を可視化したものです。

境界ボックスのない画像については、元の画像をご覧ください。

顔検出サンプルコードは、タスクから返された結果を表示する方法を示しています。詳細については、コードサンプルをご覧ください。