MMDetection,MMFewShot のインストールと動作確認(画像分類,物体検出)(PyTorch,Python を使用)(Windows 上)

MMClassification は, OpenMMLab の構成物で, Few Shot Classification, Few Shot Detection の機能を提供する.

目次

  1. 前準備
  2. MMDetection, MMFewShot のインストール(Windows 上)
  3. MMFewShot を用いた物体検出の実行(Windows 上)

文献

mmfewshot Contributors, OpenMMLab Few Shot Learning Toolbox and Benchmark, https://github.com/open-mmlab/mmfewshot, 2021.

関連する外部ページ

前準備

Build Tools for Visual Studio 2026 のインストール(Windows 上) [クリックして展開]

Build Tools for Visual Studio は,Visual Studio の IDE を含まない C/C++ コンパイラ,ライブラリ,ビルドツール等のコマンドライン向け開発ツールセットである。インストール済みの場合、この手順は不要である。

管理者権限コマンドプロンプトで以下を実行する。管理者権限のコマンドプロンプトを起動するには、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 Build Tools + Desktop development with C++(VCTools)+ 追加コンポーネント(一括)
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 で追加されるコンポーネント

上記のコマンドでは,まず Build Tools 本体と Visual C++ 再頒布可能パッケージをインストールし,次に setup.exe を用いて以下のコンポーネントを追加している。

インストール完了の確認

winget list Microsoft.VisualStudio.BuildTools

上記以外の追加のコンポーネントが必要になった場合は Visual Studio Installer で個別にインストールできる。

Visual Studio の機能を必要とする場合は、追加インストールできる。

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

以下のいずれかの方法で Python 3.7 をインストールする。Python がインストール済みの場合、この手順は不要である。

方法1:winget によるインストール

管理者権限コマンドプロンプトで以下を実行する。管理者権限のコマンドプロンプトを起動するには、Windows キーまたはスタートメニューから「cmd」と入力し、表示された「コマンドプロンプト」を右クリックして「管理者として実行」を選択する。

winget install -e --id Python.Python.3.7 --scope machine --silent --accept-source-agreements --accept-package-agreements --override "/quiet InstallAllUsers=1 PrependPath=1 AssociateFiles=1 InstallLauncherAllUsers=1"

--scope machine を指定することで、システム全体(全ユーザー向け)にインストールされる。このオプションの実行には管理者権限が必要である。インストール完了後、コマンドプロンプトを再起動すると PATH が自動的に設定される。

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

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

管理者権限コマンドプロンプトで以下を実行する.管理者権限は,winget の --scope machine オプションでシステム全体にインストールするために必要となる.

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

    サイト内の関連ページ

    関連する外部ページ

MMDetection, MMFewShot のインストール(Windows 上)

インストールの方法は複数ある. ここでは, NVIDIA CUDA ツールキットを使うことも考え, インストールしやすい方法として,ソースコードからビルドしてインストールする方法を案内している.

  1. 以下の手順を管理者権限コマンドプロンプトで実行する (手順:Windowsキーまたはスタートメニュー → cmd と入力 → 右クリック → 「管理者として実行」)。
  2. PyTorch がインストールできていることを確認するために,PyTorch のバージョンを表示
    python -c "import torch; TORCH_VERSION = '.'.join(torch.__version__.split('.')[:2]); print(TORCH_VERSION)"
    
  3. PyTorch が NVIDIA CUDA ツールキットを認識できていることを確認するために, PyTorch が認識しているNVIDIA CUDA ツールキット のバージョンを表示

    このとき,実際には 11.8 をインストールしているのに,「cu117」のように古いバージョンが表示されることがある.このような場合は,気にせずに続行する.

    python -c "import torch; CUDA_VERSION = torch.__version__.split('+')[-1]; print(CUDA_VERSION)"
    
  4. MIM,MMDetection のインストール

    インストール手順は, https://mmdetection.readthedocs.io/en/latest/get_started.html による.

    python -m pip install -U --ignore-installed pip
    python -m pip uninstall -y openmim mmcv mmcv-full opencv-python opencv-python-headless
    python -m pip install -U openmim opencv-python
    cd /d c:%HOMEPATH%
    rmdir /s /q mmdetection
    git clone https://github.com/open-mmlab/mmdetection.git
    cd mmdetection
    mim uninstall -y mmdet
    pip install -r requirements.txt
    mim install -e .
    mim list
    

    (途中省略)
  5. MMFewShot のインストール

    Python 3.7 もしくは 3.8 が必要である(2023年4月時点)

    cd /d c:%HOMEPATH%
    rmdir /s /q mmfewshot
    git clone https://github.com/open-mmlab/mmfewshot.git
    cd mmfewshot
    mim uninstall -y mmfewshot
    pip install -r requirements.txt
    mim install -e .
    mim list
    

    (省略)

MMFewShot を用いた物体検出の実行(Windows 上)

セマンティック・セグメンテーション(ImageNet-1k, ResNet50 を使用)

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

    次のコマンドを実行する.

    cd /d c:%HOMEPATH%\mmfewshot
    mkdir checkpoints
    cd checkpoints
    curl -O https://download.openmmlab.com/mmfewshot/detection/attention_rpn/coco/attention-rpn_r50_c4_4xb2_coco_base-training_20211102_003348-da28cdfd.pth
    
  3. セマンティック・セグメンテーションを行う Python プログラム

    次の Python プログラムを実行する.Matplotlib を使うので,Jupyter QtConsoleJupyter ノートブック (Jupyter Notebook) の利用が便利である.

    下のプログラムは作成途中(動作未確認)

    import os
    from mmfewshot.detection.apis import (inference_detector, init_detector, process_support_images)
    
    os.chdir((os.getenv('HOMEPATH') + '\\' + 'mmfewshow'))
    config_file = 'configs/detection/attention_rpn/coco/attention-rpn_r50_c4_4xb2_coco_base-training.py'
    checkpoint_file = 'checkpoints/attention-rpn_r50_c4_4xb2_coco_base-training_20211102_003348-da28cdfd.pth'
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    model = init_detector(config_file,checkpoint_file, device=device)
    
    fsupport_images_dir = 'demo/demo_detection_images/support_images'
    files = os.listdir(fsupport_images_dir)
    support_images = [
        os.path.join(fsupport_images_dir, file) for file in files
    ]
    classes = [file.split('.')[0] for file in files]
    support_labels = [[file.split('.')[0]] for file in files]
    print("support_images")
    display(support_images)
    print("classes")
    display(classes)
    print("support_labels")
    display(support_labels)
    process_support_images(model, support_images, support_labels, classes=classes)
    
    # single image
    img = 'demo/demo_detection_images/query_images/demo_query.jpg'
    fscore_thr = 0.3
    
    # https://mmdetection.readthedocs.io/en/v3.0.0/user_guides/inference.html
    from mmdet.registry import VISUALIZERS
    visualizer = VISUALIZERS.build(model.cfg.visualizer)
    visualizer.dataset_meta = model.dataset_meta
    
    result = inference_detector(model, img)
    image = mmcv.imconvert(mmcv.imread(img), 'bgr', 'rgb')
    visualizer.add_datasample('result', image, data_sample=result, show=False, draw_gt=False)
    mmcv.imshow(visualizer.get_image())