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

サイト内の関連ページ

用語説明

関連する外部ページ

ageitgey/face_recognition のページ: https://github.com/ageitgey/face_recognition

前準備

Python のインストール(Windows上)

注:既にPython(バージョン3.12を推奨)がインストール済みの場合は,この手順は不要である.

winget(Windowsパッケージマネージャー)を使用してインストールを行う

  1. Windowsで,コマンドプロンプト管理者権限で起動する(例:Windowsキーを押し,「cmd」と入力し,「管理者として実行」を選択)
  2. winget(Windowsパッケージマネージャー)が利用可能か確認する:
    winget --version
    
  3. Pythonのインストール(下のコマンドにより Python 3.12 がインストールされる).
    winget install --scope machine Python.Launcher
    winget install --scope machine Python.Python.3.12
    
  4. 【関連する外部サイト】

    【サイト内の関連ページ】

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 上)

  1. Windows で,コマンドプロンプト管理者権限で起動します(例:Windowsキーを押し,「cmd」と入力し,「管理者として実行」を選択)。

    以下のwingetコマンドを実行します。wingetはWindows標準のパッケージマネージャーです。

    --scope machine オプションはシステム全体にインストールすることを意味します。

    次のコマンドは,Build Tools for Visual Studio 2022と、多くのプログラムで必要とされるVC++ 2015以降の再頒布可能パッケージをインストールします.

    winget install --scope machine Microsoft.VisualStudio.2022.BuildTools
    winget install --scope machine Microsoft.VCRedist.2015+.x64
    
  2. Build Tools for Visual Studio 2022 で C++ によるデスクトップ開発関連コンポーネントのインストール

    CUDA開発には、標準のC++開発ツールに加えて、特定のコンポーネントが必要になる場合があります。

    1. Visual Studio Installer を起動します。

      起動方法: スタートメニューから「Visual Studio Installer」を探して実行します.

    2. Visual Studio Build Tools 2022 の項目で「変更」ボタンをクリックします.
    3. 「ワークロード」タブで「C++ によるデスクトップ開発」をクリックして選択します。画面右側の「インストールの詳細」で、必要に応じて「v143 ビルドツール用 C++/CLI サポート(最新)」、「ATL」、「MFC」などをチェックします(これらは一般的なC++開発や特定のプロジェクトタイプで必要になる場合があります)。その後、「変更」をクリックしてインストールまたは変更を適用します.

Visual Studio Community 2022 のインストール(Windows 上)

  1. Windows で,コマンドプロンプト管理者権限で起動します。
  2. インストールコマンドの実行

    以下の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を使用して個別にインストールすることが可能です.

  3. インストール完了の確認

    インストールが成功したか確認するには、管理者権限のコマンドプロンプトで以下のコマンドを実行します。

    winget list Microsoft.VisualStudio.2022.Community
    

    リストに表示されればインストールされています。

    トラブルシューティング:

    インストール失敗時は,以下のログファイルを確認すると原因究明の手がかりになります:

    %TEMP%\dd_setup_.log
    %TEMP%\dd_bootstrapper_.log

    ( は実行日時に対応する文字列)

  4. (オプション) Visual Studio Installer での確認と変更

    wingetでのインストール後も、Visual Studio Installerを使ってインストール内容を確認・変更できます。

    1. Visual Studio Installer を起動します。
    2. Visual Studio Community 2022 の項目で「変更」をクリックします。
    3. 「ワークロード」タブで「C++ によるデスクトップ開発」がチェックされていることを確認します。必要であれば、「個別のコンポーネント」タブで特定のツール(例: 特定バージョンのMSVCコンパイラ、CMakeツールなど)を追加・削除できます。「インストールの詳細」で「v143 ビルドツール用 C++/CLI サポート(最新)」などが選択されているかも確認できます。変更後、「変更」または「インストール」をクリックします。

Git のインストール(Windows 上)

Gitは,バージョン管理システム.ソースコードの管理や複数人での共同に役立つ.

サイト内の関連ページWindows での Git のインストール: 別ページ »で説明

関連する外部ページGit の公式ページ: https://git-scm.com/

7-Zip のインストール(Windows 上)

7-Zipは,ファイル圧縮・展開(解凍)ツール

  1. Windows で,コマンドプロンプト管理者権限で起動する(例:Windowsキーを押し,「cmd」と入力し,「管理者として実行」を選択)
  2. 次のコマンドを実行

    次のコマンドは,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\")"
    

関連する外部ページ

