1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

DeepFace: Pythonで始める顔認識

Posted at

DeepFaceはPythonで実装された、使いやすくて高機能な顔認識ライブラリです。このライブラリの特徴は、複数の最新の顔認識モデル(VGG-Face, Google FaceNet, OpenFace, DeepID, ArcFace等)をサポートしており、顔の検出から感情分析まで幅広い機能を提供していることです。

環境構築

パッケージのインストール

DeepFaceと必要な依存パッケージをインストールします:

# DeepFaceのインストール
pip install deepface

# Keras関連パッケージのインストール
pip install tf-keras

# その他の依存パッケージ(必要に応じて)
pip install tensorflow
pip install opencv-python
pip install mediapipe  # MediaPipe検出器を使用する場合

注意: GPUを使用する場合は、tensorflow-gpuもインストールすることで処理速度が向上します。

動作確認

インストールが完了したら、以下のコードで動作確認ができます:

from deepface import DeepFace
import cv2

# バージョン確認
print("DeepFace version:", DeepFace.__version__)

# テスト画像で簡単な分析
img = cv2.imread("test.jpg")
results = DeepFace.analyze(img, actions=['age', 'gender'])
if len(results) > 0:
    print("顔を検出しました:", results[0])

重要: 初回実行時に、必要なモデルが自動的にダウンロードされます。

基本機能

DeepFaceの主な機能は以下の通りです:

  1. 顔の検出(Face Detection)
  2. 顔の照合(Face Verification)
  3. 顔の認識(Face Recognition)
  4. 顔の属性分析(年齢、性別、感情など)
  5. リアルタイム分析

基本的な使い方

1. 顔の照合

2つの画像の顔が同一人物かどうかを判定します:

from deepface import DeepFace
import cv2

try:
    # 2つの画像を比較
    result = DeepFace.verify(img1_path = "img1.jpg", 
                            img2_path = "img2.jpg")

    print("同一人物?: ", result["verified"])
    print("類似度: ", result["distance"])
    
except Exception as e:
    print("エラーが発生しました:", str(e))

2. 顔の属性分析

画像から年齢、性別、感情などを分析します:

try:
    # 画像を分析
    analysis = DeepFace.analyze(img_path = "img.jpg",
                              actions = ['age', 'gender', 'emotion', 'race'])
    
    if len(analysis) > 0:
        result = analysis[0]  # 最初の検出された顔の結果
        print("推定年齢: ", result["age"])
        
        # 性別の確率を表示
        gender_probs = result["gender"]
        dominant_gender = max(gender_probs.items(), key=lambda x: x[1])[0]
        print(f"性別: {dominant_gender} ({gender_probs[dominant_gender]:.2f}%)")
        
        print("感情: ", result["dominant_emotion"])
        print("人種: ", result["dominant_race"])
    else:
        print("顔が検出されませんでした")
        
except Exception as e:
    print("エラーが発生しました:", str(e))

高度な使用例

1. モデルの選択

DeepFaceは複数の顔認識モデルをサポートしています:

result = DeepFace.verify(img1_path = "img1.jpg",
                        img2_path = "img2.jpg",
                        model_name = "VGG-Face")  # または "Facenet", "OpenFace", "DeepFace", "DeepID", "ArcFace"

2. リアルタイム分析

Webカメラからのリアルタイム顔認識も可能です:

import cv2
from deepface import DeepFace
import numpy as np

# Webカメラを開く
cap = cv2.VideoCapture(0)

while True:
    ret, frame = cap.read()
    
    try:
        # フレームを分析
        analysis = DeepFace.analyze(frame, 
                                  actions=['emotion'],
                                  enforce_detection=False)
        
        if len(analysis) > 0:
            # 結果を表示
            emotion = analysis[0]["dominant_emotion"]
            cv2.putText(frame, emotion, (50,50),
                       cv2.FONT_HERSHEY_SIMPLEX, 1, (0,255,0), 2)
        
    except Exception as e:
        pass
        
    cv2.imshow('Real Time Analysis', frame)
    
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

パフォーマンスとベストプラクティス

  1. バッチ処理の活用

    • 多数の画像を処理する場合は、バッチ処理を利用することで処理を最適化できます。
  2. モデルの選択

    • 速度重視: VGG-Face
    • 精度重視: ArcFace
    • バランス: Facenet
  3. メモリ管理

    • 大量の画像を処理する場合は、適切なバッチサイズを設定することで、メモリ使用量を抑えることができます。

制限事項と注意点

  1. ライセンス

    • MITライセンスで提供されており、商用利用も可能です。
    • ただし、各モデルには独自のライセンスがある場合があります。
  2. 検出の制限

    • 顔の向きや照明条件によって精度が影響を受けます。
    • 小さすぎる顔(デフォルトでは100x100ピクセル未満)は検出が困難です。
  3. プライバシーへの配慮

    • 顔認識技術を使用する際は、プライバシーとデータ保護に関する法的要件を確認することが重要です。

まとめ

DeepFaceは、高度な顔認識機能を簡単に利用できるライブラリです。基本的な顔の検出から感情分析まで、幅広いユースケースに対応できます。オープンソースで活発なコミュニティがあり、継続的に改善が行われているのも魅力的な点です。

参考リンク

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?