はじめに
近年、AIによる画像認識技術は急速に進化しており、顔の検出だけでなく、年齢・性別・感情といった属性までリアルタイムに推定することが可能になってきました。
本記事では、物体検出に特化したYOLOv5と、顔属性の分析が可能なDeepFaceを組み合わせて、画像内の人物を検出し、その顔属性(年齢・性別・感情)を分析・可視化するPythonコードをご紹介します。
Google Colab上で動作するため、ローカル環境に依存せず簡単に実行できます。
参考リンクまとめ
Pythonコード
# --- 必要なライブラリをインストール / Install required libraries ---
!git clone https://github.com/ultralytics/yolov5.git
%cd yolov5
%pip install -r requirements.txt
%pip install deepface opencv-python fer
# --- ライブラリ読み込み / Import libraries ---
from deepface import DeepFace
from fer import FER
import torch
import cv2
import pandas as pd
from matplotlib import pyplot as plt
from google.colab import files
# --- モデルロード / Load models ---
model = torch.hub.load('ultralytics/yolov5', 'yolov5s', pretrained=True)
fer_detector = FER()
# --- Google Colab に画像アップロード / Upload image ---
uploaded = files.upload()
img_path = list(uploaded.keys())[0]
img = cv2.imread(img_path)
# --- 人物検出(YOLOv5)/ Detect "person" class ---
results = model(img_path)
df = results.pandas().xyxy[0]
faces = df[df['name'] == 'person']
# --- 各人物に感情分析を適用(FER+DeepFace) ---
for i, row in faces.iterrows():
x1, y1, x2, y2 = map(int, [row['xmin'], row['ymin'], row['xmax'], row['ymax']])
cropped = img[y1:y2, x1:x2]
# FERによる感情分析
fer_result = fer_detector.detect_emotions(cropped)
fer_emotion = "N/A"
if fer_result:
fer_top, fer_score = fer_detector.top_emotion(cropped)
fer_emotion = f"{fer_top} ({fer_score:.2f})"
else:
fer_emotion = "FER: Fail"
# DeepFaceによる感情分析
try:
deep_result = DeepFace.analyze(cropped, actions=['emotion'], enforce_detection=False)
deep_emotion = deep_result[0]['dominant_emotion']
except:
deep_emotion = "DeepFace: Fail"
# 結果表示(print & 画像に描画)/ Print and draw results
label = f"FER: {fer_emotion} / DF: {deep_emotion}"
print(f"Person {i+1}: {label}")
cv2.rectangle(img, (x1, y1), (x2, y2), (0, 128, 255), 2)
cv2.putText(img, label, (x1, y1 - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
# --- 画像表示 / Show annotated image ---
plt.figure(figsize=(12, 8))
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
plt.axis('off')
plt.title("Emotion Analysis: FER vs DeepFace")
plt.show()
結果
Person 1 emotion: happy
改善の余地あり