Dlib Python のインストール,Dlib のソースコード等と,Dlib の学習済みモデルのダウンロード

  1. Windows で,コマンドプロンプト管理者権限で起動する(例:Windowsキーを押し,「cmd」と入力し,「管理者として実行」を選択)
  2. Dlib のパッケージのインストール

    Windowspip を実行するときは,コマンドプロンプト管理者として開き,それを使って pip を実行することにする.

    次のコマンドを実行.

    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
    
  3. Python の dlib パッケージがインストールできたことの確認

    バージョン番号が表示されれば OK.下の図とは違うバージョンが表示されることがある.

    python -c "import dlib; print( dlib.__version__ )"
    
  4. Dlib のソースコード等のダウンロード

    次のコマンドを実行.

    cd C:\
    rmdir /s /q dlib
    git clone https://github.com/davisking/dlib
    
  5. 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
    
  6. Dlib の動作確認のため,次を実行.エラーメッセージが出ずに,顔検出の結果が表示されれば OK とする.
    cd C:\dlib
    cd python_examples
    python cnn_face_detector.py mmod_human_face_detector.dat ..\examples\faces\2007_007763.jpg
    

ageitgey/ageitgey の face_recognition のインストール

  1. Windows で,コマンドプロンプト管理者権限で起動する(例:Windowsキーを押し,「cmd」と入力し,「管理者として実行」を選択)
  2. numpy, scikit-image, scikit-learn のインストール

    次のコマンドを実行する.

    python -m pip install -U numpy scikit-image scikit-learn
    
  3. face_recognition のインストール
    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 プログラム

ファイルとディレクトリの準備

  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. Windows で、ディレクトリ known_people の下に 2つの画像ファイルがあることを確認
  5. %HOMEPATH%\face_recognition\examples にある顔画像のファイル 「two_people.jpg」を,先ほど作成した ディレクトリ unknown_pictures の下にコピー
    copy %HOMEPATH%\face_recognition\examples\two_people.jpg %HOMEPATH%\face_recognition\unknown_pictures
    
  6. Windows で、ディレクトリ unknown_pictures の下に画像ファイルがあることを確認

