EmotiEffLibによる動画ベース感情認識(ソースコードと実行結果)

概要

動画やカメラ映像から人間の顔を検出し、表情から感情を認識するプログラムを示す。顔検出にはSCRFD、感情認識にはEmotiEffLib(EfficientNet-B2ベースの学習済みモデル enet_b2_8)を用いる。8つの基本感情の認識結果を5つの目的感情へ変換し、移動平均による時系列平滑化で表示を安定させる。


目次

関連する外部ページ

サイト内の関連情報

1. Python開発環境,ライブラリ類

ここでは、最低限の事前準備について説明する。機械学習や深層学習を行う場合は、NVIDIA CUDA、Visual Studio、Cursorなどを追加でインストールすると便利である。これらについては別ページ https://www.kkaneko.jp/cc/dev/aiassist.html で解説している。

2. Python 3.12 のインストール

Pythonのインストールを行い、Pythonのプログラムを実行する環境を整える。扱う環境は、Windows搭載パソコンである。金子研究室では、Python 3.12.10を推奨する。

[Windows での Python 3.12 のインストール手順を見るには、ここをクリック]

Windows での Python 3.12 のインストール

以下のいずれかの方法でPython 3.12をインストールする。Pythonがインストール済みの場合、この手順は不要である。

方法 1:winget によるインストール

インストールコマンドの実行方法

管理者権限コマンドプロンプトを起動する(手順:Windowsキーまたはスタートメニュー → cmd と入力 → 右クリック → 「管理者として実行」)。そして、コマンド全体をコマンドプロンプトにコピー&ペーストする。

--scope machine を指定することで、システム全体(全ユーザー向け)にインストールされる。このオプションの実行には管理者権限が必要である。インストール完了後、コマンドプロンプトを再起動するとPATHが反映される。

REM Python 3.12 をシステム領域にインストール
winget install --id Python.Python.3.12 -e --scope machine --silent --accept-source-agreements --accept-package-agreements --override "/quiet InstallAllUsers=1 PrependPath=1 Include_test=0 Include_pip=1 Include_launcher=1 InstallLauncherAllUsers=1 TargetDir=\"C:\Program Files\Python312\""
if not "%ERRORLEVEL%"=="0" ( color 0c & echo Python 3.12 のインストールに失敗しました & ping 127.0.0.1 -n 6 >nul & color )

REM Python と Scripts を PATH 先頭に追加
powershell -NoProfile -Command "$p='C:\Program Files\Python312'; $s=\"$p\Scripts\"; if(Test-Path $p){$k=[Microsoft.Win32.Registry]::LocalMachine.OpenSubKey('SYSTEM\CurrentControlSet\Control\Session Manager\Environment',$true); $c=$k.GetValue('Path','',[Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames); $t=$k.GetValueKind('Path'); $new=$c; if((';'+$new+';') -notlike \"*;$p;*\"){$new=$p+';'+$new}; if((';'+$new+';') -notlike \"*;$s;*\"){$new=$s+';'+$new}; if($new -ne $c){$k.SetValue('Path',$new,$t)}; $k.Close()}"

REM 現在のセッションにも反映(システムPATHを再取得して連結)
for /f "usebackq tokens=2,*" %A in (`reg query "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v Path`) do set "PATH=%B"

REM pip / wheel の更新
python -m pip install --no-user -U pip wheel
if not "%ERRORLEVEL%"=="0" ( color 0c & echo pip / wheel の更新に失敗しました & ping 127.0.0.1 -n 6 >nul & color )

