imglab を用いた画像のアノテーション(Dlib, Dlib の imglab, Python を使用)(Windows 上)

概要

Dlibは,機械学習のアルゴリズムの機能を持つソフトウェアである.

利用条件などは利用者において確認してください.

謝辞:Dlib の作者に感謝します.

目次

サイト内の関連情報

前準備

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 の機能を必要とする場合は,追加インストールできる。

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"

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

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

REM CMake をシステム領域にインストール
winget install --scope machine --id Kitware.CMake -e --silent --disable-interactivity --force --accept-source-agreements --accept-package-agreements --override "/qn /norestart ADD_CMAKE_TO_PATH=System"

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')}"

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

Dlib のインストール

  1. 以下の手順を管理者権限コマンドプロンプトで実行する (手順:Windowsキーまたはスタートメニュー → cmd と入力 → 右クリック → 「管理者として実行」)。
  2. Windowspip を実行するときは,管理者権限コマンドプロンプトを使用し,システム領域へのインストールを行う.
  3. 次のコマンドを実行する.
    python -m pip install -U --no-user dlib
    

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

  1. 以下の手順を管理者権限コマンドプロンプトで実行する (手順:Windowsキーまたはスタートメニュー → cmd と入力 → 右クリック → 「管理者として実行」)。
  2. Dlib のソースコード等のダウンロード

    次のコマンドを実行.

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

Pythonのnumpy、scikit-imageライブラリのインストール

Windows の場合

  1. 以下の手順を管理者権限コマンドプロンプトで実行する (手順:Windowsキーまたはスタートメニュー → cmd と入力 → 右クリック → 「管理者として実行」)。
  2. Windowspip を実行するときは,管理者権限コマンドプロンプトを使用し,システム領域へのインストールを行う.
  3. 次のコマンドを実行する.
    python -m pip install -U --no-user numpy scikit-image
    

Ubuntu の場合

Ubuntu を使用する場合は,次のように操作する.

# パッケージリストの情報を更新
sudo apt update
sudo apt -y install python3-numpy python3-skimage

Dlib の imglab のインストール

前準備として、Windows のときは マイクロソフト C++ ビルドツール (Build Tools) のインストールが終わっていること

  1. 以下の手順を管理者権限コマンドプロンプトで実行する (手順:Windowsキーまたはスタートメニュー → cmd と入力 → 右クリック → 「管理者として実行」)。
  2. 次のコマンドを実行
    cd C:\dlib
    cd tools\imglab
    rmdir /s /q build
    mkdir build
    cd build
    cmake -A x64 -T host=x64 ^
        -DCMAKE_INSTALL_PREFIX="%HOMEPATH%\dlib" ..
    cmake --build . --config Release --target INSTALL -- /m:4
    

結果を確認.エラーメッセージが出ていないこと

ここで,「%HOMEPATH%\dlib」は,Dlib のソースコードを展開したディレクトリに読み替えること。

imglab を使ってみる

  1. 画像を数枚準備する
  2. 準備した画像ファイルを,次のディレクトリに置く
    %HOMEPATH%\dlib\bin
    
  3. 画像ファイルの準備が終わったら、 .xml 形式ファイルを作る.

    Windowsコマンドプロンプトを開き,次のコマンドを実行する.エラーメッセージが出ないことを確認.

    「.\imglab.exe -c mydata.xml .」は、.xml 形式ファイルを作るコマンド.ファイル名 mydata.xml は何でもよい

    C:
    cd C:\dlib\bin
    .\imglab.exe -c mydata.xml .
    
  4. 生成された .xml 形式ファイルをエディタなどで開き確認してみる.
    notepad mydata.xml
    
  5. imglab を起動してみる

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

    .\imglab.exe mydata.xml
    

    imglab は,画像ビューワになっている

    • 複数の画像を簡単に表示できる機能がある。
    • ラベル(label)を編集する機能がある (Next Labelのところに書き込む)
    • 領域を指定する機能がある (シフトキー(SHIFT キー)を押しながら、マウスをドラッグ
  6. imglab で、領域を指定してみる

    シフトキー(SHIFT キー)を押しながら、マウスをドラッグ

  7. 保存する

    File」→「Save」と操作する

  8. 確かに .xml形式ファイルに,結果が保存される

    指定した領域についての情報が保存される

Dlib を用いた学習

  1. 教材ファイル Release.zip をダウンロードし,%HOMEPATH%\dlib\bin に置く
    C:
    cd C:\dlib\bin
    curl -O https://www.kkaneko.jp/sample/dog/Release.zip
    "c:\Program Files\7-Zip\7z.exe" x Release.zip
    
  2. Web ブラウザで training.xml を開いて、確認してみる

    14枚の画像について、 領域を指定済み

    Google Chrome ではうまく表示できない.下の図では Firefox での表示結果を示している.

  3. imglab を起動して確認してみる

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

    C:
    cd C:\dlib\bin
    .\imglab.exe training.xml
    
  4. imglab を閉じる
  5. 学習を行う(教師データの生成)

    最後の「.」を忘れないこと

    copy %HOMEPATH%\dlib\examples\faces\*.jpg .
    python C:\dlib\python_examples\train_object_detector.py .
    
  6. 途中で、Enterキーを押して続行
  7. Python プログラムの実行

    謝辞:http://tadaoyamaoka.hatenablog.com/entry/2016/09/21/184955 のものを参考に(少し変更して)使っています

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

    python
    

    次の Python プログラムを実行

    import dlib
    
    f = '5920652345_5be61ae940.jpg'
    
    detector = dlib.simple_object_detector("detector.svm")
    
    win_det = dlib.image_window()
    win_det.set_image(detector)
    
    win = dlib.image_window()
    
    print("Processing file: {}".format(f))
    img = dlib.load_rgb_image(f)
    dets = detector(img)
    print("Number of objects detected: {}".format(len(dets)))
    for k, d in enumerate(dets):
        print("Detection {}: Left: {} Top: {} Right: {} Bottom: {}".format(
            k, d.left(), d.top(), d.right(), d.bottom()))
    
    win.clear_overlay()
    win.set_image(img)
    win.add_overlay(dets)
    dlib.hit_enter_to_continue()
    

    上の犬の写真では、画像分類がうまくいっていない

  8. 学習に使う画像を増やすには
    .\imglab training.xml