顔検出の Python プログラム

  • Python プログラムの実行

    Python プログラムの実行

    Python 開発環境(Jupyter Qt Console, Jupyter ノートブック (Jupyter Notebook), Jupyter Lab, Nteract, Spyder, PyCharm, PyScripterなど)も便利である.

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

    python
    

    face_recognition/unknown_pictures」のところは、実際に作成したディレクトリに書き換えて実行すること.ディレクトリの切れ目に「\」でなく「/」を使うのは Python の流儀.

    コマンドプロンプトで次を実行

    cd /d c:%HOMEPATH%
    python
    

    次の Python プログラムを実行

    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()
    

    顔検出と画像表示の Python プログラム

    プログラムは、https://github.com/ageitgey/face_recognition/blob/master/examples/find_faces_in_picture.py  のものを一部変更したものを掲載している

    1. Python プログラムファイルの作成

      ここでは,ファイル名は a.py とする.

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

      ソースコードは次の通り.

      face_recognition/unknown_pictures」のところは、実際に作成したディレクトリに書き換えて実行すること.ディレクトリの切れ目に「\」でなく「/」を使うのは Python の流儀.

      import face_recognition
      import PIL
      import cv2
      
      F = "unknown_pictures/two_people.jpg"
      
      image = face_recognition.load_image_file(F)
      face_locations = face_recognition.face_locations(image, model="cnn")
      
      def box_label(bgr, x1, y1, x2, y2, label):
          cv2.rectangle(bgr, (x1, y1), (x2, y2), (255, 0, 0), 1, 1)
          cv2.rectangle(bgr, (int(x1), int(y1-25)), (x2, y1), (255,255,255), -1)
          cv2.putText(bgr, label, (x1, int(y1-5)), cv2.FONT_HERSHEY_COMPLEX, 0.7, (0,0,0), 1)
      
      bgr = cv2.imread(F)
      for face_location in face_locations:
          top, right, bottom, left = face_location
          box_label(bgr, left, top, right, bottom, 'face')
      
      cv2.imshow('', bgr)
      cv2.waitKey(0)
      cv2.destroyAllWindows()
      
    2. Python プログラムの実行

      Python プログラムの実行: 別ページ »で説明

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

      python a.py
      

      画像が表示されるので確認. このあと,ウインドウの右上の「x」をクリックしない.画面の中をクリックしてから,何かのキーを押して閉じる

    顔ランドマークの Python プログラム

  • Python プログラムの実行

    Python プログラムの実行

    Python 開発環境(Jupyter Qt Console, Jupyter ノートブック (Jupyter Notebook), Jupyter Lab, Nteract, Spyder, PyCharm, PyScripterなど)も便利である.

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

    python
    

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

    「face_landmarks_list = face_recognition.face_landmarks(image)」の行を, 次のように書き換えると改善するかどうかは未確認(いずれ確認したい)

    コマンドプロンプトで次を実行

    cd /d c:%HOMEPATH%
    python
    

    次の Python プログラムを実行

    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()
    

    顔ランドマークと画像表示の Python プログラム

    プログラムは、https://github.com/ageitgey/face_recognition/blob/master/examples/find_faces_in_picture.py  のものを一部変更したものを掲載している

    1. Python プログラムファイルの作成

      ここでは,ファイル名は a.py とする.

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

      ソースコードは次の通り.

      unknown_pictures」のところは、実際に作成したディレクトリに書き換えて実行すること.ディレクトリの切れ目に「\」でなく「/」を使うのは Python の流儀.

      import face_recognition
      import PIL
      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)
      
      def box_label(bgr, x1, y1, x2, y2, label):
          cv2.rectangle(bgr, (x1, y1), (x2, y2), (255, 0, 0), 1, 1)
          cv2.rectangle(bgr, (int(x1), int(y1-25)), (x2, y1), (255,255,255), -1)
          cv2.putText(bgr, label, (x1, int(y1-5)), cv2.FONT_HERSHEY_COMPLEX, 0.7, (0,0,0), 1)
      
      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()
      
    2. Python プログラムの実行

      Python プログラムの実行: 別ページ »で説明

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

      python a.py
      

      画像が表示されるので確認. このあと,ウインドウの右上の「x」をクリックしない.画面の中をクリックしてから,何かのキーを押して閉じる

    顔のランドマークの Python プログラムで、左目(lefteye)と左の眉(left_eyrbrow)を表示

  • Python プログラムの実行

    Python プログラムの実行

    Python 開発環境(Jupyter Qt Console, Jupyter ノートブック (Jupyter Notebook), Jupyter Lab, Nteract, Spyder, PyCharm, PyScripterなど)も便利である.

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

    python
    

    コマンドプロンプトで次を実行

    cd /d c:%HOMEPATH%
    python
    

    次の Python プログラムを実行

    import face_recognition
    image = face_recognition.load_image_file("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()
    

    左目(lefteye)と左の眉(left_eyrbrow)のランドマークについて画像表示

    1. Python プログラムファイルの作成

      ここでは,ファイル名は a.py とする.

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

      ソースコードは次の通り.

      プログラムは、https://github.com/ageitgey/face_recognition/blob/master/examples/find_faces_in_picture.py  のものを一部変更したものを掲載している

      unknown_pictures」のところは、実際に作成したディレクトリに書き換えて実行すること.ディレクトリの切れ目に「\」でなく「/」を使うのは Python の流儀.

      import face_recognition
      import PIL
      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)
      
      def box_label(bgr, x1, y1, x2, y2, label):
          cv2.rectangle(bgr, (x1, y1), (x2, y2), (255, 0, 0), 1, 1)
          cv2.rectangle(bgr, (int(x1), int(y1-25)), (x2, y1), (255,255,255), -1)
          cv2.putText(bgr, label, (x1, int(y1-5)), cv2.FONT_HERSHEY_COMPLEX, 0.7, (0,0,0), 1)
      
      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()
      
    2. Python プログラムの実行

      Python プログラムの実行: 別ページ »で説明

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

      python a.py
      

      画像が表示されるので確認. このあと,ウインドウの右上の「x」をクリックしない.画面の中をクリックしてから,何かのキーを押して閉じる

    顔検証 (face verification) の Python プログラム

    2つの顔画像が同一人物かを識別する Python プログラム

    コマンドプロンプトで次を実行

    cd /d c:%HOMEPATH%
    python
    

    次の Python プログラムを実行

    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)
    print(results)
    exit()
    

    2つの顔画像が同一人物かを識別する Python プログラム(別の顔で動かす)

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

    1. コマンドプロンプトで次を実行

      (ここでは、上の画像ファイルを、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
      
    2. 次の Python プログラムを実行

      (今度は True と表示される)

      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)
      print(results)
      exit()