DeepFace のインストール,DeepFace を用いた年齢・性別・表情推定プログラム,表情推定プログラム(DeepFace,Python,TensorFlow を使用)(Windows 上)
【概要】
Windows 環境でのDeepFaceのインストールと,DeepFaceを使用した顔画像解析プログラムを示しています.まず,DeepFaceのインストールとテスト実行方法が示しています.次に,パソコン接続のカメラを使用したリアルタイムの年齢・性別・表情推定プログラムが示しています.このプログラムでは,カメラから取得した顔画像に対してDeepFaceを用いて解析を行い,結果を画面上に表示します.選択された画像ファイルについて,年齢・性別・表情推定を行うプログラムを示しています.複数の画像ファイルを選択することで一括処理が可能です.さらに,DeepFaceを使用した顔認識プログラムも示しています.このプログラムでは,指定された画像に最も似ている顔画像をディレクトリ内の画像ファイルから検索し,入力画像と上位3つの結果を表示します.


【目次】
前準備
Python 3.10,Git,7-Zip のインストール(Windows 上)
Pythonは,プログラミング言語の1つ. Gitは,分散型のバージョン管理システム. 7-Zipは,ファイル圧縮・展開(解凍)ツール.
【手順】
- Windows で,コマンドプロンプトを管理者権限で起動する(例:Windowsキーを押し,「cmd」と入力し,「管理者として実行」を選択)
次のコマンドを実行
次のコマンドは,Python ランチャーとPython 3.10とGitと7-Zipをインストールし,Gitと7-Zipにパスを通すものである.
次のコマンドでインストールされるGitは 「git for Windows」と呼ばれるものであり, Git,MinGW などから構成されている.
winget install --scope machine Python.Launcher winget install --scope machine Python.Python.3.10 winget install --scope machine Git.Git powershell -command "$oldpath = [System.Environment]::GetEnvironmentVariable(\"Path\", \"Machine\"); $oldpath += \";c:\Program Files\Git\cmd\"; [System.Environment]::SetEnvironmentVariable(\"Path\", $oldpath, \"Machine\")" winget install --scope machine 7zip.7zip powershell -command "$oldpath = [System.Environment]::GetEnvironmentVariable(\"Path\", \"Machine\"); $oldpath += \";c:\Program Files\7-Zip\"; [System.Environment]::SetEnvironmentVariable(\"Path\", $oldpath, \"Machine\")"
【関連する外部ページ】
- Python の公式ページ: https://www.python.org/
- Git の公式ページ: https://git-scm.com/
- 7-Zip の公式ページ: https://7-zip.opensource.jp/
【サイト内の関連ページ】
【関連項目】 Python, Git バージョン管理システム, Git の利用, 7-Zip
Build Tools for Visual Studio 2022 (ビルドツール for Visual Studio 2022)または Visual Studio 2022 のインストール(Windows 上)
【インストールの判断】 Build Tools for Visual Studio は,開発ツールセットである. Visual Studio は統合開発環境であり,いくつかの種類があり,Build Tools for Visual Studioの機能を含むか連携して使用するものである.インストールは以下の基準で判断してください:
- Build Tools for Visual Studio の機能のみが必要な場合
- Visual Studio の機能が必要である,あるいは,よく分からない場合
Visual Studio 2022 をインストールする際に,「C++ によるデスクトップ開発」を選択することで, Build Tools for Visual Studio 2022 の機能も一緒にインストールされる.
不明な点がある場合は,Visual Studio 全体をインストール を行う方が良い.
Build Tools for Visual Studio 2022 のインストール(Windows 上)
- Windows で,コマンドプロンプトを管理者権限で起動する(例:Windowsキーを押し,「cmd」と入力し,「管理者として実行」を選択)
次のコマンドを実行
次のコマンドは,Build Tools for Visual Studio 2022と VC2015 再配布可能パッケージをインストールするものである.
- Build Tools for Visual Studio 2022 での C++ によるデスクトップ開発,CLI,ATL,MFC のインストール(Windows 上)
- Visual Studio Installer の起動
起動方法: スタートメニューの「Visual Studio Installer」を選ぶ.
- Visual Studio Build Tools 2022 で「変更」を選ぶ.
- 「C++ によるデスクトップ開発」をクリック.そして,画面右側の「インストール」の詳細で「v143 ビルドツール用 C++/CLI サポート(最新)」,「ATL」,「MFC」をチェックする.その後,「変更」をクリック.
- Visual Studio Installer の起動
Visual Studio のインストール(Windows 上)
- Windows で,コマンドプロンプトを管理者権限で起動する(例:Windowsキーを押し,「cmd」と入力し,「管理者として実行」を選択)
次のコマンドを実行
- コマンドプロンプトを管理者権限で起動する(例:Windowsキーを押し,「cmd」と入力し,「管理者として実行」を選択)
- インストールコマンドの実行
winget install Microsoft.VisualStudio.2022.Community --scope machine --override "--add Microsoft.VisualStudio.Workload.NativeDesktop Microsoft.VisualStudio.ComponentGroup.NativeDesktop.Core Microsoft.VisualStudio.Component.VC.CLI.Support Microsoft.VisualStudio.Component.CoreEditor Microsoft.VisualStudio.Component.NuGet Microsoft.VisualStudio.Component.Roslyn.Compiler Microsoft.VisualStudio.Component.TextTemplating Microsoft.VisualStudio.Component.Windows.SDK.Latest Microsoft.VisualStudio.Component.VC.Tools.x86.x64 Microsoft.VisualStudio.Component.VC.ATL Microsoft.VisualStudio.Component.VC.ATLMFC" winget install Microsoft.VisualStudio.2022.Community --scope machine Microsoft.VCRedist.2015+.x64
インストールされるコンポーネントの説明:
NativeDesktop
:C++によるデスクトップアプリケーション開発のためのワークロード一式NativeDesktop.Core
:C++デスクトップ開発に必要な基本コンポーネント群VC.CLI.Support
:マネージドコードとネイティブコードの統合開発を可能にするC++/CLIサポートCoreEditor
:コード編集,デバッグ,検索などの基本機能を提供するVisual StudioのコアエディタNuGet
:.NETライブラリの依存関係を管理するパッケージ管理システムWindows.SDK.Latest
:Windows 向けアプリケーション開発用SDK(Software Development Kit)VC.Tools.x86.x64
:32ビット及び64ビット向けC++コンパイラとビルドツールVC.ATL
:Windowsコンポーネント開発用のActive Template LibraryVC.ATLMFC
:デスクトップアプリケーション開発用のMicrosoft Foundation Class Library
システム要件と注意事項:
- 管理者権限でのインストールが必須
- 必要ディスク容量:10GB以上
- 推奨メモリ:8GB以上のRAM
- インストール過程でシステムの再起動が要求される可能性がある
- 安定したインターネット接続環境が必要
追加のコンポーネントが必要な場合は,Visual Studio Installerを使用して個別にインストールすることが可能である.
- インストール完了の確認
winget list Microsoft.VisualStudio.2022.Community
トラブルシューティング:
インストール失敗時は,以下のログファイルを確認:
%TEMP%\dd_setup_<timestamp>.log %TEMP%\dd_bootstrapper_<timestamp>.log
- Visual Studio での C++ によるデスクトップ開発,CLI のインストール(Windows 上)
- Visual Studio Installer の起動
起動方法: スタートメニューの「Visual Studio Installer」を選ぶ.
- Visual Studio Community 2022 で「変更」を選ぶ.
- 「C++ によるデスクトップ開発」をチェック.そして,画面右側の「インストール」の詳細で「v143 ビルドツール用 C++/CLI サポート(最新)」をチェックする.その後,「インストール」をクリック.
- Visual Studio Installer の起動
NVIDIA ドライバのインストール(Windows 上)
NVIDIA ドライバ
NVIDIA ドライバは,NVIDIA製GPUを動作させるための重要なソフトウェアである.このドライバをインストールすることにより,GPUの性能を引き出すことができ,グラフィックス関連のアプリ,AI関連のアプリの高速化が期待できる.
ドライバはNVIDIA公式サイトである https://www.nvidia.co.jp/Download/index.aspx?lang=jp からダウンロードできる.このサイトからダウンロードするときには,グラフィックスカードとオペレーティングシステムを選択する. なお,NVIDIA GeForce Experiance を用いてインストールすることも可能である.
【サイト内の関連ページ】
- NVIDIA グラフィックス・ボードの確認
Windows で,NVIDIA グラフィックス・ボードの種類を調べたいときは, 次のコマンドを実行することにより調べることができる.
wmic path win32_VideoController get name
- NVIDIA ドライバのダウンロード
NVIDIA ドライバは,以下の NVIDIA 公式サイトからダウンロードできる.
- ダウンロードの際には,使用しているグラフィックス・ボードの型番とオペレーティングシステムを選択する.
NVIDIA CUDA ツールキット 11.8 のインストール(Windows 上)
NVIDIA CUDA ツールキットのインストール時の注意点
NVIDIAのGPUを使用して並列計算を行うためのツールセット
主な機能: GPU を利用した並列処理,GPU のメモリ管理,C++をベースとした拡張言語とAPIとライブラリ
【NVIDIA CUDA ツールキットの動作に必要なもの】
- CUDA対応のNVIDIA GPUが必要.
そのために,NVIDIA グラフィックス・ボードを確認する. Windows で,NVIDIA グラフィックス・ボードの種類を調べたいときは, 次のコマンドを実行することにより調べることができる.
wmic path win32_VideoController get name
- NVIDIA ドライバのダウンロードとインストール
NVIDIA ドライバは,以下の NVIDIA 公式サイトからダウンロードできる. ダウンロードの際には,使用しているグラフィックス・ボードの型番とオペレーティングシステムを選択する.
- Windows では,インストール前に,Build Tools for Visual Studio もしくは Visual Studio をインストールしておくことが必要である.
【Windows でインストールするときの注意点】
- Windows では, NVIDIA CUDA ツールキットのインストール中は,なるべく他のウインドウはすべて閉じておくこと.
- NVIDIA CUDA ツールキットのインストールが終わったら,ユーザ環境変数 TEMP の設定を行う.
Windows のユーザ名が日本語のとき,nvcc がうまく動作しないエラーを回避するためである.
ユーザ環境変数 TEMP に「C:\TEMP」を設定するために, コマンドプロンプトで,次のコマンドを実行する.
mkdir C:\TEMP powershell -command "[System.Environment]::SetEnvironmentVariable(\"TEMP\", \"C:\TEMP\", \"User\")"
【関連する外部ページ】
- NVIDIA CUDA ツールキットのアーカイブの公式ページ: https://developer.nvidia.com/cuda-toolkit-archive
- NVIDIA CUDA ツールキット の公式のドキュメント: https://docs.nvidia.com/cuda/cuda-installation-guide-linux/index.html
- NVIDIA CUDA ツールキットのインストールに関する,NVIDIA CUDA クイックスタートガイドの公式ページ: https://docs.nvidia.com/cuda/cuda-quick-start-guide/index.html
【関連項目】 NVIDIA CUDA ツールキット, NVIDIA CUDA ツールキット 12.5 のインストール(Windows 上), NVIDIA CUDA ツールキット 11.8 のインストール(Windows 上)
- Windows では,NVIDIA CUDA ツールキットのインストール中は,なるべく他のウインドウはすべて閉じておくこと.
- Windows で,コマンドプロンプトを管理者権限で起動する(例:Windowsキーを押し,「cmd」と入力し,「管理者として実行」を選択)
- 次のコマンドを実行
次のコマンドは,NVIDIA GeForce Experience,NVIDIA CUDA ツールキット 11.8 をインストールするものである.
wmic path win32_VideoController get name winget install --scope machine Nvidia.CUDA --version 11.8 powershell -command "[System.Environment]::SetEnvironmentVariable(\"CUDA_HOME\", \"C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.8\", \"Machine\")"
- NVIDIA CUDA ツールキットのインストールが終わったら,ユーザ環境変数 TEMP の設定を行う.
Windows のユーザ名が日本語のとき,nvcc がうまく動作しないエラーを回避するためである.
ユーザ環境変数 TEMP に「C:\TEMP」を設定するために, コマンドプロンプトで,次のコマンドを実行する.
mkdir C:\TEMP powershell -command "[System.Environment]::SetEnvironmentVariable(\"TEMP\", \"C:\TEMP\", \"User\")"
NVIDIA cuDNN 8.9.7 のインストール(Windows 上)
NVIDIA cuDNN
NVIDIA cuDNN は,NVIDIA CUDA ツールキット上で動作する、高性能なディープラーニング用ライブラリです.畳み込みニューラルネットワーク (CNN) やリカレントニューラルネットワーク (RNN) など,さまざまなディープラーニングモデルのトレーニングと推論を高速化します.
【cuDNN利用時の注意点: zlibwapi.dll エラー】
Windows環境でcuDNNを利用するアプリケーションを実行した際に、「Could not locate zlibwapi.dll. Please make sure it is in your library path!」というエラーが表示されることがあります。これは、cuDNNの一部の機能が圧縮ライブラリである zlib
に依存しているためです。このエラーが発生した場合は、後述する手順で ZLIB DLL をインストールする必要があります。
【関連する外部ページ】
- NVIDIA cuDNN の公式ページ(ダウンロードにはDeveloper Programへの登録が必要): https://developer.nvidia.com/cudnn
NVIDIA cuDNN のインストール(Windows 上)の概要
- NVIDIA Developer Program メンバーシップへの加入: cuDNNのダウンロードには無料のメンバーシップ登録が必要です。
NVIDIA Developer Program の公式ページ: https://developer.nvidia.com/developer-program
- 互換バージョンの選択とダウンロード: インストール済みのCUDAツールキットのバージョン (今回は11.x) に適合するcuDNNのバージョン (今回はv8.9.7) を選択し、Windows用のzipファイルをダウンロードします。
- ファイルの展開と配置: ダウンロードしたzipファイルを展開(解凍)し、中のファイル(
bin
,include
,lib
フォルダ内)を、CUDAツールキットのインストールディレクトリにコピーします。 - (オプション) 環境変数の設定: 必要に応じてシステム環境変数
CUDNN_PATH
を設定します。 - (必要に応じて) ZLIB DLL のインストール:
zlibwapi.dll
が見つからないエラーが発生する場合にインストールします。 - 動作確認: cuDNNライブラリ (
cudnn64_*.dll
) にパスが通っているか確認します。
zlib のインストール(Windows 上)
- Windows で,コマンドプロンプトを管理者権限で起動する(例:Windowsキーを押し,「cmd」と入力し,「管理者として実行」を選択)
- 次のコマンドを実行
次のコマンドは,zlibをインストールし,パスを通すものである.
cd /d c:%HOMEPATH% rmdir /s /q zlib git clone https://github.com/madler/zlib cd zlib del CMakeCache.txt rmdir /s /q CMakeFiles\ cmake . -G "Visual Studio 17 2022" -A x64 -T host=x64 -DCMAKE_INSTALL_PREFIX=c:/zlib cmake --build . --config RELEASE --target INSTALL powershell -command "$oldpath = [System.Environment]::GetEnvironmentVariable(\"Path\", \"Machine\"); $oldpath += \";c:\zlib\bin\"; [System.Environment]::SetEnvironmentVariable(\"Path\", $oldpath, \"Machine\")" powershell -command "[System.Environment]::SetEnvironmentVariable(\"ZLIB_HOME\", \"C:\zlib\", \"Machine\")"
【関連する外部ページ】
- zlib の公式ページ: https://www.zlib.net/
【関連項目】 zlib
NVIDIA cuDNN 8.9.7 のインストール(Windows 上)
- NVIDIA cuDNN のウェブページを開く
- ダウンロードしたいので,cuDNNのところにある「Download cuDNN」をクリック.
- cuDNN Downloads のページで「Archive of Previous Releases」をクリック
- 「cuDNN 8.x - 1.x」をクリック
- ダウンロードしたいバージョンを選ぶ
ここでは「NVIDIA cuDNN v8.9.7 for CUDA 11.x」を選んでいる.
このとき,画面の「for CUDA ...」のところを確認し,使用するNVIDIA CUDA のバージョンに合うものを選ぶこと.
- Windows にインストールするので Windows 版を選ぶ
- NVIDIA Developer Program メンバーシップに入る
NVIDIA cuDNN のダウンロードのため.
「Join now」をクリック.その後,画面の指示に従う. 利用者本人が,電子メールアドレス,表示名,パスワード,生年月日を登録.利用条件等に合意.
- ログインする
- 調査の画面が出たときは,調査に応じる
- ライセンス条項の確認
- ダウンロードが始まる.
- ダウンロードした .zip ファイルを展開(解凍)する.
その中のサブディレクトリを確認しておく.
- NVIDIA CUDA ツールキットをインストールしたディレクトリを確認する.「C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.8」のようになっている.
- 確認したら,
さきほど展開してできたすべてのファイルとディレクトリを,NVIDIA CUDA ツールキットをインストールしたディレクトリにコピーする
- パスが通っていることを確認.
次の操作により,cudnn64_8.dll にパスが通っていることを確認する.
Windows のコマンドプロンプトを開き,次のコマンドを実行する.エラーメッセージが出ないことを確認.
where cudnn64_8.dll
- Windows の システム環境変数 CUDNN_PATH の設定を行う.
Windows では,
コマンドプロンプトを管理者として開き,
次のコマンドを実行することにより,
システム環境変数 CUDNN_PATH の設定を行うことができる.
コマンドプロンプトを管理者として実行: 別ページ »で説明
powershell -command "[System.Environment]::SetEnvironmentVariable(\"CUDNN_PATH\", \"C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.8\", \"Machine\")"
TensorFlow 2.10.1 のインストール(Windows 上)
- Windows で,コマンドプロンプトを管理者権限で起動する(例:Windowsキーを押し,「cmd」と入力し,「管理者として実行」を選択)
- TensorFlow 2.10.1 のインストール(Windows 上)
次のコマンドを実行することにより,TensorFlow 2.10.1 および関連パッケージ(tf_slim,tensorflow_datasets,tensorflow-hub,Keras,keras-tuner,keras-visualizer)がインストール(インストール済みのときは最新版に更新)される. そして,Pythonパッケージ(Pillow, pydot, matplotlib, seaborn, pandas, scipy, scikit-learn, scikit-learn-intelex, opencv-python, opencv-contrib-python)がインストール(インストール済みのときは最新版に更新)される.
python -m pip uninstall -y protobuf tensorflow tensorflow-cpu tensorflow-gpu tensorflow-intel tensorflow-text tensorflow-estimator tf-models-official tf_slim tensorflow_datasets tensorflow-hub keras keras-tuner keras-visualizer python -m pip install -U protobuf tensorflow==2.10.1 tf_slim tensorflow_datasets==4.8.3 tensorflow-hub tf-keras keras keras_cv keras-tuner keras-visualizer python -m pip install git+https://github.com/tensorflow/docs python -m pip install git+https://github.com/tensorflow/examples.git python -m pip install git+https://www.github.com/keras-team/keras-contrib.git python -m pip install -U pillow pydot matplotlib seaborn pandas scipy scikit-learn scikit-learn-intelex opencv-python opencv-contrib-python
DeepFace のインストールとテスト実行(Windows 上)
- Windows で,コマンドプロンプトを管理者権限で起動する(例:Windowsキーを押し,「cmd」と入力し,「管理者として実行」を選択)
- DeepFace のインストール
* 「 python -m pip install ...」は,Python パッケージをインストールするためのコマンド.
python -m pip install -U deepface
- ソースコード等のダウンロード,DeepFace のインストール
cd /d c:%HOMEPATH% rmdir /s /q deepface git clone --recursive https://github.com/serengil/deepface cd deepface python -m pip install -v -e .
- 確認のため,顔認識のコマンドを実行してみる.
cd /d c:%HOMEPATH% deepface find deepface\tests\dataset\img38.jpg deepface\tests\dataset
- 確認のため,表情や性別や年齢の推定のコマンドを実行してみる.
cd /d c:%HOMEPATH% deepface analyze -d retinaface deepface\tests\dataset\img38.jpg
顔画像からの表情,性別,年齢の推定(DeepFace を使用)
パソコン接続のカメラを使用
- Windows で,コマンドプロンプトを実行
- エディタを起動
cd /d c:%HOMEPATH% notepad tfdeepface.py
- エディタで,次のプログラムを保存
このプログラムは、カメラからリアルタイムで顔画像を取得し、DeepFaceライブラリを用いて年齢、性別、表情の推定を行います。推定結果は画面上に表示され、フレームレートも計算されます。GPUが利用可能な場合はGPUを使用します.'q'キーで終了、'p'キーで一時停止/再開ができます。
【プログラムの説明】
- set_gpu_config() 関数で、利用可能なGPUを設定し、GPUが見つからない場合はCPUを使用することを示します。
- resize_image() 関数で、入力画像をリサイズします(縦横比を維持)。
- display_results() 関数で、推定結果を入力画像上に描画します。
- update_fps() 関数で、FPSを計算し更新します。
- analyze_camera_frames() 関数で、以下の処理を行います:
カメラから画像を取得、入力画像をリサイズ、DeepFaceを使用して年齢、性別、表情を推定、推定結果を表示、FPSを更新、'q'キーで終了、'p'キーで一時停止/再開
- main() 関数で、GPUの設定を行い、analyze_camera_frames() 関数を呼び出します。
【使用法】
- プログラムを実行すると、カメラを使い、リアルタイムで顔の検出と属性(年齢、性別、表情)の推定が始まります。
- 画面上には、検出された顔の属性(年齢、性別、表情)、推定にかかった時間、現在のFPSが表示されます。
- プログラムの実行中に以下のキー操作ができます:
- 'q' キー:プログラムを終了します。
- 'p' キー:推定処理を一時停止/再開します。一時停止中は、画面が静止し、最後に処理されたフレームが表示されます。
- プログラムを終了するには、'q' キーを押すか、ウィンドウを閉じてください。
import tensorflow as tf from deepface import DeepFace import cv2 import time import numpy as np # ==== 設定 ==== CONFIG = { 'ACTIONS': ['age', 'gender', 'emotion'], 'OUTPUT_SIZE': (400, 400) } def set_gpu_config(): """ GPUの設定と確認を行う関数 """ physical_devices = tf.config.list_physical_devices('GPU') if len(physical_devices) > 0: print("GPU available:", physical_devices) for device in physical_devices: tf.config.experimental.set_memory_growth(device, True) else: print("No GPU found. Running on CPU.") def resize_image(img, size): """ 画像をリサイズする関数(縦横比を維持) """ height, width, _ = img.shape aspect_ratio = width / height target_width, target_height = size if aspect_ratio > 1: target_height = int(target_width / aspect_ratio) else: target_width = int(target_height * aspect_ratio) return cv2.resize(img, (target_width, target_height), interpolation=cv2.INTER_AREA) def display_results(frame, obj, prediction_time, fps): """ 推定結果を表示する関数 """ # 入力画像に推定結果を描画 cv2.putText(frame, f"Age: {obj['age']}", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2) cv2.putText(frame, f"Gender: {obj['gender']}", (10, 70), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2) cv2.putText(frame, f"Emotion: {obj['dominant_emotion']}", (10, 110), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2) cv2.putText(frame, f"Time: {prediction_time:.2f}s", (10, 150), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2) cv2.putText(frame, f"FPS: {fps:.2f}", (10, 190), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2) def update_fps(fps_buffer, prediction_time): """ FPSを更新する関数 """ fps_buffer.append(prediction_time) if len(fps_buffer) > 10: fps_buffer.pop(0) fps = len(fps_buffer) / sum(fps_buffer) return fps def analyze_camera_frames(): """ カメラからのフレームを取得し、年齢、性別、表情の推定を行う関数 """ cap = cv2.VideoCapture(0) fps_buffer = [] paused = False while cap.isOpened(): if not paused: ret, frame = cap.read() if not ret: break # 入力画像をリサイズ(縦横比を維持) frame = resize_image(frame, CONFIG['OUTPUT_SIZE']) start_time = time.perf_counter() obj = DeepFace.analyze(img_path=frame, actions=CONFIG['ACTIONS'], enforce_detection=False) if isinstance(obj, list) and len(obj) > 0: obj = obj[0] # リストの最初の要素を取得 prediction_time = time.perf_counter() - start_time fps = update_fps(fps_buffer, prediction_time) display_results(frame, obj, prediction_time, fps) cv2.imshow("Age, Gender, Emotion Estimation", frame) key = cv2.waitKey(1) & 0xFF if key == ord('q'): break elif key == ord('p'): paused = not paused cap.release() cv2.destroyAllWindows() def main(): set_gpu_config() analyze_camera_frames() if __name__ == "__main__": main()
- Python プログラムの実行
Python プログラムの実行
- Windows では python (Python ランチャーは py)
- Ubuntu では python3
【サイト内の関連ページ】 Python のまとめ: 別ページ »
プログラムを tfdeepface.pyのようなファイル名で保存したので, 「python tfdeepface.py」のようなコマンドで行う.
python tfdeepface.py
- 結果の確認
終了は q キー
画像ファイルを選択
- Windows で,コマンドプロンプトを実行
- エディタを起動
cd /d c:%HOMEPATH% notepad tfdeepfaceimg.py
- エディタで,次のプログラムを保存
このプログラムは、OpenCVとDeepFaceを用いて、選択した画像から年齢、性別、感情を推定し、結果を画像に表示します。
【プログラムの説明】
- GPUの設定、画像ファイルの選択、画像のリサイズを行う関数を定義します。
- DeepFaceを使用して年齢、性別、感情を推定し、結果を表示する関数を定義します。
- 推定結果を画像に描画する処理を行います。
- メイン関数で、選択した画像に対して処理を実行し、結果を表示します。
【使用法】
- プログラムを実行する
- 画像ファイルを選択する
ファイル選択ダイアログが表示されるので、画像ファイルを選択します。 複数の画像を選択する場合は、Ctrlキー(Windows の場合)またはCommandキー(Macの場合)を押しながらクリックします。
- 結果を確認します。
- 選択した画像ごとに、推定結果がコンソールに表示され、結果が描画された画像
- が表示されます。
- 結果が表示されたウィンドウは、任意のキーを押すと閉じられます。
import tensorflow as tf from deepface import DeepFace import pandas as pd import os import cv2 import tkinter as tk from tkinter import filedialog # ==== 設定 ==== CONFIG = { 'ACTIONS': ['age', 'gender', 'emotion'], 'OUTPUT_SIZE': (400, 400) } def set_gpu_config(): """ GPUの設定と確認を行う関数 """ physical_devices = tf.config.list_physical_devices('GPU') if len(physical_devices) > 0: print("GPU available:", physical_devices) for device in physical_devices: tf.config.experimental.set_memory_growth(device, True) else: print("No GPU found. Running on CPU.") def select_files(): """ 画像ファイルを選択する関数 """ root = tk.Tk() root.withdraw() image_paths = filedialog.askopenfilenames() return image_paths def resize_image(img, size): """ 画像をリサイズする関数(縦横比を維持) """ height, width, _ = img.shape aspect_ratio = width / height target_width, target_height = size if aspect_ratio > 1: target_height = int(target_width / aspect_ratio) else: target_width = int(target_height * aspect_ratio) return cv2.resize(img, (target_width, target_height), interpolation=cv2.INTER_AREA) def display_results(obj, img_path): """ 推定結果を表示する関数 """ print(f"Image: {img_path}") print(f"Age: {obj['age']}") print(f"Gender: {obj['gender']}") print(f"Emotion: {obj['dominant_emotion']}") print("\n") def process_image(img_path): """ 画像処理と年齢、性別、表情の推定を行う関数 """ img = cv2.imread(img_path) if img is None: print(f"Failed to read image: {img_path}. Skipping.") return None # 入力画像をリサイズ(縦横比を維持) img = resize_image(img, CONFIG['OUTPUT_SIZE']) print(f"Image dimensions for {img_path}: Width = {img.shape[1]}, Height = {img.shape[0]}") obj = DeepFace.analyze(img_path=img_path, actions=CONFIG['ACTIONS']) if isinstance(obj, list) and len(obj) > 0: obj = obj[0] # リストの最初の要素を取得 display_results(obj, img_path) # 入力画像に推定結果を描画 cv2.putText(img, f"Age: {obj['age']}", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2) cv2.putText(img, f"Gender: {obj['gender']}", (10, 70), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2) cv2.putText(img, f"Emotion: {obj['dominant_emotion']}", (10, 110), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2) return img def main(): set_gpu_config() img_paths = select_files() for img_path in img_paths: if not os.path.isfile(img_path): print(f"Image file not found: {img_path}. Skipping.") continue img = process_image(img_path) if img is not None: cv2.imshow("Age, Gender, Emotion Estimation", img) cv2.waitKey(0) cv2.destroyAllWindows() if __name__ == "__main__": main()
- Python プログラムの実行
Python プログラムの実行
- Windows では python (Python ランチャーは py)
- Ubuntu では python3
【サイト内の関連ページ】 Python のまとめ: 別ページ »
プログラムを tfdeepfaceimg.pyのようなファイル名で保存したので, 「python tfdeepfaceimg.py」のようなコマンドで行う.
python tfdeepfaceimg.py
- ファイルダイアログが開くので,画像ファイルを選ぶ.
このとき,画像ファイルを複数選ぶことができる.
- 結果の確認
顔認識の実行(DeepFace を使用)
- Windows で,コマンドプロンプトを実行
- エディタを起動
cd /d c:%HOMEPATH% notepad tfdeepfacerecog.py
- エディタで,次のプログラムを保存
次のプログラムは,DeepFaceを使用して顔認識を行い,入力画像に最も似ている顔画像を指定されたディレクトリ内の画像ファイルから検索し,入力画像と上位3つの結果を表示するプログラムです.
プログラムの主な流れは以下の通りです.
- 必要なライブラリとモジュールをインポートします.
- 設定値(モデル名,距離メトリック,入力サイズ,出力サイズ,結果ウィンドウ名)を設定します.
- GPUの設定と確認を行います.
- 選択されたファルダについて,画像ファイルを1枚ずつ処理します.
画像を読み込み,縦横比を維持しながら入力サイズにリサイズします. 顔認識を実行します.結果を表示します.あわせて, 結果の上位3つの画像を読み込み,縦横比を維持しながら出力サイズにリサイズします. リサイズされた結果の画像を表示します.
プログラムの使い方
- プログラムを実行する
- 顔認識したい画像ファイルを選択する
- 顔画像の入ったフォルダを選択する
- 結果ウィンドウに入力画像と最も似ている上位3つの顔画像が表示される.画面に類似度が高い顔画像のファイル名が表示される.
import tensorflow as tf from deepface import DeepFace import cv2 import tkinter as tk from tkinter import filedialog import os import numpy as np # ==== 設定 ==== CONFIG = { 'MODEL_NAME': 'VGG-Face', 'DISTANCE_METRIC': 'cosine', 'INPUT_SIZE': (224, 224), 'OUTPUT_SIZE': (400, 400), 'RESULT_WINDOW_NAME': 'Face Recognition Results' } def select_files(): """ 画像ファイルを選択する関数 """ try: if 'google.colab' in str(get_ipython()): from google.colab import files uploaded = files.upload() image_paths = list(uploaded.keys()) else: root = tk.Tk() root.withdraw() image_paths = filedialog.askopenfilenames() except NameError: root = tk.Tk() root.withdraw() image_paths = filedialog.askopenfilenames() return image_paths def select_folder(): """ フォルダを選択する関数 """ root = tk.Tk() root.withdraw() folder_path = filedialog.askdirectory() return folder_path def set_gpu_config(): """ GPUの設定と確認を行う関数 """ physical_devices = tf.config.list_physical_devices('GPU') if len(physical_devices) > 0: print("GPU available:", physical_devices) for device in physical_devices: tf.config.experimental.set_memory_growth(device, True) else: print("No GPU found. Running on CPU.") def perform_face_recognition(img_path, db_path): """ 顔認識を実行する関数 """ try: print(img_path, db_path) df = DeepFace.find(img_path=img_path, db_path=db_path, model_name=CONFIG['MODEL_NAME'], distance_metric=CONFIG['DISTANCE_METRIC'], detector_backend='skip') if isinstance(df, list) and len(df) > 0: df = df[0] df['img_path'] = img_path # img_pathをDataFrameに追加 return df except Exception as e: print(f"Error during face recognition for {img_path}: {str(e)}") return None def process_image(img_path, db_path): """ 画像処理と顔認識を行う関数 """ img = cv2.imread(img_path) if img is None: print(f"Failed to read image: {img_path}. Skipping.") return None # 入力画像をリサイズ(縦横比を維持) img = resize_image(img, CONFIG['INPUT_SIZE']) print(f"Image dimensions for {img_path}: Width = {img.shape[1]}, Height = {img.shape[0]}") results = perform_face_recognition(img_path, db_path) if results is None or results.empty: return None distance_column = get_distance_column(results) if distance_column is None: print(f"No distance column found for {img_path}. Skipping.") return None display_results(results, distance_column, img_path) # img_pathを渡す # 入力画像をリサイズ(縦横比を維持) input_img = resize_image(img.copy(), CONFIG['OUTPUT_SIZE']) # 入力画像にファイル名を描画 cv2.putText(input_img, f"Input: {os.path.basename(img_path)}", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2) result_images = process_result_images(results, distance_column) padded_images = pad_images([input_img] + result_images) return padded_images def resize_image(img, size): """ 画像をリサイズする関数(縦横比を維持) """ height, width, _ = img.shape aspect_ratio = width / height target_width, target_height = size if aspect_ratio > 1: target_height = int(target_width / aspect_ratio) else: target_width = int(target_height * aspect_ratio) return cv2.resize(img, (target_width, target_height), interpolation=cv2.INTER_AREA) def get_distance_column(results): """ 距離メトリックに対応する列名を取得する関数 """ distance_columns = [col for col in results.columns if 'distance' in col] if len(distance_columns) > 0: return distance_columns[0] else: return None def display_results(results, distance_column, img_path): """ 顔認識結果を表示する関数 """ for _, row in results.iterrows(): target_img_path = row.identity distance = row[distance_column] print(f"Source Image: {img_path}") # img_pathを直接使用 print(f"Target Image: {target_img_path}") print(f"Distance: {distance}") # facial_areaが存在する場合のみ表示 if 'facial_area' in row: facial_area = row.facial_area print(f"Bounding Box: {facial_area}") print("\n") def process_result_images(results, distance_column): """ 結果の画像を処理する関数 """ result_images = [] for i, (_, row) in enumerate(results.sort_values(by=distance_column).head(3).iterrows(), start=1): identity = row.identity result_img = cv2.imread(identity) if result_img is None: print(f"Failed to read result image: {identity}. Skipping.") continue # 結果の画像をリサイズ(縦横比を維持) result_img = resize_image(result_img, CONFIG['OUTPUT_SIZE']) # 結果の画像にファイル名と距離を描画 cv2.putText(result_img, f"Result {i}: {os.path.basename(identity)}", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2) cv2.putText(result_img, f"Distance: {row[distance_column]:.4f}", (10, 70), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2) result_images.append(result_img) return result_images def pad_images(images): """ 画像の高さを揃えるために、上下に黒い余白を追加する関数 """ max_height = max(img.shape[0] for img in images) padded_images = [] for img in images: height, width, _ = img.shape pad_height = max_height - height pad_top = pad_height // 2 pad_bottom = pad_height - pad_top padded_img = cv2.copyMakeBorder(img, pad_top, pad_bottom, 0, 0, cv2.BORDER_CONSTANT, value=[0, 0, 0]) padded_images.append(padded_img) return padded_images def display_results_window(padded_images): """ 結果の画像を表示するウィンドウを作成する関数 """ if len(padded_images) <= 1: return line_width = 10 max_height = padded_images[0].shape[0] line_img = np.zeros((max_height, line_width, 3), dtype=np.uint8) line_img[:] = [255, 255, 255] # 白色の線 output_img = np.concatenate([padded_images[0], line_img] + padded_images[1:], axis=1) cv2.imshow(CONFIG['RESULT_WINDOW_NAME'], output_img) cv2.waitKey(0) cv2.destroyAllWindows() def main(): set_gpu_config() img_paths = select_files() db_path = select_folder() if not db_path: print("No database folder selected. Exiting.") return for img_path in img_paths: if not os.path.isfile(img_path): print(f"Image file not found: {img_path}. Skipping.") continue padded_images = process_image(img_path, db_path) if padded_images is not None: display_results_window(padded_images) if __name__ == "__main__": main()
- Python プログラムの実行
Python プログラムの実行
- Windows では python (Python ランチャーは py)
- Ubuntu では python3
【サイト内の関連ページ】 Python のまとめ: 別ページ »
プログラムを tfdeepface.pyのようなファイル名で保存したので, 「python tfdeepface.py」のようなコマンドで行う.
python tfdeepface.py
- ファイルダイアログが開くので,画像ファイルを選ぶ.
このとき,画像ファイルを複数選ぶことができる.
- 次に出力結果を保存するフォルダを選ぶ.
- 結果の確認