face_recognition による顔検出,顔のランドマーク,顔検証の Python プログラム(Dlib,ageitgey/face_recognition,Python を使用)(Windows 上)

概要

本記事では,face_recognition による顔検出,顔のランドマーク,顔検証の Python プログラム(Dlib,ageitgey/face_recognition,Python を使用)について,Windows 上での環境構築からプログラムの実行までを解説する.

Dlibは,数多くの機能を持つ C++ ライブラリである.機能には,機械学習,数値計算,グラフィカルモデル推論,画像処理,スレッド,通信,GUI,データ圧縮・一貫性,テスト,さまざまなユーティリティなどがある.Python API もある.

本記事で扱うプログラムは以下の通りである.

目次

サイト内の関連情報

1. 前準備(必要ソフトウェアの入手)

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

Build Tools for Visual Studio 2026(ビルドツール)のインストール

Build Tools for Visual Studio 2026(ビルドツール)のインストールを行い、C/C++ コードのビルド環境を整える。

[Build Tools for Visual Studio 2026(ビルドツール)のインストール手順を見るには、ここをクリック]

Windows での Build Tools for Visual Studio 2026 のインストール

Build Tools for Visual Studio は,Visual Studio の IDE を含まない C/C++ コンパイラ,ライブラリ,ビルドツール等のコマンドライン向け開発ツールセットである。インストール済みの場合,この手順は不要である。

以下のコマンドは、Build Tools が未インストールの場合は winget で新規インストールし、インストール済みの場合は setup.exe modify でコンポーネントを追加する(バージョンは変更しない)。

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

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

REM VC++ ランタイム
winget install --scope machine --id Microsoft.VCRedist.2015+.x64 -e --silent --disable-interactivity --force --accept-source-agreements --accept-package-agreements --override "/quiet /norestart"

REM ============================================================
REM Visual Studio Build Tools + Desktop development with C++
REM (VCTools、MSBuildTools、CMake連携、Clang、Windows 11 SDK)
REM ============================================================
REM 進行中のインストーラーを停止(ロック競合回避)
taskkill /F /IM vs_setup.exe /T >nul 2>&1
taskkill /F /IM vs_installer.exe /T >nul 2>&1
taskkill /F /IM vs_installerservice.exe /T >nul 2>&1

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 --includeRecommended --quiet --norestart --nocache
) 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"
)

REM 破損時の修復(任意、動作がおかしくなった場合)
REM "C:\Program Files (x86)\Microsoft Visual Studio\Installer\setup.exe" repair --installPath "C:\Program Files (x86)\Microsoft Visual Studio\18\BuildTools" --quiet --norestart

REM 導入確認(インストールパスが表示されれば正常)
"C:\Program Files (x86)\Microsoft Visual Studio\Installer\vswhere.exe" -products * -requires Microsoft.VisualStudio.Workload.VCTools -property installationPath

上記のコマンドでは、Build Tools 本体と Visual C++ 再頒布可能パッケージをインストールし、続いて以下のコンポーネントを追加している。

上記以外の追加のコンポーネントが必要になった場合は Visual Studio Installer で個別にインストールできる。

インストール完了の確認

winget list Microsoft.VisualStudio.BuildTools

Visual Studio を必要とするとき

Visual Studio の機能を必要とする場合は,追加インストールできる。

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\""

REM Python と Scripts を PATH 先頭に追加
powershell -NoProfile -Command "$p='C:\Program Files\Python312'; $s=\"$p\Scripts\"; $c=[Environment]::GetEnvironmentVariable('Path','Machine'); if((Test-Path $p) -and (';'+$c+';' -notlike \"*;$p;*\") -and (';'+$c+';' -notlike \"*;$s;*\")){[Environment]::SetEnvironmentVariable('Path',\"$p;$s;$c\",'Machine')}"

方法 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' は、内部コマンドまたは外部コマンドとして認識されていません。」と表示される場合は、インストールが正常に完了していない。

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 ============================================================
winget uninstall -e --id Microsoft.VisualStudioCode --silent --disable-interactivity --accept-source-agreements
rmdir /s /q C:\ProgramData\vscode-extensions 2>nul
rmdir /s /q "%APPDATA%\Code" 2>nul
rmdir /s /q "%USERPROFILE%\.vscode" 2>nul
rmdir /s /q "%LOCALAPPDATA%\Microsoft\vscode-update" 2>nul

REM VS Code をシステム領域に新規インストール
winget install --scope machine --id Microsoft.VisualStudioCode -e --silent --accept-source-agreements --accept-package-agreements

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

REM スタートメニューのショートカットを --extensions-dir 付きで再作成
rmdir /s /q "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Visual Studio Code" 2>nul
del "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Visual Studio Code.lnk" 2>nul
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
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)を選択する.

