face_recognition による顔のクラスタリングを行う Python プログラム(Dlib,ageitgey/face_recognition,Python を使用)(Windows 上)
【サイト内の関連ページ】
- 説明資料: Dlib の機能概要 [PDF], [パワーポイント]
- 顔情報処理の Python プログラム(Dlib,face_recognition を使用) について: 別ページ »にまとめ
- Windows で動く人工知能関係 Pythonアプリケーション,オープンソースソフトウエア): 別ページ »にまとめている.
【用語説明】
- Dlib
Dlibは,数多くの機能を持つ C++ ライブラリ.機能には,機械学習,数値計算,グラフィカルモデル推論,画像処理,スレッド,通信,GUI,データ圧縮・一貫性,テスト,さまざまなユーティリティなどがある.Python API もある.
【関連する外部ページ】
ageitgey/face_recognition のページ: https://github.com/ageitgey/face_recognition
前準備
Python のインストール(Windows上)
注:既にPython(バージョン3.12を推奨)がインストール済みの場合は,この手順は不要である.
winget(Windowsパッケージマネージャー)を使用してインストールを行う
- Windowsで,コマンドプロンプトを管理者権限で起動する(例:Windowsキーを押し,「cmd」と入力し,「管理者として実行」を選択)
- winget(Windowsパッケージマネージャー)が利用可能か確認する:
winget --version
- Pythonのインストール(下のコマンドにより Python 3.12 がインストールされる).
- Python詳細ガイド:Pythonまとめ »
- コマンドラインからのビルドなど、C++コンパイラ機能のみが必要な場合:
- Visual Studioのエディタやデバッガなどの統合開発環境機能が必要な場合、あるいは、どちらをインストールすべきかよく分からない場合:
Visual Studio Community (または他のエディション) をインストール します.
Visual Studio 2022 をインストールする際に,「C++ によるデスクトップ開発」ワークロードを選択することで,必要なBuild Toolsの機能も一緒にインストールされます.
- Windows で,コマンドプロンプトを管理者権限で起動します(例:Windowsキーを押し,「cmd」と入力し,「管理者として実行」を選択)。
以下の
winget
コマンドを実行します。winget
はWindows標準のパッケージマネージャーです。--scope machine
オプションはシステム全体にインストールすることを意味します。次のコマンドは,Build Tools for Visual Studio 2022と、多くのプログラムで必要とされるVC++ 2015以降の再頒布可能パッケージをインストールします.
- Build Tools for Visual Studio 2022 で C++ によるデスクトップ開発関連コンポーネントのインストール
CUDA開発には、標準のC++開発ツールに加えて、特定のコンポーネントが必要になる場合があります。
- Visual Studio Installer を起動します。
起動方法: スタートメニューから「Visual Studio Installer」を探して実行します.
- Visual Studio Build Tools 2022 の項目で「変更」ボタンをクリックします.
- 「ワークロード」タブで「C++ によるデスクトップ開発」をクリックして選択します。画面右側の「インストールの詳細」で、必要に応じて「v143 ビルドツール用 C++/CLI サポート(最新)」、「ATL」、「MFC」などをチェックします(これらは一般的なC++開発や特定のプロジェクトタイプで必要になる場合があります)。その後、「変更」をクリックしてインストールまたは変更を適用します.
- Visual Studio Installer を起動します。
- Windows で,コマンドプロンプトを管理者権限で起動します。
- インストールコマンドの実行
以下の
winget
コマンドを実行します。--override "--add ..."
部分で、インストールするワークロードやコンポーネントを指定しています。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++によるデスクトップ開発): CUDA開発に必要なC++コンパイラ(VC.Tools.x86.x64
)やWindows SDK (Windows.SDK.Latest
)など、基本的な開発ツール一式を含みます。CoreEditor
: Visual Studioの基本的なコードエディタ機能を提供します。VC.CLI.Support
: C++/CLIを用いた開発サポート(通常、純粋なCUDA C++開発では不要な場合もあります)。NuGet
: .NETライブラリ管理用(C++プロジェクトでも利用されることがあります)。VC.ATL
/VC.ATLMFC
: 特定のWindowsアプリケーション開発フレームワーク(通常、CUDA開発自体には直接必要ありません)。
システム要件と注意事項:
- 管理者権限でのインストールが必須です。
- 必要ディスク容量:10GB以上(選択するコンポーネントにより変動)。
- 推奨メモリ:8GB以上のRAM。
- インストール過程でシステムの再起動が要求される可能性があります。
- 安定したインターネット接続環境が必要です。
後から追加のコンポーネントが必要になった場合は,Visual Studio Installerを使用して個別にインストールすることが可能です.
- インストール完了の確認
インストールが成功したか確認するには、管理者権限のコマンドプロンプトで以下のコマンドを実行します。
winget list Microsoft.VisualStudio.2022.Community
リストに表示されればインストールされています。
トラブルシューティング:
インストール失敗時は,以下のログファイルを確認すると原因究明の手がかりになります:
%TEMP%\dd_setup_
.log %TEMP%\dd_bootstrapper_ .log (
は実行日時に対応する文字列) - (オプション) Visual Studio Installer での確認と変更
winget
でのインストール後も、Visual Studio Installerを使ってインストール内容を確認・変更できます。- Visual Studio Installer を起動します。
- Visual Studio Community 2022 の項目で「変更」をクリックします。
- 「ワークロード」タブで「C++ によるデスクトップ開発」がチェックされていることを確認します。必要であれば、「個別のコンポーネント」タブで特定のツール(例: 特定バージョンのMSVCコンパイラ、CMakeツールなど)を追加・削除できます。「インストールの詳細」で「v143 ビルドツール用 C++/CLI サポート(最新)」などが選択されているかも確認できます。変更後、「変更」または「インストール」をクリックします。
- Windows で,コマンドプロンプトを管理者権限で起動する(例:Windowsキーを押し,「cmd」と入力し,「管理者として実行」を選択)
- 次のコマンドを実行
次のコマンドは,7-Zipをインストールするものである.
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\")"
- 7-Zip の公式ページ: https://7-zip.opensource.jp/
- Windows で,コマンドプロンプトを管理者権限で起動する(例:Windowsキーを押し,「cmd」と入力し,「管理者として実行」を選択)
- 次のコマンドを実行する.
python -m pip install -U dlib
- Windows で,コマンドプロンプトを管理者権限で起動する(例:Windowsキーを押し,「cmd」と入力し,「管理者として実行」を選択)
- Dlib のソースコード等のダウンロード
次のコマンドを実行.
cd C:\ rmdir /s /q dlib git clone https://github.com/davisking/dlib
- Dlib の学習済みモデルのダウンロード
次のコマンドを実行.
cd C:\dlib cd python_examples curl -O http://dlib.net/files/mmod_human_face_detector.dat.bz2 curl -O http://dlib.net/files/dlib_face_recognition_resnet_model_v1.dat.bz2 curl -O http://dlib.net/files/shape_predictor_5_face_landmarks.dat.bz2 curl -O http://dlib.net/files/shape_predictor_68_face_landmarks.dat.bz2 "c:\Program Files\7-Zip\7z.exe" x mmod_human_face_detector.dat.bz2 "c:\Program Files\7-Zip\7z.exe" x dlib_face_recognition_resnet_model_v1.dat.bz2 "c:\Program Files\7-Zip\7z.exe" x shape_predictor_5_face_landmarks.dat.bz2 "c:\Program Files\7-Zip\7z.exe" x shape_predictor_68_face_landmarks.dat.bz2 del mmod_human_face_detector.dat.bz2 del dlib_face_recognition_resnet_model_v1.dat.bz2 del shape_predictor_5_face_landmarks.dat.bz2 del shape_predictor_68_face_landmarks.dat.bz2
- Windows のコマンドプロンプトを開く
- Python プログラムファイルの作成
ここでは,ファイル名は cluster.py とする.
cd /d c:%HOMEPATH% cd face_recognition notepad cluster.py
ソースコードは次の通り.
次のソースコードは,Dlib に付属の python_examples\face_clustering.py (パブリックドメイン)を書き替えたもの.
太字が書き換え部分.顔画像のすべてを出力するように変更.
#!/usr/bin/python # The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt # # This example shows how to use dlib's face recognition tool for clustering using chinese_whispers. # This is useful when you have a collection of photographs which you know are linked to # a particular person, but the person may be photographed with multiple other people. # In this example, we assume the largest cluster will contain photos of the common person in the # collection of photographs. Then, we save extracted images of the face in the largest cluster in # a 150x150 px format which is suitable for jittering and loading to perform metric learning (as shown # in the dnn_metric_learning_on_images_ex.cpp example. # https://github.com/davisking/dlib/blob/master/examples/dnn_metric_learning_on_images_ex.cpp # # COMPILING/INSTALLING THE DLIB PYTHON INTERFACE # You can install dlib using the command: # pip install dlib # # Alternatively, if you want to compile dlib yourself then go into the dlib # root folder and run: # python setup.py install # # Compiling dlib should work on any operating system so long as you have # CMake installed. On Ubuntu, this can be done easily by running the # command: # sudo apt -y install cmake # # Also note that this example requires Numpy which can be installed # via the command: # pip install numpy import sys import os import dlib import glob if len(sys.argv) != 5: print( "Call this program like this:\n" " ./face_clustering.py shape_predictor_5_face_landmarks.dat dlib_face_recognition_resnet_model_v1.dat ../examples/faces output_folder\n" "You can download a trained facial shape predictor and recognition model from:\n" " http://dlib.net/files/shape_predictor_5_face_landmarks.dat.bz2\n" " http://dlib.net/files/dlib_face_recognition_resnet_model_v1.dat.bz2") exit() predictor_path = sys.argv[1] face_rec_model_path = sys.argv[2] faces_folder_path = sys.argv[3] output_folder_path = sys.argv[4] # Load all the models we need: a detector to find the faces, a shape predictor # to find face landmarks so we can precisely localize the face, and finally the # face recognition model. detector = dlib.get_frontal_face_detector() sp = dlib.shape_predictor(predictor_path) facerec = dlib.face_recognition_model_v1(face_rec_model_path) descriptors = [] images = [] # Now find all the faces and compute 128D face descriptors for each face. for f in glob.glob(os.path.join(faces_folder_path, "*.jpg")): print("Processing file: {}".format(f)) img = dlib.load_rgb_image(f) # Ask the detector to find the bounding boxes of each face. The 1 in the # second argument indicates that we should upsample the image 1 time. This # will make everything bigger and allow us to detect more faces. dets = detector(img, 1) print("Number of faces detected: {}".format(len(dets))) # Now process each face we found. for k, d in enumerate(dets): # Get the landmarks/parts for the face in box d. shape = sp(img, d) # Compute the 128D vector that describes the face in img identified by # shape. face_descriptor = facerec.compute_face_descriptor(img, shape) descriptors.append(face_descriptor) images.append((img, shape)) # Now let's cluster the faces. labels = dlib.chinese_whispers_clustering(descriptors, 0.5) num_classes = len(set(labels)) print("Number of clusters: {}".format(num_classes)) if not os.path.isdir(output_folder_path): os.makedirs(output_folder_path) # Find biggest class biggest_class = None biggest_class_length = 0 for i in range(0, num_classes): print(i) indices = [] for k, label in enumerate(labels): if label == i: indices.append(k) for k, index in enumerate(indices): img, shape = images[index] file_path = os.path.join(output_folder_path, "face_" + str(i) + "_" + str(k)) dlib.save_face_chip(img, shape, file_path, size=150, padding=0.25)
- Python プログラムの実行
python cluster.py ..\dlib\python_examples\shape_predictor_5_face_landmarks.dat ..\dlib\python_examples\dlib_face_recognition_resnet_model_v1.dat ..\examples\faces output_folder
- 結果を確認
「..\examples\faces」の下にあったすべてのファイルについて顔が抽出され,Dlib の chinese_whispers_clustering によりクラスタリングが行われる.
結果の画像ファイル名は output_folder に入る. 画像ファイル名は「face_<クラスタ番号>_<クラスタ内での番号>」になる.
次のような結果が得られる.
【関連する外部サイト】
【サイト内の関連ページ】
Build Tools for Visual Studio 2022 (ビルドツール for Visual Studio 2022)または Visual Studio 2022 のインストール(Windows 上)
CUDAツールキットは、GPU上でコードをコンパイルするためにC++コンパイラを必要とします。そのため、事前にMicrosoft C++ Build Tools または Visual Studio (C++開発ワークロードを含む) をインストールしておく必要があります。
【インストールの判断】 Build Tools for Visual Studio は,C++コンパイラなどを含む開発ツールセットです. Visual Studio は統合開発環境であり,いくつかのエディションがあり,Build Tools for Visual Studioの機能を含むか連携して使用します.インストールは以下の基準で判断してください:
不明な点がある場合は,Visual Studio 全体をインストール する方が、後で機能を追加する手間が省ける場合があります.
Build Tools for Visual Studio 2022 のインストール(Windows 上)
Visual Studio Community 2022 のインストール(Windows 上)
Git のインストール(Windows 上)
Gitは,バージョン管理システム.ソースコードの管理や複数人での共同に役立つ.
【サイト内の関連ページ】 Windows での Git のインストール: 別ページ »で説明
【関連する外部ページ】 Git の公式ページ: https://git-scm.com/
7-Zip のインストール(Windows 上)
7-Zipは,ファイル圧縮・展開(解凍)ツール
【関連する外部ページ】