Dlib による顔検出を行う Python プログラム(Dlib, Python を使用)(Windows 上)

目次

  1. 前準備
  2. Dlib Python のインストール,Dlib のソースコード等と,Dlib の学習済みモデルのダウンロード
  3. Dlib による顔検出を行う Python プログラム(Dlib に付属のプログラムを使用)
  4. Dlib による顔検出を行う Python プログラム(手持ちの画像ファイルや,パソコンのカメラで顔検出を行う)

サイト内の関連ページ

用語説明

1. 前準備

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

    インストールの判断Build Tools for Visual Studio は,開発ツールセットである. Visual Studio は統合開発環境であり,いくつかの種類があり,Build Tools for Visual Studioの機能を含むか連携して使用するものである.インストールは以下の基準で判断してください:

    不明な点がある場合は,Visual Studio 全体をインストール を行う方が良い.

    Build Tools for Visual Studio 2022 のインストール(Windows 上)

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

      次のコマンドを実行

      次のコマンドは,Build Tools for Visual Studio 2022と VC2015 再配布可能パッケージをインストールするものである.

      winget install --scope machine Microsoft.VisualStudio.2022.BuildTools
      winget install --scope machine Microsoft.VCRedist.2015+.x64
      
    2. Build Tools for Visual Studio 2022 での C++ によるデスクトップ開発,CLI,ATL,MFC のインストール(Windows 上)
      1. Visual Studio Installer の起動

        起動方法: スタートメニューの「Visual Studio Installer」を選ぶ.

      2. Visual Studio Build Tools 2022 で「変更」を選ぶ.
      3. C++ によるデスクトップ開発」をクリック.そして,画面右側の「インストール」の詳細で「v143 ビルドツール用 C++/CLI サポート(最新)」,「ATL」,「MFC」をチェックする.その後,「変更」をクリック.

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

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

      次のコマンドを実行

      1. コマンドプロンプト管理者権限で起動する(例:Windowsキーを押し,「cmd」と入力し,「管理者として実行」を選択)
      2. インストールコマンドの実行
        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 Library
        • VC.ATLMFC:デスクトップアプリケーション開発用のMicrosoft Foundation Class Library

        システム要件と注意事項:

        • 管理者権限でのインストールが必須
        • 必要ディスク容量:10GB以上
        • 推奨メモリ:8GB以上のRAM
        • インストール過程でシステムの再起動が要求される可能性がある
        • 安定したインターネット接続環境が必要

        追加のコンポーネントが必要な場合は,Visual Studio Installerを使用して個別にインストールすることが可能である.

      3. インストール完了の確認
        winget list Microsoft.VisualStudio.2022.Community
        

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

        インストール失敗時は,以下のログファイルを確認:

        %TEMP%\dd_setup_<timestamp>.log
        %TEMP%\dd_bootstrapper_<timestamp>.log
    2. Visual Studio での C++ によるデスクトップ開発,CLI のインストール(Windows 上)
      1. Visual Studio Installer の起動

        起動方法: スタートメニューの「Visual Studio Installer」を選ぶ.

      2. Visual Studio Community 2022 で「変更」を選ぶ.
      3. C++ によるデスクトップ開発」をチェック.そして,画面右側の「インストール」の詳細で「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\")"
      

    関連する外部ページ

    2. 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
      

    Dlib による顔検出を行う Python プログラム(Dlib に付属のプログラムを使用)

    Dlib による顔検出 を行う.

    Python プログラムの実行(Windows 上)

    1. まずは、DLib に同封の顔画像ファイルに何があるかを、簡単にみておく

      %HOMEPATH%\dlib\examples\faces の下の顔画像のファイルを確認する

    2. cnn_face_detector.py をエディタなどで開いて、中身を確認

      Dlib には Convolutional Network による顔検出の機能があり、顔検出させるためのプログラムは実質2行. 画面を開く、画像ファイルを読み込む、画像データを表示する、顔部分を四角で描くといったことも簡単なコマンド.

    3. Dlib では、顔のサイズは 80 x 80 であるとして、学習済みデータが配布されている。 より小さな顔を検出したいときは、アップサンプルを行う。アップサンプルを行うと、動作は遅くなる。

      cnn_face_detector.py の「dets = cnn_face_detector(img, 1)」の「1」を「2」や「3」に変える。 そして、再び、cnn_face_detector.py を実行する。

      上で使用した画像を、縦、横 0.4 倍した画像で試してみる。 まず、「dets = cnn_face_detector(img, 1)」のとき

      「dets = cnn_face_detector(img, 2)」のとき

      「dets = cnn_face_detector(img, 3)」のとき

    Dlib による顔検出を行う Python プログラム(手持ちの画像ファイルや,パソコンのカメラで顔検出を行う)

    Python の opencv-python のインストール

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

      *pip install ...」は,Python パッケージをインストールするための操作

      python -m pip install -U opencv-python opencv-contrib-python
      

    手持ちの画像ファイルで顔検出を行う.

    dlib に付属の「face_detector.py」を参考にして、次のプログラムを作成してみた.

    1. 処理したい画像ファイルを準備

      ファイル名は a.png にする. %HOMEPATH%\dlib\python_examples に置く.

      cd C:\dlib\python_examples
      curl -O https://www.kkaneko.jp/sample/face/126.png
      move 126.png a.png
      
    2. Python プログラムファイルの作成
      notepad hoge.py
      

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

      import dlib
      import cv2
      import numpy as np
      
      def box_label(img, x1, y1, x2, y2, label):
          cv2.rectangle(img, (x1, y1), (x2, y2), (255, 0, 0), 1, 1)
          cv2.rectangle(img, (int(x1), int(y1-25)), (x2, y1), (255,255,255), -1)
          cv2.putText(img, label, (x1, int(y1-5)), cv2.FONT_HERSHEY_COMPLEX, 0.7, (0,0,0), 1)
      
      # 「mmod_human_face_detector.bat」のところは、学習済みモデルのファイル名.
      face_detector = dlib.cnn_face_detection_model_v1('mmod_human_face_detector.dat')
      
      # 画像ファイル名を a.png のところに設定
      img = cv2.imread('a.png')
      if img is None:
          print("画像ファイルがない")
          exit()
      
      # 顔検出を行う.
      faces = face_detector(img, 1)
      
      # 顔検出で得られた顔(複数あり得る)それぞれについて、四角を書く
      for i, f in enumerate(faces):
              box_label(img, f.rect.left(), f.rect.top(), f.rect.right(), f.rect.bottom(), 'face')
      
      # 画面に描画
      cv2.imshow('',img)
      cv2.waitKey(0)
      cv2.destroyAllWindows()
      
      # ファイルに保存
      cv2.imwrite("result.png", img)
      
    3. Python プログラムの実行

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

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

      python hoge.py
      

    パソコンのカメラで顔検出を行う.

    dlib に付属の「face_detector.py」を参考にして、次のプログラムを作成してみた.

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

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

      import dlib
      import cv2
      import numpy as np
      
      def box_label(img, x1, y1, x2, y2, label):
          cv2.rectangle(img, (x1, y1), (x2, y2), (255, 0, 0), 1, 1)
          cv2.rectangle(img, (int(x1), int(y1-25)), (x2, y1), (255,255,255), -1)
          cv2.putText(img, label, (x1, int(y1-5)), cv2.FONT_HERSHEY_COMPLEX, 0.7, (0,0,0), 1)
      
      # ディープラーニングを使わない.精度は低下し,性能は上がるとされている.
      face_detector = dlib.get_frontal_face_detector()
      
      # ビデオカメラ
      v = cv2.VideoCapture(0)
      
      
      while(v.isOpened()):
          r, img = v.read()
          if ( r == False ):
              break
      # 顔検出を行う
          faces = face_detector(img, 1)
          for i, f in enumerate(faces):
      # 四角を書く
              box_label(img, f.left(), f.top(), f.right(), f.bottom(), 'face')
              print(d)
          cv2.imshow("", img)
          if cv2.waitKey(1) & 0xFF == ord('q'):
              cv2.destroyAllWindows()
              break
      
    2. Python プログラムの実行

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

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

      python hoge2.py
      

      * 途中で止めたいとき,右上の「x」をクリックしない.画面の中をクリックしてから,「q」のキーを押して閉じる