Git のインストール(Windows 上) [クリックして展開]

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

REM Git をシステム領域にインストール
winget install --scope machine --id Git.Git -e --silent --disable-interactivity --force --accept-source-agreements --accept-package-agreements --override "/VERYSILENT /NORESTART /NOCANCEL /SP- /CLOSEAPPLICATIONS /RESTARTAPPLICATIONS /COMPONENTS=""icons,ext\reg\shellhere,assoc,assoc_sh"" /o:PathOption=Cmd /o:CRLFOption=CRLFCommitAsIs /o:BashTerminalOption=MinTTY /o:DefaultBranchOption=main /o:EditorOption=VIM /o:SSHOption=OpenSSH /o:UseCredentialManager=Enabled /o:PerformanceTweaksFSCache=Enabled /o:EnableSymlinks=Disabled /o:EnableFSMonitor=Disabled"

7-Zip のインストール(Windows 上) [クリックして展開]

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

REM 7-Zip をシステム領域にインストール
winget install --scope machine --id 7zip.7zip -e --silent --disable-interactivity --force --accept-source-agreements --accept-package-agreements
REM 7-Zip のパス設定
powershell -NoProfile -Command "$p='C:\Program Files\7-Zip'; $c=[Environment]::GetEnvironmentVariable('Path','Machine'); if((Test-Path $p) -and $c -notlike \"*$p*\"){[Environment]::SetEnvironmentVariable('Path',\"$p;$c\",'Machine')}"

Dlib ライブラリのインストールと学習済みモデルのダウンロード [クリックして展開]

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

Dlib ライブラリのインストール

python -m pip uninstall -y dlib
cd C:\
rmdir /s /q dlib
git clone https://github.com/davisking/dlib
cd C:\dlib
python setup.py build --no DLIB_GIF_SUPPORT
python setup.py install --no DLIB_GIF_SUPPORT

インストールの確認

バージョン番号が表示されれば OK である.下の図とは異なるバージョンが表示されることがある.
python -c "import dlib; print( dlib.__version__ )"

Dlib のソースコード等のダウンロード

cd C:\
rmdir /s /q dlib
git clone https://github.com/davisking/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

Dlib の動作確認

次を実行し,エラーメッセージが出ずに顔検出の結果が表示されれば OK とする.

cd C:\dlib
cd python_examples
python cnn_face_detector.py mmod_human_face_detector.dat ..\examples\faces\2007_007763.jpg

必要なライブラリのインストール [クリックして展開]

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

python -m pip install -U --no-user opencv-python opencv-contrib-python numpy scikit-image scikit-learn

ageitgey の face_recognition のインストール [クリックして展開]

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

cd /d c:%HOMEPATH%
rmdir /s /q face_recognition
git clone https://github.com/ageitgey/face_recognition
cd face_recognition
copy C:\dlib\python_examples\shape_predictor_68_face_landmarks.dat .
python setup.py build
python setup.py install

インストール確認

バージョン番号が表示されればインストール成功である.

python -c "import face_recognition; print(face_recognition.__version__)"

2. 実行のための準備とその確認手順(Windows 前提)

2.1 プログラムファイルの準備

第4章に掲載するソースコード(画像表示を伴うプログラム)をテキストエディタ(メモ帳等)に貼り付け,a.py として %HOMEPATH%\face_recognition ディレクトリに保存する(文字コード:UTF-8).

cd /d c:%HOMEPATH%
cd face_recognition
notepad a.py

対話的に実行するプログラム(顔検出,顔ランドマーク,顔検証)は,Python インタプリタ上で直接入力して実行する.

また,以下の手順でファイルとディレクトリを準備する.

  1. Windows のコマンドプロンプトを開く
  2. 2つのディレクトリ known_people, unknown_pictures を作る
    mkdir %HOMEPATH%\face_recognition\known_people
    mkdir %HOMEPATH%\face_recognition\unknown_pictures
    
  3. %HOMEPATH%\face_recognition\examples にある顔画像ファイル「biden.jpg」と「obama.jpg」を,ディレクトリ known_people の下にコピーする
    copy %HOMEPATH%\face_recognition\examples\biden.jpg %HOMEPATH%\face_recognition\known_people
    copy %HOMEPATH%\face_recognition\examples\obama.jpg %HOMEPATH%\face_recognition\known_people
    
  4. ディレクトリ known_people の下に 2つの画像ファイルがあることを確認する
  5. 同様に「two_people.jpg」を,ディレクトリ unknown_pictures の下にコピーする
    copy %HOMEPATH%\face_recognition\examples\two_people.jpg %HOMEPATH%\face_recognition\unknown_pictures
    
  6. ディレクトリ unknown_pictures の下に画像ファイルがあることを確認する

