ゼロショットのセグメンテーション(Segment Anything Model,Python,PyTorch を使用)(Windows 上)

元画像と,生成されたセグメンテーションマスク

Segment Anything Model (SAM)

Segment Anything(SA)は、画像セグメンテーションのための基盤モデルを構築することを目的としたプロジェクトである。このプロジェクトでは、新しいデータ分布とタスクに一般化できるプロンプト可能なセグメンテーションモデルSegment Anything Model(SAM)が開発された。Segment Anything Model(SAM)はゼロショットでのセグメンテーションが可能である。さらに、1100万枚以上の画像と、それらの画像に対する10億以上のマスクを含むセグメンテーションデータセットSA-1Bデータセットが構築された。

【文献】

Alexander Kirillov, Eric Mintun, Nikhila Ravi, Hanzi Mao, Chloe Rolland, Laura Gustafson, Tete Xiao, Spencer Whitehead, Alex Berg, Wan-Yen Lo, Piotr Dollar, Ross Girshick, Segment Anything, arXiv:2304.02643, 2023.

https://arxiv.org/pdf/2304.02643v1.pdf

【関連する外部ページ】

【関連項目】 HQ-SAM (Segment Anything in High Quality)

前準備

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 ============================================================
REM Visual C++ 再頒布可能パッケージ (VCRedist 2015-)
REM ============================================================
winget install --scope machine --id Microsoft.VCRedist.2015+.x64 -e --silent --disable-interactivity --force --accept-source-agreements --accept-package-agreements --override "/quiet /norestart"
if not "%ERRORLEVEL%"=="0" ( color 0c & echo VCRedist のインストールに失敗しました & ping 127.0.0.1 -n 6 >nul & color )

REM ============================================================
REM Visual Studio Build Tools + Desktop development with C++
REM (VCTools、MSBuildTools、CMake連携、Clang、Windows 11 SDK)
REM ============================================================
REM 進行中のインストーラーを停止(ロック競合回避。対象プロセスが存在しない場合は
REM taskkillがエラーを返すが、これは想定内であるため出力のみ抑制する)
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
taskkill /F /IM msiexec.exe /T >nul 2>&1

REM Build Tools + Desktop development with C++(VCTools)+ 追加コンポーネント(一括)
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 --add Microsoft.VisualStudio.Component.VC.v143.x86.x64 --includeRecommended --quiet --norestart --nocache
    if not "%ERRORLEVEL%"=="0" ( color 0c & echo Build Tools のコンポーネント追加に失敗しました & ping 127.0.0.1 -n 6 >nul & color )
) 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 --add Microsoft.VisualStudio.Component.VC.v143.x86.x64"
    if not "%ERRORLEVEL%"=="0" ( color 0c & echo Build Tools のインストールに失敗しました & ping 127.0.0.1 -n 6 >nul & color )
)

REM
REM BuildTools のインストールパスを vswhere.exe で取得(メジャーバージョンに依存しない)
set "VSWHERE=C:\Program Files (x86)\Microsoft Visual Studio\Installer\vswhere.exe"
set "BT_PATH="
for /f "usebackq delims=" %P in (`"%VSWHERE%" -products Microsoft.VisualStudio.Product.BuildTools -property installationPath`) do set "BT_PATH=%P"
if not defined BT_PATH ( color 0c & echo Build Tools のインストールパスを取得できませんでした & ping 127.0.0.1 -n 6 >nul & color )

REM 破損時の修復(任意、動作がおかしくなった場合)
REM if defined BT_PATH "C:\Program Files (x86)\Microsoft Visual Studio\Installer\setup.exe" repair --installPath "%BT_PATH%" --quiet --norestart
REM 導入確認(インストールパスが表示されれば正常)
"%VSWHERE%" -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\""
if not "%ERRORLEVEL%"=="0" ( color 0c & echo Python 3.12 のインストールに失敗しました & ping 127.0.0.1 -n 6 >nul & color )

REM Python と Scripts を PATH 先頭に追加
powershell -NoProfile -Command "$p='C:\Program Files\Python312'; $s=\"$p\Scripts\"; if(Test-Path $p){$k=[Microsoft.Win32.Registry]::LocalMachine.OpenSubKey('SYSTEM\CurrentControlSet\Control\Session Manager\Environment',$true); $c=$k.GetValue('Path','',[Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames); $t=$k.GetValueKind('Path'); $new=$c; if((';'+$new+';') -notlike \"*;$p;*\"){$new=$p+';'+$new}; if((';'+$new+';') -notlike \"*;$s;*\"){$new=$s+';'+$new}; if($new -ne $c){$k.SetValue('Path',$new,$t)}; $k.Close()}"

REM 現在のセッションにも反映(システムPATHを再取得して連結)
for /f "usebackq tokens=2,*" %A in (`reg query "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v Path`) do set "PATH=%B"

REM pip / wheel の更新
python -m pip install --no-user -U pip wheel
if not "%ERRORLEVEL%"=="0" ( color 0c & echo pip / wheel の更新に失敗しました & ping 127.0.0.1 -n 6 >nul & color )

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

