ゼロショットのセグメンテーション(HQ-SAM,Light HQ-SAM,Python,PyTorch を使用)(Windows 上)
【目次】
- 前準備
- Segment Anything in High Quality のインストール(Windows 上)
- ゼロショットのセグメンテーションの実行(HQ-SAM,Python,PyTorch を使用)(Windows 上)
元画像と,生成されたセグメンテーションマスク
HQ-SAM (Segment Anything in High Quality)
HQ-SAMは、既存のSAM(Segment Anything Model)を拡張し、より高精度なゼロショットセグメンテーションを実現する手法である。SAMは、プロンプト(点、バウンディングボックス、粗いマスクなど)を入力として、多様なオブジェクトや視覚構造のセグメンテーションを可能にするモデルである。しかし、SAMは細かい構造を持つオブジェクトに対するセグメンテーションが不十分で、その精度に限界がある。この問題を解決するために、HQ-SAMはSAMを拡張している。HQ-SAMでは、SAMのマスクデコーダに新しい学習可能な「HQ-Output Token」を導入している。さらに、グローバルなセマンティックコンテキストとローカルな境界(バウンダリ)の詳細を両方考慮する「Global-local Feature Fusion」も導入されている。複数のデータセットでの実験により、HQ-SAMが高精度なセグメンテーションマスクを生成できることが確認されている。
【文献】 Ke, Lei and Ye, Mingqiao and Danelljan, Martin and Liu, Yifan and Tai, Yu-Wing and Tang, Chi-Keung and Yu, Fisher, Segment Anything in High Quality, arXiv:2306.01567, 2023.
https://arxiv.org/pdf/2306.01567v1.pdf
【関連する外部ページ】
- 公式の GitHub ページ: https://github.com/SysCV/sam-hq
- HQ-SAM (ゼロショットのセグメンテーション)のオンラインデモ(Hugging Face上): https://huggingface.co/spaces/sam-hq-team/sam-hq
- HQ-SAM (ゼロショットのセグメンテーション)のオンラインデモ(Google Colaboratory 上): https://colab.research.google.com/drive/1QwAbn5hsdqKOD5niuBzuqQX4eLCbNKFL?usp=sharing
- Paper with Code のページ: https://paperswithcode.com/paper/segment-anything-in-high-quality
【関連項目】 SAM (Segment Anything Model)
前準備
Build Tools for Visual Studio 2022 のインストール(Windows 上)
Build Tools for Visual Studio は,Visual Studio の IDE を含まない C/C++ コンパイラ,ライブラリ,ビルドツール等のコマンドライン向け開発ツールセットである。
以下のコマンドを管理者権限のコマンドプロンプトで実行する
(手順:Windowsキーまたはスタートメニュー → cmd と入力 → 右クリック → 「管理者として実行」)。
REM VC++ ランタイム
winget install --scope machine --accept-source-agreements --accept-package-agreements --silent --id Microsoft.VCRedist.2015+.x64
REM Build Tools + Desktop development with C++(VCTools)+ 追加コンポーネント(一括)
winget install --id Microsoft.VisualStudio.2022.BuildTools ^
--override "--passive --wait --add Microsoft.VisualStudio.Workload.VCTools --includeRecommended --add Microsoft.VisualStudio.Component.VC.Llvm.Clang --add Microsoft.VisualStudio.ComponentGroup.ClangCL --add Microsoft.VisualStudio.Component.VC.CMake.Project --add Microsoft.VisualStudio.Component.Windows11SDK.26100"
--add で追加されるコンポーネント
上記のコマンドでは,まず Build Tools 本体と Visual C++ 再頒布可能パッケージをインストールし,次に setup.exe を用いて以下のコンポーネントを追加している。
VCTools:C++ デスクトップ開発ワークロード(--includeRecommendedにより、MSVC コンパイラ、C++ AddressSanitizer、vcpkg、CMake ツール、Windows 11 SDK 等の推奨コンポーネントが含まれる)VC.Llvm.Clang:Windows 向け C++ Clang コンパイラClangCL:clang-cl ツールセットを含むコンポーネントグループ(MSBuild から Clang を使用するために必要)VC.CMake.Project:Windows 向け C++ CMake ツールWindows11SDK.26100:Windows 11 SDK(ビルド 10.0.26100)
インストール完了の確認
winget list Microsoft.VisualStudio.2022.BuildTools
上記以外の追加のコンポーネントが必要になった場合は Visual Studio Installer で個別にインストールできる。
Visual Studio の機能を必要とする場合は、追加インストールできる。
Python 3.12,Git のインストール(Windows 上)
Pythonは,プログラミング言語の1つ. Gitは,分散型のバージョン管理システム.
【手順】
- Windows で,管理者権限でコマンドプロンプトを起動(手順:Windowsキーまたはスタートメニュー >
cmdと入力 > 右クリック > 「管理者として実行」)。次のコマンドを実行
次のコマンドは,Python ランチャーとPython 3.12とGitをインストールし,Gitにパスを通すものである.
次のコマンドでインストールされるGitは 「git for Windows」と呼ばれるものであり, Git,MinGW などから構成されている.
reg add "HKLM\SYSTEM\CurrentControlSet\Control\FileSystem" /v LongPathsEnabled /t REG_DWORD /d 1 /f REM Python, Git をシステム領域にインストール winget install --scope machine --id Python.Python.3.12 --id Python.Launcher --id Git.Git -e --silent REM Python のパス set "INSTALL_PATH=C:\Program Files\Python312" echo "%PATH%" | find /i "%INSTALL_PATH%" >nul if errorlevel 1 setx PATH "%PATH%;%INSTALL_PATH%" /M >nul echo "%PATH%" | find /i "%INSTALL_PATH%\Scripts" >nul if errorlevel 1 setx PATH "%PATH%;%INSTALL_PATH%\Scripts" /M >nul REM Git のパス set "NEW_PATH=C:\Program Files\Git\cmd" if exist "%NEW_PATH%" echo "%PATH%" | find /i "%NEW_PATH%" >nul if exist "%NEW_PATH%" if errorlevel 1 setx PATH "%PATH%;%NEW_PATH%" /M >nul
【関連する外部ページ】
- Python の公式ページ: https://www.python.org/
- Git の公式ページ: https://git-scm.com/
【サイト内の関連ページ】
【関連項目】 Python, Git バージョン管理システム, Git の利用
Build Tools for Visual Studio 2022,NVIDIA ドライバ,NVIDIA CUDA ツールキット 11.8,NVIDIA cuDNN 8.9.7 のインストール(Windows 上)
【サイト内の関連ページ】 NVIDIA グラフィックスボードを搭載しているパソコンの場合には, NVIDIA ドライバ, NVIDIA CUDA ツールキット, NVIDIA cuDNN のインストールを行う.
- Windows での Build Tools for Visual Studio 2022 のインストール: 別ページ »で説明
- Windows での NVIDIA ドライバ,NVIDIA CUDA ツールキット 11.8,NVIDIA cuDNN v8.9.7 のインストール手順: 別ページ »で説明
【関連する外部ページ】
- Build Tools for Visual Studio 2022 (ビルドツール for Visual Studio 2022)の公式ダウンロードページ: https://visualstudio.microsoft.com/ja/visual-cpp-build-tools/
- NVIDIA ドライバのダウンロードの公式ページ: https://www.nvidia.co.jp/Download/index.aspx?lang=jp
- NVIDIA CUDA ツールキットのアーカイブの公式ページ: https://developer.nvidia.com/cuda-toolkit-archive
- NVIDIA cuDNN のダウンロードの公式ページ: https://developer.nvidia.com/cudnn
PyTorch のインストール(Windows 上)
- Windows で,管理者権限でコマンドプロンプトを起動(手順:Windowsキーまたはスタートメニュー >
cmdと入力 > 右クリック > 「管理者として実行」)。 - PyTorch のページを確認
- 次のようなコマンドを実行(実行するコマンドは,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())"【サイト内の関連ページ】
【関連する外部ページ】
Segment Anything in High Quality のインストール(Windows 上)
公式の GitHub ページ: https://github.com/SysCV/sam-hq の記載に従う.
- Windows で,管理者権限でコマンドプロンプトを起動(手順:Windowsキーまたはスタートメニュー >
cmdと入力 > 右クリック > 「管理者として実行」)。 - ダウンロードとインストール
cd /d c:%HOMEPATH% rmdir /s /q sam-hq git clone --recursive https://github.com/syscv/sam-hq cd sam-hq python -m pip install -e . python -m pip install -U opencv-python pycocotools matplotlib onnxruntime onnx gdown mkdir pretrained_checkpoint - 終了の確認
エラーメッセージが出ていないこと.
- 学習済みモデルのダウンロード
学習済みモデルは,公式ページ https://github.com/SysCV/sam-hq で公開されている.
次のコマンドを実行することにより, 公式ページで公開されている学習済みモデル vit_b: ViT-B HQ-SAM model, vit_l: ViT-L HQ-SAM model, vit_h: ViT-H HQ-SAM model, vit_tiny (Light HQ-SAM for real-time need): ViT-Tiny HQ-SAM model をダウンロードする.
cd /d c:%HOMEPATH%\sam-hq cd pretrained_checkpoint curl -L -O https://huggingface.co/lkeab/hq-sam/resolve/main/sam_hq_vit_b.pth curl -L -O https://huggingface.co/lkeab/hq-sam/resolve/main/sam_hq_vit_l.pth curl -L -O https://huggingface.co/lkeab/hq-sam/resolve/main/sam_hq_vit_h.pth curl -L -O https://huggingface.co/lkeab/hq-sam/resolve/main/sam_hq_vit_tiny.pth
- 動作確認のためデモを実行.
cd /d c:%HOMEPATH%\sam-hq python -m pip install -U timm python demo\demo_hqsam.py - 実行の結果,エラーメッセージが出ないことを確認
元画像の画像ファイルは,demo\input_imgs にある
結果の画像ファイルは,demo\hq_sam_result にある
ゼロショットのセグメンテーションの実行(HQ-SAM,Python,PyTorch を使用)(Windows 上)
画像全体からセグメンテーション・マスクを生成(HQ-SAMを使用)(Windows 上)
実行時にファイルを選択する.ファイルは複数選択可能である.
- Windows で,コマンドプロンプトを実行
- エディタを起動
cd /d c:%HOMEPATH%\sam-hq notepad segment.py - エディタで,次のプログラムを保存
このプログラムは,公式の Sement Anything のページで公開されていたものを参考に作成.
from segment_anything import SamAutomaticMaskGenerator, sam_model_registry sam_checkpoint = "./pretrained_checkpoint/sam_hq_vit_h.pth" model_type = "vit_h" #"vit_l/vit_b/vit_h/vit_tiny" device = "cuda" sam = sam_model_registry[model_type](checkpoint=sam_checkpoint) sam.to(device=device) mask_generator = SamAutomaticMaskGenerator(sam) import numpy as np import torch import matplotlib.pyplot as plt import cv2 import tkinter as tk from tkinter import filedialog 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
- Python プログラムの実行
Python プログラムの実行
- Windows では python (Python ランチャーは py)
- Ubuntu では python3
Python 開発環境(Jupyter Qt Console, Jupyter ノートブック (Jupyter Notebook), Jupyter Lab, Nteract, Spyder, PyCharm, PyScripterなど)も便利である.
Python のまとめ: 別ページ »にまとめ
プログラムを segment.pyのようなファイル名で保存したので, 「python segment.py」のようなコマンドで行う.
python segment.py
- ファイル選択画面が出るので,画像ファイルを選択する.画像ファイルは複数選択可能である.
- 元画像が表示される.
確認したら,右上の「x」をクリックする.右上の「x」をクリックするまでは,プログラム実行は中断している.
- しばらく待つと,セグメンテーション・マスクが表示される.
確認したら,右上の「x」をクリックする.右上の「x」をクリックするまでは,プログラム実行は中断している.
- セグメンテーション・マスクは,画像ファイルにも保存される.
ファイル名は,0.png, 1.png, 2.png, ... のようになっている.
パソコンのビデオカメラ
パソコンのビデオカメラで実行する.
- Windows で,コマンドプロンプトを実行
- エディタを起動
cd /d c:%HOMEPATH%\sam-hq notepad vidcam.py
- エディタで,次のプログラムを保存
このプログラムは,公式の Sement Anything のページで公開されていたものを参考に作成.
最も軽量である vit_tiny (Light HQ-SAM for real-time need): ViT-Tiny HQ-SAM model を使用.
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_hq_vit_tiny.pth" model_type = "vit_tiny" #"vit_l/vit_b/vit_h/vit_tiny" 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()
- Python プログラムの実行
Python プログラムの実行
- Windows では python (Python ランチャーは py)
- Ubuntu では python3
Python 開発環境(Jupyter Qt Console, Jupyter ノートブック (Jupyter Notebook), Jupyter Lab, Nteract, Spyder, PyCharm, PyScripterなど)も便利である.
Python のまとめ: 別ページ »にまとめ
プログラムを vidcam.pyのようなファイル名で保存したので, 「python vidcam.py」のようなコマンドで行う.
python vidcam.py
- ビデオカメラの画像の画面と処理結果の画像の画面が出るので確認
q キーで終了する.
プロンプトを指定してからセグメンテーション・マスクを生成(HQ-SAMを使用)(Windows 上)
使い方:「masks, scores, logits = predictor.predict()」の引数にプロンプトを設定.実行したらファイルを選択.画像を確認したら,画像をクリックした後,キーボードのキーをクリックして次に進む
import cv2 import numpy as np from segment_anything import SamPredictor, sam_model_registry sam_checkpoint = "./pretrained_checkpoint/sam_hq_vit_h.pth" model_type = "vit_h" device = "cuda" sam = sam_model_registry[model_type](checkpoint=sam_checkpoint) sam.to(device=device) predictor = SamPredictor(sam) import tkinter as tk from tkinter import filedialog root = tk.Tk() root.withdraw() fpaths = filedialog.askopenfilenames() for fpath in root.tk.splitlist(fpaths): print("file name: ", fpath) bgr = cv2.imread(fpath) rgb = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB) cv2.imshow("1", rgb) print("press a key to continue") cv2.waitKey(0) predictor.set_image(rgb) masks, scores, logits = predictor.predict( point_coords=None, point_labels=None, box = None, multimask_output=False, hq_token_only= False, ) opencv_mat = cv2.cvtColor(masks[0].astype(np.uint8) * 255, cv2.COLOR_GRAY2BGR) cv2.imshow("2", opencv_mat) print("press a key to continue") cv2.waitKey(0) cv2.destroyAllWindows() - Windows で,管理者権限でコマンドプロンプトを起動(手順:Windowsキーまたはスタートメニュー >