2.2 実行コマンド

対話的プログラムは,コマンドプロンプトでホームディレクトリに移動してから Python インタプリタを起動し実行する.

cd /d c:%HOMEPATH%
python

ファイルとして保存したプログラム(a.py)は以下で実行する.

cd /d c:%HOMEPATH%
cd face_recognition
python a.py
Python プログラムの実行: 別ページ »で説明

Python のまとめ: 別ページ »にまとめ

2.3 動作確認チェックリスト

確認項目期待される結果
顔検出プログラムの実行顔の位置座標(top, right, bottom, left のタプル)が出力される
顔検出と画像表示プログラムの実行検出された顔の数がコンソールに表示され,顔を矩形で囲んだ画像ウインドウが表示される
顔ランドマークプログラムの実行chin, left_eyebrow, right_eyebrow, nose_bridge, left_eye, right_eye の情報が表示される
顔ランドマークと画像表示プログラムの実行ランドマーク点が描画されたウインドウが表示される
left_eye / left_eyebrow ランドマーク表示の実行左目(緑色)と左眉(赤色)のランドマーク点が描画されたウインドウが表示される
顔検証プログラム(異なる人物)の実行[False] と顔間のユークリッド距離が出力される
顔検証プログラム(同一人物)の実行[True] と顔間のユークリッド距離が出力される
画像表示ウインドウの終了画面の中をクリックしてからキーを押すとウインドウが閉じる(右上の「x」はクリックしない)

3. 概要・使い方・実行上の注意

本章の各プログラムについて,対話的に実行するものは Python インタプリタ上で直接入力する.ファイルとして実行するもの(a.py)のソースコードは第4章に掲載する.パス中のディレクトリ区切りに「\」でなく「/」を使うのは Python の流儀である.実際の環境に合わせてディレクトリパスを書き換えて実行すること.

画像表示を伴うプログラムでは,ウインドウの右上の「x」をクリックしない.画面の中をクリックしてから,何かのキーを押して閉じる

顔検出

face_recognition.face_locations に model="cnn" を指定し,CNN ベースの顔検出を行う.

顔検出と画像表示

プログラムは,https://github.com/ageitgey/face_recognition/blob/master/examples/find_faces_in_picture.py を一部変更したものである.

顔ランドマーク

chin, left_eyebrow, right_eyebrow, nose_bridge, left_eye, right_eye の情報が表示される.

顔ランドマークと画像表示

プログラムは,https://github.com/ageitgey/face_recognition/blob/master/examples/find_faces_in_picture.py を一部変更したものである.

left_eye と left_eyebrow のランドマーク表示

left_eye と left_eyebrow のランドマーク画像表示

プログラムは,https://github.com/ageitgey/face_recognition/blob/master/examples/find_faces_in_picture.py を一部変更したものである.

顔検証 (face verification)

2つの顔画像が同一人物か判定する

別の顔で動かす

https://github.com/ageitgey/face_recognition に掲載の写真から切り取った,次の写真を使う.

画像ファイルを unknown_pictures の下に 104.png として保存する.

cd /d c:%HOMEPATH%
curl -O https://www.kkaneko.jp/ai/dlib/104.png
copy 104.png face_recognition\unknown_pictures
python

今度は True と表示される.

4. ソースコード

顔検出

import face_recognition
image = face_recognition.load_image_file("face_recognition/unknown_pictures/two_people.jpg")
face_locations = face_recognition.face_locations(image, model="cnn")
print(face_locations)
exit()

顔検出と画像表示(a.py)

import face_recognition
import cv2

F = "unknown_pictures/two_people.jpg"
image = face_recognition.load_image_file(F)
face_locations = face_recognition.face_locations(image, model="cnn")
print("検出された顔の数:", len(face_locations))

bgr = cv2.imread(F)
for top, right, bottom, left in face_locations:
    cv2.rectangle(bgr, (left, top), (right, bottom), (255, 0, 0), 1)
    cv2.rectangle(bgr, (left, top - 25), (right, top), (255, 255, 255), -1)
    cv2.putText(bgr, 'face', (left, top - 5), cv2.FONT_HERSHEY_COMPLEX, 0.7, (0, 0, 0), 1)

cv2.imshow('', bgr)
cv2.waitKey(0)
cv2.destroyAllWindows()

顔ランドマーク

import face_recognition
image = face_recognition.load_image_file("face_recognition/unknown_pictures/two_people.jpg")
face_locations = face_recognition.face_locations(image, model="cnn")
face_landmarks_list = face_recognition.face_landmarks(image, face_locations=face_locations)
for i in face_landmarks_list:
    print(i)