Git のインストール

管理者権限のコマンドプロンプトで以下を実行する。管理者権限のコマンドプロンプトを起動するには、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"

【関連する外部ページ】

Build Tools for Visual Studio 2022,NVIDIA ドライバ,NVIDIA CUDA ツールキット 11.8,NVIDIA cuDNN 8.9.7 のインストール(Windows 上)

【サイト内の関連ページ】 NVIDIA グラフィックスボードを搭載しているパソコンの場合には, NVIDIA ドライバ, NVIDIA CUDA ツールキット, NVIDIA cuDNN のインストールを行う.

【関連する外部ページ】

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

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

    PyTorch の公式ページ: https://pytorch.org/index.html

  3. 次のようなコマンドを実行(実行するコマンドは,PyTorch のページの表示されるコマンドを使う).

    次のコマンドを実行することにより, PyTorch 2.3 (NVIDIA CUDA 11.8 用)がインストールされる. 但し,Anaconda3を使いたい場合には別手順になる.

    事前に NVIDIA CUDA のバージョンを確認しておくこと(ここでは,NVIDIA CUDA ツールキット 11.8 が前もってインストール済みであるとする).

    PyTorch で,GPU が動作している場合には,「torch.cuda.is_available()」により,True が表示される.

    python -m pip install -U --ignore-installed pip
    python -m pip uninstall -y torch torchvision torchaudio torchtext xformers
    python -m pip install -U torch torchvision torchaudio numpy --index-url https://download.pytorch.org/whl/cu118
    
    python -c "import torch; print(torch.__version__, torch.cuda.is_available())" 
    
    Anaconda3を使いたい場合には, Anaconda プロンプト (Anaconda Prompt) を管理者として実行し, 次のコマンドを実行する. (PyTorch と NVIDIA CUDA との連携がうまくいかない可能性があるため,Anaconda3を使わないことも検討して欲しい).
    conda install -y pytorch torchvision torchaudio pytorch-cuda=11.8 cudnn -c pytorch -c nvidia
    py -c "import torch; print(torch.__version__, torch.cuda.is_available())" 
    

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

    【関連する外部ページ】

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

公式の GitHub ページ: https://github.com/facebookresearch/segment-anything の記載に従う.

  1. 以下の手順を管理者権限のコマンドプロンプトで実行する (手順:Windowsキーまたはスタートメニュー → cmd と入力 → 右クリック → 「管理者として実行」)。
  2. ダウンロードとインストール
    cd /d c:%HOMEPATH%
    rmdir /s /q segment-anything
    git clone --recursive https://github.com/facebookresearch/segment-anything
    cd segment-anything
    python -m pip install -e .
    python -m pip install -U opencv-python pycocotools matplotlib onnxruntime onnx gdown
    mkdir pretrained_checkpoint
    
  3. 終了の確認

    エラーメッセージが出ていないこと.

  4. 学習済みモデルのダウンロード

    学習済みモデルは,公式ページ で公開されている.

    次のコマンドを実行することにより, 公式ページで公開されている学習済みモデル vit_b: ViT-B SAM model, vit_l: ViT-L SAM model, vit_h: ViT-H SAM model をダウンロードする.

    cd /d c:%HOMEPATH%\segment-anything
    cd pretrained_checkpoint
    curl -L -O https://dl.fbaipublicfiles.com/segment_anything/sam_vit_b_01ec64.pth
    curl -L -O https://dl.fbaipublicfiles.com/segment_anything/sam_vit_l_0b3195.pth
    curl -L -O https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth
    
  5. 動作確認のためデモを実行.
    cd /d c:%HOMEPATH%\segment-anything
    python -m pip install -U timm
    python scripts/amg.py --checkpoint ./pretrained_checkpoint/sam_vit_l_0b3195.pth --model-type vit_l --input ./notebooks/images --output ./results
    
  6. 実行の結果,エラーメッセージが出ないことを確認

    元画像の画像ファイルは,notebooks\images にある

    結果の画像ファイルは,results にある

ゼロショットのセグメンテーションの実行(Segment Anything Model,Python,PyTorch を使用)(Windows 上)

画像全体からセグメンテーション・マスクを生成(Segment Anythingを使用)(Windows 上)

