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

目次

  1. 前準備
  2. Dlib Python のインストール,Dlib のソースコード等と,Dlib の学習済みモデルのダウンロード
  3. 顔写真とビデオの準備
  4. Python プログラム

サイト内の関連ページ

用語説明

  • 顔ランドマークの検出 (face landmark detector): 画像から 68 のランドマーク (68 landmarks) を得る. tree structured part model により,最大 68 のランドマークを得る

    顔のランドマーク検知が行われ,顔を囲むようなバウンディングボックス (bounding box) と,顔のランドマーク表示される.

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

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

    関連する外部ページ

    imutils のインストール

    1. Windows で,コマンドプロンプト管理者権限で起動する(例:Windowsキーを押し,「cmd」と入力し,「管理者として実行」を選択)
    2. imutils のインストール
      cd /d c:%HOMEPATH%
      rmdir /s /q imutils
      
      cd /d c:%HOMEPATH%
      git clone https://github.com/jrosebr1/imutils
      cd imutils
      python setup.py build
      python setup.py install
      

      (以下省略)
    3. imutils のバージョン確認

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

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

    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
      

    顔写真とビデオの準備

    ここで使用するビデオ

    mp4 形式動画ファイル: sample1.mp4

    ここで使用する顔写真

    顔写真: 126.png, 127.png

    作業手順

    1. Windows のコマンドプロンプトを開く
    2. ダウンロード

      次のコマンドを実行.

      cd C:\dlib
      cd python_examples
      curl -O https://www.kkaneko.jp/sample/face/126.png
      curl -O https://www.kkaneko.jp/sample/face/127.png
      curl -O https://www.kkaneko.jp/sample/face/sample1.mp4
      

    Python プログラム

    濃淡画像に変換して表示する Python プログラム

    顔画像ファイル 126.png を読み込んで、濃淡画像に変換してみる

  • Python プログラムの実行

    Python プログラムの実行

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

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

    python
    

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

    cd C:\dlib
    python
    

    次の Python プログラムを実行

    import numpy as np
    import dlib
    import cv2
    import imutils
    from imutils import face_utils
    img = cv2.imread("./python_examples/126.png")
    mono = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    cv2.imshow("", mono)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    exit()
    

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

    顔検出の Python プログラム

  • Python プログラムの実行

    Python プログラムの実行

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

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

    python
    

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

    cd C:\dlib
    python
    

    次の Python プログラムを実行

    import numpy as np
    import dlib
    import cv2
    import imutils
    from imutils import face_utils
    img = cv2.imread("./python_examples/126.png")
    mono = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    
    detector = dlib.get_frontal_face_detector()
    rects = detector(mono, 1)
    print(rects)
    exit()
    

    結果が数値で表示される

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

  • Python プログラムの実行

    Python プログラムの実行

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

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

    python
    

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

    cd C:\dlib
    python
    

    次の Python プログラムを実行

    import numpy as np
    import dlib
    import cv2
    import imutils
    from imutils import face_utils
    img = cv2.imread("./python_examples/126.png")
    mono = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    
    detector = dlib.get_frontal_face_detector()
    rects = detector(mono, 1)
    print(rects)
    
    from imutils import face_utils
    
    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)
    
    disp = img.copy()
    predictor = dlib.shape_predictor('python_examples/shape_predictor_68_face_landmarks.dat')
    for (i, rect) in enumerate(rects):
        shape = predictor(mono, rect)
        shape = face_utils.shape_to_np(shape)
        (x, y, w, h) = face_utils.rect_to_bb(rect)
        box_label(disp, x, y, x + w, y + h, str(i))
        j = 0
        for (x, y) in shape:
            j = j + 1
            cv2.putText(disp, str(j), (x, y - 6), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 1)
            cv2.circle(disp, (x, y), 2, (0, 255, 0), -1)
    
    cv2.imshow("", disp)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    exit()
    

    68 ランドマークの結果を表示

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

    右目と左目の情報のみを表示

  • Python プログラムの実行

    Python プログラムの実行

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

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

    python
    

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

    python
    

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

    cd C:\dlib
    python
    

    次の Python プログラムを実行

    「if ( j > 36 and j < 49): 」を追加

    import numpy as np
    import dlib
    import cv2
    import imutils
    from imutils import face_utils
    img = cv2.imread("./python_examples/126.png")
    mono = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    
    detector = dlib.get_frontal_face_detector()
    rects = detector(mono, 1)
    print(rects)
    
    from imutils import face_utils
    
    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)
    
    disp = img.copy()
    predictor = dlib.shape_predictor('python_examples/shape_predictor_68_face_landmarks.dat')
    for (i, rect) in enumerate(rects):
        shape = predictor(mono, rect)
        shape = face_utils.shape_to_np(shape)
        (x, y, w, h) = face_utils.rect_to_bb(rect)
        box_label(disp, x, y, x + w, y + h, str(i))
        j = 0
        for (x, y) in shape:
            j = j + 1
            if ( j > 36 and j < 49):
                cv2.putText(disp, str(j), (x, y - 6), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 1)
                cv2.circle(disp, (x, y), 2, (0, 255, 0), -1)
    
    cv2.imshow("", disp)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    

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

    ビデオで行ってみる

  • Python プログラムの実行

    Python プログラムの実行

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

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

    python
    

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

    cd C:\dlib
    python
    

    次の Python プログラムを実行

    OpenCV による動画表示を行う.

    import numpy as np
    import dlib
    import cv2
    import imutils
    from imutils import face_utils
    
    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)
    
    detector = dlib.get_frontal_face_detector()
    predictor = dlib.shape_predictor('python_examples/shape_predictor_68_face_landmarks.dat')
    
    
    v = cv2.VideoCapture("./python_examples/sample1.mp4")
    while(v.isOpened()):
        r, f = v.read()
        if ( r == False ):
            break
        mono = cv2.cvtColor(f, cv2.COLOR_BGR2GRAY)
        rects = detector(mono, 1)
        for (i, rect) in enumerate(rects):
            shape = predictor(mono, rect)
            shape = face_utils.shape_to_np(shape)
            (x, y, w, h) = face_utils.rect_to_bb(rect)
            box_label(f, x, y, x + w, y + h, str(i))
            j = 0
            for (x, y) in shape:
                j = j + 1
                if ( j > 36 and j < 49):
                    cv2.putText(f, str(j), (x, y - 6), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 1)
                    cv2.circle(f, (x, y), 2, (0, 255, 0), -1)
        cv2.imshow("", f)
        # Press Q to exit
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    
    v.release()
    cv2.destroyAllWindows()
    

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

    ビデオカメラで行ってみる

    今度は、USB接続できるビデオカメラを準備し,パソコンに接続しておく.

    「v = cv2.VideoCapture(0)」のように設定している.他は前のプログラムと同じ

    import numpy as np
    import dlib
    import cv2
    import imutils
    from imutils import face_utils
    
    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)
    
    detector = dlib.get_frontal_face_detector()
    predictor = dlib.shape_predictor('python_examples/shape_predictor_68_face_landmarks.dat')
    
    
    v = cv2.VideoCapture(0)
    while(v.isOpened()):
        r, f = v.read()
        if ( r == False ):
            break
        mono = cv2.cvtColor(f, cv2.COLOR_BGR2GRAY)
        rects = detector(mono, 1)
        for (i, rect) in enumerate(rects):
            shape = predictor(mono, rect)
            shape = face_utils.shape_to_np(shape)
            (x, y, w, h) = face_utils.rect_to_bb(rect)
            box_label(f, x, y, x + w, y + h, str(i))
            j = 0
            for (x, y) in shape:
                j = j + 1
                if ( j > 36 and j < 49):
                    cv2.putText(f, str(j), (x, y - 6), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 1)
                    cv2.circle(f, (x, y), 2, (0, 255, 0), -1)
        cv2.imshow("", f)
        # Press Q to exit
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    
    v.release()
    cv2.destroyAllWindows()
    

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