exit()

顔ランドマークと画像表示(a.py)

import face_recognition
import cv2

F = "unknown_pictures/two_people.jpg"
image = face_recognition.load_image_file(F)
face_locations = face_recognition.face_locations(image, model="cnn")
face_landmarks_list = face_recognition.face_landmarks(image, face_locations=face_locations)

bgr = cv2.imread(F)
for i in face_landmarks_list:
    for j in i.keys():
        for k in i[j]:
            cv2.circle(bgr, (k[0], k[1]), 2, (255, 0, 0), -1)

cv2.imshow('', bgr)
cv2.waitKey(0)
cv2.destroyAllWindows()

left_eye と left_eyebrow のランドマーク表示

import face_recognition
image = face_recognition.load_image_file("face_recognition/unknown_pictures/two_people.jpg")
face_locations = face_recognition.face_locations(image, model="cnn")
face_landmarks_list = face_recognition.face_landmarks(image, face_locations=face_locations)
for i in face_landmarks_list:
    print(i['left_eye'])
    print(i['left_eyebrow'])

exit()

left_eye と left_eyebrow のランドマーク画像表示(a.py)

import face_recognition
import cv2

F = "unknown_pictures/two_people.jpg"
image = face_recognition.load_image_file(F)
face_locations = face_recognition.face_locations(image, model="cnn")
face_landmarks_list = face_recognition.face_landmarks(image, face_locations=face_locations)

bgr = cv2.imread(F)
for i in face_landmarks_list:
    for j in i['left_eye']:
        cv2.circle(bgr, (j[0], j[1]), 2, (0, 255, 0), -1)
    for j in i['left_eyebrow']:
        cv2.circle(bgr, (j[0], j[1]), 2, (0, 0, 255), -1)

cv2.imshow('', bgr)
cv2.waitKey(0)
cv2.destroyAllWindows()

顔検証(異なる人物の比較)

import face_recognition
picture_of_obama = face_recognition.load_image_file("face_recognition/known_people/obama.jpg")
obama_face_encoding = face_recognition.face_encodings(picture_of_obama)[0]

biden_picture = face_recognition.load_image_file("face_recognition/known_people/biden.jpg")
biden_face_encoding = face_recognition.face_encodings(biden_picture)[0]

results = face_recognition.compare_faces([obama_face_encoding], biden_face_encoding)
distance = face_recognition.face_distance([obama_face_encoding], biden_face_encoding)
print(results)
print("顔間のユークリッド距離:", distance)
exit()

顔検証(同一人物の比較)

import face_recognition
picture_of_obama = face_recognition.load_image_file("face_recognition/known_people/obama.jpg")
obama_face_encoding = face_recognition.face_encodings(picture_of_obama)[0]

another_picture = face_recognition.load_image_file("face_recognition/unknown_pictures/104.png")
another_face_encoding = face_recognition.face_encodings(another_picture)[0]

results = face_recognition.compare_faces([obama_face_encoding], another_face_encoding)
distance = face_recognition.face_distance([obama_face_encoding], another_face_encoding)
print(results)
print("顔間のユークリッド距離:", distance)
exit()

5. まとめ

本記事で扱った主要概念を以下に整理する.

顔検出

face_recognition.face_locations に model="cnn" を指定することで,CNN ベースの顔検出を行う.画像から顔の位置座標(top, right, bottom, left)を取得し,OpenCV の cv2.rectangle で矩形を描画できる.

顔ランドマーク

face_recognition.face_landmarks により,chin, left_eyebrow, right_eyebrow, nose_bridge, left_eye, right_eye 等の顔ランドマーク情報を取得できる.取得した座標を OpenCV の cv2.circle で描画することも可能である.

顔検証 (face verification)

face_recognition.face_encodings で顔の特徴量を取得し,face_recognition.compare_faces で2つの顔画像が同一人物か判定する.face_recognition.face_distance により顔間のユークリッド距離も確認できる.

Dlib と face_recognition の環境構築

Dlib は数多くの機能を持つ C++ ライブラリであり,Python API もある.Build Tools for Visual Studio によるコンパイル環境の準備,Dlib のソースコードからのビルドとインストール,学習済みモデルのダウンロードが必要である.ageitgey の face_recognition は Dlib をベースとした Python ライブラリであり,numpy, scikit-image, scikit-learn とあわせてインストールする.

画像表示ウインドウの操作

OpenCV の cv2.imshow で表示されるウインドウは,右上の「x」をクリックせず,画面の中をクリックしてからキーを押して閉じる.cv2.waitKey(0) がキー入力を待機し,cv2.destroyAllWindows() がウインドウを破棄する.