実行時にファイルを選択する.ファイルは複数選択可能である.

  1. Windows で,コマンドプロンプトを実行
  2. エディタを起動
    cd /d c:%HOMEPATH%\segment-anything
    notepad segment.py
    
  3. エディタで,次のプログラムを保存

    このプログラムは,公式の Sement Anything のページで公開されていたものを参考に作成.

    from segment_anything import SamAutomaticMaskGenerator, sam_model_registry
    import numpy as np
    import torch
    import matplotlib.pyplot as plt
    import cv2
    import tkinter as tk
    from tkinter import filedialog
    
    def main():
        sam_checkpoint = "./pretrained_checkpoint/sam_vit_h_4b8939.pth"
        model_type = "vit_h"  # "vit_l/vit_b/vit_h"
        device = "cuda"
    
        sam = sam_model_registry[model_type](checkpoint=sam_checkpoint)
        sam.to(device=device)
        mask_generator = SamAutomaticMaskGenerator(sam)
    
        root = tk.Tk()
        root.withdraw()
        fpaths = filedialog.askopenfilenames()
    
        def show_anns(anns):
            if len(anns) == 0:
                return
            sorted_anns = sorted(anns, key=(lambda x: x['area']), reverse=True)
            ax = plt.gca()
            ax.set_autoscale_on(False)
    
            img = np.ones((sorted_anns[0]['segmentation'].shape[0], sorted_anns[0]['segmentation'].shape[1], 4))
            img[:, :, 3] = 0
            for ann in sorted_anns:
                m = ann['segmentation']
                color_mask = np.concatenate([np.random.random(3), [0.35]])
                img[m] = color_mask
            ax.imshow(img)
    
        i = 0
        for fpath in root.tk.splitlist(fpaths):
            print("file name: ", fpath)
            bgr = cv2.imread(fpath)
            rgb = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB)
            plt.figure(figsize=(20, 20))
            plt.imshow(rgb)
            plt.axis('off')
            plt.show()
    
            masks = mask_generator.generate(rgb)
            plt.figure(figsize=(20, 20))
            plt.imshow(rgb)
            show_anns(masks)
            plt.axis('off')
            plt.savefig(str(i) + ".png", bbox_inches='tight', pad_inches=0, transparent=True)
            print(str(i) + ".png" + " saved.")
            plt.show()
            plt.close()  # グラフを閉じる
            i = i + 1
    
    if __name__ == "__main__":
        main()
    
  4. Python プログラムの実行
    Python プログラムの実行

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

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

    プログラムを segment.pyのようなファイル名で保存したので, 「python segment.py」のようなコマンドで行う.

    python segment.py
    
  5. ファイル選択画面が出るので,画像ファイルを選択する.画像ファイルは複数選択可能である.
  6. 元画像が表示される.

    確認したら,右上の「x」をクリックする.右上の「x」をクリックするまでは,プログラム実行は中断している.

  7. しばらく待つと,セグメンテーション・マスクが表示される.

    確認したら,右上の「x」をクリックする.右上の「x」をクリックするまでは,プログラム実行は中断している.

  8. セグメンテーション・マスクは,画像ファイルにも保存される.

    ファイル名は,0.png, 1.png, 2.png, ... のようになっている.

パソコンのビデオカメラ

パソコンのビデオカメラで実行する.

  1. Windows で,コマンドプロンプトを実行
  2. エディタを起動
    cd /d c:%HOMEPATH%\segment-anything
    notepad vidcam.py
    
  3. エディタで,次のプログラムを保存

    このプログラムは,公式の Sement Anything のページで公開されていたものを参考に作成.

    学習済みモデルは最も軽量なものを選んでいる.

    from segment_anything import SamAutomaticMaskGenerator, sam_model_registry
    import numpy as np
    import torch
    import matplotlib.pyplot as plt
    import cv2
    
    def main():
        sam_checkpoint = "./pretrained_checkpoint/sam_vit_b_01ec64.pth"
        model_type = "vit_b"  # "vit_l/vit_b/vit_h"
        device = "cuda"
    
        sam = sam_model_registry[model_type](checkpoint=sam_checkpoint)
        sam.to(device=device)
        mask_generator = SamAutomaticMaskGenerator(sam)
    
        def get_anns(anns):
            if len(anns) == 0:
                return
            sorted_anns = sorted(anns, key=(lambda x: x['area']), reverse=True)
            ax = plt.gca()
            ax.set_autoscale_on(False)
    
            img = np.ones((sorted_anns[0]['segmentation'].shape[0], sorted_anns[0]['segmentation'].shape[1], 4))
            img[:, :, 3] = 0
            for ann in sorted_anns:
                m = ann['segmentation']
                color_mask = np.concatenate([np.random.random(3), [0.35]])
                img[m] = color_mask
            return img
    
        print("Prease press q to exit")
        cap = cv2.VideoCapture(0)
        while (cap.isOpened()):
            r, f = cap.read()
            if (r == False):
                print("Video Capture Error")
                break
            else:
                cv2.imshow('Video Capture', f)
                if cv2.waitKey(1) & 0xFF == ord('q'):
                    break
                masks = mask_generator.generate(f)
                img = get_anns(masks)
                cv2.imshow('SAM Result', img)
                if cv2.waitKey(1) & 0xFF == ord('q'):
                    break
    
        cap.release()
        cv2.destroyAllWindows()
    
    if __name__ == "__main__":
        main()
    
  4. Python プログラムの実行
    Python プログラムの実行

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

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

    プログラムを vidcam.pyのようなファイル名で保存したので, 「python vidcam.py」のようなコマンドで行う.

    python vidcam.py
    
  5. ビデオカメラの画像の画面と処理結果の画像の画面が出るので確認

    q キーで終了する.