方法 2:インストーラーによるインストール

  1. Python公式サイト(https://www.python.org/downloads/)にアクセスし、「Download Python 3.x.x」ボタンからWindows用インストーラーをダウンロードする。
  2. ダウンロードしたインストーラーを実行する。
  3. 初期画面の下部に表示される「Add python.exe to PATH」にチェックを入れてから「Customize installation」を選択する。このチェックを入れ忘れると、コマンドプロンプトから python コマンドを実行できない。
  4. 「Install Python 3.xx for all users」にチェックを入れ、「Install」をクリックする。

インストールの確認

コマンドプロンプトで以下を実行する。

python --version

バージョン番号(例:Python 3.12.x)が表示されればインストール成功である。「'python' は、内部コマンドまたは外部コマンドとして認識されていません。」と表示される場合は、インストールが正常に完了していない。

3. Python の開発環境 Visual Studio Code のインストールと Python 用の設定

Python の開発環境Visual Studio Code(プログラムを編集するソフトウェア。以下、VS Code)を整える。

[Windows での Visual Studio Code のインストールと Python 用の設定手順を見るには、ここをクリック]

Windows での Visual Studio Code のインストールと Python 用の設定手順

1. VS Code と拡張機能のインストール

以下のコマンドにより,既存の VS Code を削除し,全ユーザー共有の設定で再インストールしたうえで,拡張機能(VS Code に機能を追加するソフトウェア)をまとめて導入する.

インストールコマンドの実行方法

管理者権限コマンドプロンプトを起動する(手順:Windows キーまたはスタートメニュー → cmd と入力 → 右クリック → 「管理者として実行」)。そして,コマンド全体をコマンドプロンプトにコピー&ペーストする。

インストールコマンド


REM ============================================================
REM Microsoft Visual Studio Code
REM ============================================================
REM Build Tools + Desktop development with C++(VCTools)+ 追加コンポーネント(一括)
REM 未インストール時: winget で新規インストール
REM インストール済み時: setup.exe modify でコンポーネント追加(バージョンは変更しない)
winget list --id Microsoft.VisualStudio.BuildTools 2>nul | findstr /i "BuildTools" >nul 2>&1
if %ERRORLEVEL% EQU 0 (
    for /f "usebackq delims=" %P in (`"C:\Program Files (x86)\Microsoft Visual Studio\Installer\vswhere.exe" -products Microsoft.VisualStudio.Product.BuildTools -property installationPath`) do start /wait "" "C:\Program Files (x86)\Microsoft Visual Studio\Installer\setup.exe" modify --installPath "%P" --add Microsoft.VisualStudio.Workload.VCTools --add Microsoft.VisualStudio.Workload.MSBuildTools --add Microsoft.VisualStudio.Component.VC.CMake.Project --add Microsoft.VisualStudio.Component.VC.Llvm.Clang --add Microsoft.VisualStudio.Component.VC.Llvm.ClangToolset --add Microsoft.VisualStudio.Component.Windows11SDK.26100 --add Microsoft.VisualStudio.Component.VC.v143.x86.x64 --includeRecommended --quiet --norestart --nocache
    if not "%ERRORLEVEL%"=="0" ( color 0c & echo Build Tools のコンポーネント追加に失敗しました & ping 127.0.0.1 -n 6 >nul & color )
) else (
    winget install --scope machine --id Microsoft.VisualStudio.BuildTools -e --silent --disable-interactivity --force --accept-source-agreements --accept-package-agreements --override "--quiet --wait --norestart --nocache --add Microsoft.VisualStudio.Workload.VCTools --includeRecommended --add Microsoft.VisualStudio.Workload.MSBuildTools --add Microsoft.VisualStudio.Component.VC.CMake.Project --add Microsoft.VisualStudio.Component.VC.Llvm.Clang --add Microsoft.VisualStudio.Component.VC.Llvm.ClangToolset --add Microsoft.VisualStudio.Component.Windows11SDK.26100 --add Microsoft.VisualStudio.Component.VC.v143.x86.x64"
    if not "%ERRORLEVEL%"=="0" ( color 0c & echo Build Tools のインストールに失敗しました & ping 127.0.0.1 -n 6 >nul & color )
)

REM 全ユーザー共有の拡張機能フォルダ
if not exist "C:\ProgramData\vscode-extensions" mkdir "C:\ProgramData\vscode-extensions"
icacls "C:\ProgramData\vscode-extensions" /grant "Everyone:(OI)(CI)M" /T

REM スタートメニューのショートカットを --extensions-dir 付きで再作成
if exist "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Visual Studio Code" rmdir /s /q "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Visual Studio Code"
if exist "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Visual Studio Code.lnk" del "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Visual Studio Code.lnk"
powershell -NoProfile -Command "$s=New-Object -ComObject WScript.Shell; $lnk=$s.CreateShortcut('C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Visual Studio Code.lnk'); $lnk.TargetPath='C:\Program Files\Microsoft VS Code\Code.exe'; $lnk.Arguments='--extensions-dir \"C:\ProgramData\vscode-extensions\"'; $lnk.Save()"
REM ショートカットの検証
powershell -NoProfile -Command "$s=New-Object -ComObject WScript.Shell; $lnk=$s.CreateShortcut('C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Visual Studio Code.lnk'); Write-Host 'TargetPath:' $lnk.TargetPath; Write-Host 'Arguments:' $lnk.Arguments"

REM ファイル / フォルダ右クリックの「Code で開く」を登録
reg add "HKLM\SOFTWARE\Classes\*\shell\VSCode\command" /ve /d "\"C:\Program Files\Microsoft VS Code\Code.exe\" --extensions-dir \"C:\ProgramData\vscode-extensions\" \"%1\"" /f
reg add "HKLM\SOFTWARE\Classes\Directory\shell\VSCode\command" /ve /d "\"C:\Program Files\Microsoft VS Code\Code.exe\" --extensions-dir \"C:\ProgramData\vscode-extensions\" \"%1\"" /f
reg add "HKLM\SOFTWARE\Classes\Directory\Background\shell\VSCode\command" /ve /d "\"C:\Program Files\Microsoft VS Code\Code.exe\" --extensions-dir \"C:\ProgramData\vscode-extensions\" \"%V\"" /f

REM --extensions-dir 付きで起動する code.cmd ラッパを作成
REM (%* を echo で書くと対話的 cmd で失われるため、PowerShell で [char]37+'*' を書き出す)
powershell -NoProfile -Command "$pct=[char]37; $q=[char]34; $c='@echo off'+[char]13+[char]10+$q+'C:\Program Files\Microsoft VS Code\bin\code.cmd'+$q+' --extensions-dir '+$q+'C:\ProgramData\vscode-extensions'+$q+' '+$pct+'*'+[char]13+[char]10; [IO.File]::WriteAllText('C:\ProgramData\vscode-extensions\vscode.cmd',$c,[Text.Encoding]::ASCII)"

REM 拡張機能のインストール
set "CODE=C:\Program Files\Microsoft VS Code\bin\code.cmd"
"%CODE%" --extensions-dir "C:\ProgramData\vscode-extensions" --uninstall-extension GitHub.copilot
"%CODE%" --extensions-dir "C:\ProgramData\vscode-extensions" --uninstall-extension GitHub.copilot-chat
"%CODE%" --extensions-dir "C:\ProgramData\vscode-extensions" --install-extension ms-python.python
"%CODE%" --extensions-dir "C:\ProgramData\vscode-extensions" --install-extension ms-python.vscode-pylance
"%CODE%" --extensions-dir "C:\ProgramData\vscode-extensions" --install-extension ms-python.debugpy
"%CODE%" --extensions-dir "C:\ProgramData\vscode-extensions" --install-extension MS-CEINTL.vscode-language-pack-ja
"%CODE%" --extensions-dir "C:\ProgramData\vscode-extensions" --install-extension saoudrizwan.claude-dev
"%CODE%" --extensions-dir "C:\ProgramData\vscode-extensions" --install-extension rust-lang.rust-analyzer
"%CODE%" --extensions-dir "C:\ProgramData\vscode-extensions" --install-extension tamasfe.even-better-toml
"%CODE%" --extensions-dir "C:\ProgramData\vscode-extensions" --install-extension anthropic.claude-code
"%CODE%" --extensions-dir "C:\ProgramData\vscode-extensions" --install-extension almenon.arepl
"%CODE%" --extensions-dir "C:\ProgramData\vscode-extensions" --list-extensions --show-versions

REM settings.json を作成(自動更新オフ、Python、Claude Code 設定)
if not exist "%APPDATA%\Code\User" mkdir "%APPDATA%\Code\User"
python -c "import json,os;data={'update.mode':'none','update.enableWindowsBackgroundUpdates':False,'extensions.autoUpdate':False,'python.defaultInterpreterPath':r'C:\Program Files\Python312\python.exe','claudeCode.environmentVariables':[{'name':'ANTHROPIC_API_KEY','value':'not-needed'},{'name':'ANTHROPIC_AUTH_TOKEN','value':'ollama'},{'name':'ANTHROPIC_BASE_URL','value':'http://localhost:11434'},{'name':'ANTHROPIC_MODEL','value':'glm-4.7-flash'},{'name':'CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC','value':'1'}]};p=os.path.join(os.environ['APPDATA'],'Code','User','settings.json');open(p,'w',encoding='utf-8').write(json.dumps(data,indent=4));print('Done:',p)"

REM 自動更新の抑止ポリシー(settings.json に加えて、レジストリ側でも明示的にオフ)
reg add "HKLM\SOFTWARE\Policies\Microsoft\VSCode" /v "UpdateMode" /t REG_SZ /d "none" /f
echo === セットアップ完了 ===

2. Python インタプリタの選択

同一マシンに複数の Python がインストールされている場合,VS Code で使用する Python 本体(インタプリタ:Python プログラムを解釈・実行するソフトウェア)を選択する必要がある.

  1. コマンドパレット(コマンド名で機能を呼び出す VS Code の入力欄)を開く(Ctrl+Shift+P
  2. Python: Select Interpreter と入力する
  3. 表示される一覧から,使用する Python(例:C:\Program Files\Python312\python.exe)を選択する.

4. 必要なライブラリのインストール

必要なライブラリをシステム領域にインストールする。

管理者権限コマンドプロンプトを起動する (手順:Windowsキーまたはスタートメニュー → cmd と入力 → 右クリック → 「管理者として実行」)。

起動したコマンドプロンプトで以下を実行する。1行目でCUDA 12.8対応のPyTorchを、2行目で感情認識と顔検出に必要なライブラリをインストールする(--no-user はユーザ領域ではなくシステム領域へインストールする指定である)。

REM PyTorch をインストール(GPU対応版)
set "CUDA_TAG=cu128"
set "PYTHON_PATH=C:\Program Files\Python312"
"%PYTHON_PATH%\Scripts\pip" install -U --no-user numpy torch torchvision torchaudio --index-url https://download.pytorch.org/whl/%CUDA_TAG%
"%PYTHON_PATH%\Scripts\pip" install -U --no-user opencv-python pillow emotiefflib[torch] insightface

5. EmotiEffLibによる動画ベース感情認識プログラム

概要

動画やカメラ映像から人間の顔を検出し、表情を分析して感情を認識する機能を持つ。8つの基本感情から5つの目的感情への変換を行い、時系列データの平滑化によって安定した感情認識を実現している。

主要技術

参考文献

[1] Guo, J., Deng, J., Lattas, A., & Zafeiriou, S. (2021). Sample and computation redistribution for efficient face detection. arXiv preprint arXiv:2105.04714.

[2] Tan, M., & Le, Q. (2019). EfficientNet: Rethinking model scaling for convolutional neural networks. In Proceedings of the 36th International Conference on Machine Learning (pp. 6105-6114). PMLR.

[3] Savchenko, A. V. (2022). HSEmotion: High-speed emotion recognition library. Software Impacts, 14, 100433.

# EmotiEffLibによる動画ベース感情認識プログラム
# 特徴技術名: EfficientNetベース感情認識(EmotiEffLib)
# 出典: Savchenko, A. V., Savchenko, L. V., & Makarov, I. (2022). Classifying
#       emotions and engagement in online learning based on a single facial
#       expression recognition neural network. IEEE Transactions on Affective Computing.
# 特徴機能: 軽量EfficientNetアーキテクチャによる高速かつ高精度な感情認識、
#          30MBのコンパクトモデルで高精度な感情分類を実現
# 学習済みモデル: enet_b2_8(EfficientNet-B2ベース)- 8つの感情
#               (怒り、軽蔑、嫌悪、恐怖、幸福、中立、悲しみ、驚き)を認識、
#               モデルサイズ30MB、VGGFace2で事前学習しAffectNetで学習、
#               AffectNet 8クラスでの精度63.03%、EmotiEffLibが自動ダウンロード
#               https://github.com/sb-ai-lab/EmotiEffLib
#               顔検出は SCRFD-10GF(InsightFaceのモデルパック buffalo_l に同梱、
#               自動ダウンロード)
# 方式設計
#   - 関連利用技術: OpenCV(動画処理)、PyTorch(深層学習)、InsightFace SCRFD(顔検出)、
#                  EmotiEffLib(感情認識)、NumPy(数値計算)、Pillow(日本語表示)
#   - 入力と出力: 入力: 動画像,カメラ(ユーザは「0:動画ファイル,1:カメラ」のメニューで選択.
#                0:動画ファイルの場合はtkinterでファイル選択.1の場合はOpenCVでカメラが開く)
#                出力: リアルタイム感情認識結果を表示した動画
#   - 処理手順: 顔検出→前処理→EfficientNet特徴抽出→8感情分類→5感情マッピング→
#              時系列平滑化→可視化
#   - 前処理,後処理: 顔領域を260x260リサイズ、ImageNet正規化
#                    (平均: [0.485, 0.456, 0.406]、標準偏差: [0.229, 0.224, 0.225])、
#                    移動平均による時系列平滑化。前処理はEmotiEffLibが内部で実行する
#   - 追加処理: 8クラス感情から5つの目的感情への変換マッピング、
#              移動平均による予測結果の安定化
#   - 調整を必要とする設定値: EMOTION_WINDOW_SIZE(時系列平滑化フレーム数、デフォルト10)、
#                          DET_THRESH(顔検出の信頼度しきい値、デフォルト0.5)。
#                          プログラム中で実現可能な機能・将来方策:
#                          感情履歴の可視化機能、リアルタイム感情統計レポート機能
#   - その他の重要事項: 8感情から5感情への変換はマッピング行列により実現、
#                     日本語表示にはPillowライブラリを使用、
#                     顔の情報のみを使用した感情認識(顔以外の情報は使用しない)、
#                     静止画との違い:フレーム間の時系列情報を活用した移動平均による
#                     感情予測の安定化処理を実装
# 前準備
#   - pip install -U --no-user numpy torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu128
#   - pip install -U --no-user opencv-python pillow emotiefflib[torch] insightface

import cv2
import torch
import numpy as np
from PIL import Image, ImageDraw, ImageFont
import tkinter as tk
from tkinter import filedialog
from collections import deque
import sys
import io
import time
from insightface.app import FaceAnalysis
from emotiefflib.facial_analysis import EmotiEffLibRecognizer

# Windows文字エンコーディング設定
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', line_buffering=True)

# 調整可能な設定値
EMOTION_WINDOW_SIZE = 10  # 感情の時系列平滑化に使用するフレーム数
DET_THRESH = 0.5  # 顔検出の信頼度しきい値

# 感情ラベルの定義
ORIGINAL_EMOTIONS = ['怒り', '軽蔑', '嫌悪', '恐怖', '幸福', '中立', '悲しみ', '驚き']
TARGET_EMOTIONS = ['焦り', '楽しさ', 'ストレス', '集中', '疲労']

# 8クラスから5クラスへのマッピング行列
EMOTION_MAPPING = np.array([
    [0.3, 0.0, 0.5, 0.0, 0.2],  # 怒り → 焦り、ストレス、疲労
    [0.0, 0.0, 0.3, 0.3, 0.4],  # 軽蔑 → ストレス、集中、疲労
    [0.0, 0.0, 0.6, 0.0, 0.4],  # 嫌悪 → ストレス、疲労
    [0.7, 0.0, 0.3, 0.0, 0.0],  # 恐怖 → 焦り、ストレス
    [0.0, 0.9, 0.0, 0.1, 0.0],  # 幸福 → 楽しさ、集中
    [0.0, 0.1, 0.0, 0.8, 0.1],  # 中立 → 楽しさ、集中、疲労
    [0.0, 0.0, 0.4, 0.0, 0.6],  # 悲しみ → ストレス、疲労
    [0.4, 0.3, 0.3, 0.0, 0.0],  # 驚き → 焦り、楽しさ、ストレス
], dtype=np.float32)

# モデルの読み込み
print("感情認識モデルを読み込んでいます...")
device = 'cuda' if torch.cuda.is_available() else 'cpu'
ctx_id = 0 if torch.cuda.is_available() else -1

# EmotiEffLib感情認識器の初期化(学習済みモデルは自動ダウンロード)
fer = EmotiEffLibRecognizer(engine='torch', model_name='enet_b2_8', device=device)

# SCRFD顔検出器の初期化(buffalo_l に同梱の SCRFD-10GF、自動ダウンロード)
face_detector = FaceAnalysis(name='buffalo_l', allowed_modules=['detection'])
face_detector.prepare(ctx_id=ctx_id, det_thresh=DET_THRESH, det_size=(640, 640))

# 感情予測関数
def predict_emotions(face_bgr):
    face_rgb = cv2.cvtColor(face_bgr, cv2.COLOR_BGR2RGB)
    _, scores = fer.predict_emotions(face_rgb, logits=False)
    original_probs = scores[0]
    # 8クラスから5クラスへ変換
    target_probs = np.matmul(original_probs, EMOTION_MAPPING)
    return original_probs, target_probs

# 動画入力の選択
print("0: 動画ファイル")
print("1: Webカメラ")

choice = input("選択: ")

if choice == '0':
    root = tk.Tk()
    root.withdraw()
    path = filedialog.askopenfilename()
    if not path:
        exit()
    cap = cv2.VideoCapture(path)
else:
    cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)
    cap.set(cv2.CAP_PROP_BUFFERSIZE, 1)

# 感情履歴の初期化
emotion_history = deque(maxlen=EMOTION_WINDOW_SIZE)

# フォント設定(日本語表示用)
font = ImageFont.truetype("C:/Windows/Fonts/msgothic.ttc", 20)

# 5秒間隔でのprint表示用
last_print_time = time.time()

# メイン処理
while True:
    cap.grab()
    ret, frame = cap.retrieve()
    if not ret:
        break

    # SCRFDによる顔検出
    faces = face_detector.get(frame)

    # 最大の顔を1つ選択
    if len(faces) > 0:
        largest_face = max(faces, key=lambda face: (face.bbox[2] - face.bbox[0]) * (face.bbox[3] - face.bbox[1]))
        x, y, x2, y2 = largest_face.bbox.astype(int).tolist()
        # 顔領域を画面内に収める
        x, y = max(x, 0), max(y, 0)
        x2, y2 = min(x2, frame.shape[1]), min(y2, frame.shape[0])
        w = x2 - x

        # 顔領域の抽出
        face_roi = frame[y:y2, x:x2]

        # 感情予測
        original_emotions, target_emotions = predict_emotions(face_roi)

        # 履歴に追加
        emotion_history.append(target_emotions)

        # 移動平均の計算
        avg_emotions = np.mean(emotion_history, axis=0)

        # バウンディングボックスを描画
        cv2.rectangle(frame, (x, y), (x2, y2), (0, 255, 0), 2)

        # 棒グラフ表示の最適化: 一度の変換で全処理
        bar_width = 150
        bar_height = 15
        start_x = x + w + 10
        start_y = y

        # 5感情の棒グラフ描画
        for i, score in enumerate(avg_emotions):
            # 棒グラフの背景
            cv2.rectangle(frame, (start_x, start_y + i*25), (start_x + bar_width, start_y + i*25 + bar_height), (50, 50, 50), -1)

            # 棒グラフの値
            bar_length = int(bar_width * score)
            color = (0, int(255*score), int(255*(1-score)))
            cv2.rectangle(frame, (start_x, start_y + i*25), (start_x + bar_length, start_y + i*25 + bar_height), color, -1)

        # 8感情の棒グラフ描画
        start_y_8 = start_y + len(TARGET_EMOTIONS) * 25 + 20

        for i, score in enumerate(original_emotions):
            # 棒グラフの背景
            cv2.rectangle(frame, (start_x, start_y_8 + i*25), (start_x + bar_width, start_y_8 + i*25 + bar_height), (50, 50, 50), -1)

            # 棒グラフの値
            bar_length = int(bar_width * score)
            color = (int(255*(1-score)), 0, int(255*score))
            cv2.rectangle(frame, (start_x, start_y_8 + i*25), (start_x + bar_length, start_y_8 + i*25 + bar_height), color, -1)

        # 日本語ラベル表示(最適化: 一度の変換で全処理)
        img_pil = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
        draw = ImageDraw.Draw(img_pil)

        # 5感情のラベル
        for i, (emotion, score) in enumerate(zip(TARGET_EMOTIONS, avg_emotions)):
            text = f"{emotion}: {score*100:.1f}%"
            draw.text((start_x + bar_width + 5, start_y + i*25 - 2), text, font=font, fill=(255, 255, 255))

        # 8感情のラベル
        for i, (emotion, score) in enumerate(zip(ORIGINAL_EMOTIONS, original_emotions)):
            text = f"{emotion}: {score*100:.1f}%"
            draw.text((start_x + bar_width + 5, start_y_8 + i*25 - 2), text, font=font, fill=(255, 255, 255))

        frame = cv2.cvtColor(np.array(img_pil), cv2.COLOR_RGB2BGR)

        # 5秒に1回、5感情と8感情をprint表示
        current_time = time.time()
        if current_time - last_print_time >= 5.0:
            print("=== 5感情の詳細 ===")
            for emotion, score in zip(TARGET_EMOTIONS, avg_emotions):
                print(f"{emotion}: {score*100:.1f}%")
            print("=== 8感情の詳細 ===")
            for emotion, score in zip(ORIGINAL_EMOTIONS, original_emotions):
                print(f"{emotion}: {score*100:.1f}%")
            print("==================")
            last_print_time = current_time

    cv2.imshow('感情認識', frame)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

プログラムを終了するには、映像ウィンドウを選択した状態で q キーを押す。