金子邦彦研究室人工知能Windows でのインストールと動作確認(人工知能関係)Detectron2 による物体検出,インスタンス・セグメンテーション(Detectron2,PyTorch, Python を使用)(Windows 上)

Detectron2 による物体検出,インスタンス・セグメンテーション(Detectron2,PyTorch, Python を使用)(Windows 上)

Detectron2 のインストールと動作確認を行う.

目次

  1. 前準備
  2. Detectron2 のインストール(Windows 上)
  3. Detectron2 の物体検出,インスタンス・セグメンテーションのPython プログラム

文献

Yuxin Wu and Alexander Kirillov and Francisco Massa and Wan-Yen Lo and Ross Girshick, Detectron2, https://github.com/facebookresearch/detectron2, 2019.

関連する外部ページ

前準備

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

Windows での Git のインストール: 別ページ »で説明

関連する外部ページ

Git の公式ページ: https://git-scm.com/

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

Windows での Python 3.10,関連パッケージ,Python 開発環境のインストール: 別ページ »で説明

サイト内の関連ページ

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

関連する外部ページ

Python の公式ページ: https://www.python.org/

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

Windows での Build Tools for Visual Studio 2022NVIDIA ドライバNVIDIA CUDA ツールキット 11.8,NVIDIA cuDNN v8.6 のインストールと動作確認: 別ページ »で説明

関連する外部ページ

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

  1. Windows で,コマンドプロンプト管理者として実行

    コマンドプロンプトを管理者として実行: 別ページ »で説明

  2. PyTorch のページを確認

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

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

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

    python -m pip install -U pip
    python -m pip install -U torch torchvision torchaudio numpy numba --index-url https://download.pytorch.org/whl/cu118
    python -c "import torch; print(torch.__version__, torch.cuda.is_available())" 
    

    (途中省略)
    [image]

Python の opencv-python のインストール

  1. Windows で,コマンドプロンプト管理者として実行

    コマンドプロンプトを管理者として実行: 別ページ »で説明

  2. opencv-python のインストール

    ※ 「pip install ...」は,Python パッケージをインストールするための操作

    python -m pip install -U opencv-python opencv-contrib-python
    

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

次の記事に記載の手順による.

https://dgmaxime.medium.com/how-to-easily-install-detectron2-on-windows-10-39186139101c

  1. Windows で,コマンドプロンプト管理者として実行

    コマンドプロンプトを管理者として実行: 別ページ »で説明

  2. cython のインストール
    python -m pip install cython
    
  3. pycocotools のインストール
    python -m pip install "git+https://github.com/philferriere/cocoapi.git#egg=pycocotools&subdirectory=PythonAPI"
    
  4. Detectron2 のインストールと動作確認

    https://github.com/DGMaxime/detectron2-windows を使用している.

    python -m pip uninstall detectron2
    cd %HOMEPATH%
    rmdir /s /q detectron2-windows
    git clone --recursive https://github.com/DGMaxime/detectron2-windows.git
    cd detectron2-windows
    python -m pip install -e .
    python tests\test_windows_install.py
    
  5. 結果の確認

    [image]

    結果が,次のように表示される.

    [image]
  6. 引き続き,COCO 2018 Panoptic Segmentation Task API, The Cityscapes Dataset 用スクリプトのインストール
    pip install git+https://github.com/cocodataset/panopticapi.git
    pip install git+https://github.com/mcordts/cityscapesScripts.git
    

    [image]

Detectron2 の物体検出,インスタンス・セグメンテーションのPython プログラム

画像の準備

coco (common object in context) データセットの中の画像ファイルをダウンロード

https://colab.research.google.com/drive/16jcaJoc6bCFAQ96jDe2HwtXj7BMD_-m5#scrollTo=FsePPpwZSmqt の記載による

cd %HOMEPATH%\detectron2-windows
curl -O http://images.cocodataset.org/val2017/000000439715.jpg

[image]

物体検出

  1. Windows のコマンドプロンプトを開く
  2. Python プログラムを実行する

    Python プログラムの実行: 別ページ »で説明

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

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

    cd %HOMEPATH%\detectron2-windows
    python
    

    次の Python プログラムを実行する

    Python プログラムの実行: 別ページ »で説明

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

    RetinaNet, R101, FPN, 3x による物体検出. COCO データセットによる学習済みモデルを使用.

    https://colab.research.google.com/drive/16jcaJoc6bCFAQ96jDe2HwtXj7BMD_-m5#scrollTo=FsePPpwZSmqt のプログラムをもとに作成

    Detectron2 の学習済みモデルは https://github.com/facebookresearch/detectron2/blob/main/MODEL_ZOO.md

    「im = cv2.imread('000000439715.jpg')」で,処理したい画像ファイルをロードしている.

    import detectron2
    from detectron2 import model_zoo
    from detectron2.engine import DefaultPredictor
    from detectron2.config import get_cfg
    from detectron2.utils.visualizer import Visualizer
    from detectron2.data import MetadataCatalog, DatasetCatalog
    
    def setup_config(configfile):
        cfg = get_cfg()
        # add project-specific config (e.g., TensorMask) here if you're not running a model in detectron2's core library
        cfg.merge_from_file(model_zoo.get_config_file(configfile))
        cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.5  # set threshold for this model
        # Find a model from detectron2's model zoo. You can use the https://dl.fbaipublicfiles... url as well
        cfg.MODEL.WEIGHTS = model_zoo.get_checkpoint_url(configfile)
        return cfg
    
    def look_instance(outputs):
        # インスタンス・セグメンテーションの結果の確認
        # look at the outputs. See https://detectron2.readthedocs.io/tutorials/models.html#model-output-format for specification
        print(outputs["instances"].pred_classes)
        print(outputs["instances"].pred_boxes)
    
    def visualize_instance(im, cfg, outputs):
        # 画面表示
        # We can use `Visualizer` to draw the predictions on the image.
        v = Visualizer(im[:, :, ::-1], MetadataCatalog.get(cfg.DATASETS.TRAIN[0]), scale=1.2)
        out = v.draw_instance_predictions(outputs["instances"].to("cpu"))
        cv2.imshow("", out.get_image()[:, :, ::-1])
        cv2.waitKey(15)
    
    import cv2
    im = cv2.imread('000000439715.jpg')
    cfg = setup_config('COCO-Detection/retinanet_R_101_FPN_3x.yaml')
    predictor = DefaultPredictor(cfg)
    outputs = predictor(im)
    look_instance(outputs)
    visualize_instance(im, cfg, outputs)
    

    [image]

    [image]

インスタンス・セグメンテーションのPython プログラム (COCO データセット)

  1. Windows のコマンドプロンプトを開く
  2. Python プログラムを実行する

    Python プログラムの実行: 別ページ »で説明

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

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

    cd %HOMEPATH%\detectron2-windows
    python
    

    次の Python プログラムを実行する

    Mask-RCNN, R101, FPN, 3x によるインスタンス・セグメンテーション. COCO データセットによる学習済みモデルを使用.

    https://colab.research.google.com/drive/16jcaJoc6bCFAQ96jDe2HwtXj7BMD_-m5#scrollTo=FsePPpwZSmqt のプログラムをもとに作成

    Detectron2 の学習済みモデルは https://github.com/facebookresearch/detectron2/blob/main/MODEL_ZOO.md

    「im = cv2.imread('000000439715.jpg')」で,処理したい画像ファイルをロードしている.

    import detectron2
    from detectron2 import model_zoo
    from detectron2.engine import DefaultPredictor
    from detectron2.config import get_cfg
    from detectron2.utils.visualizer import Visualizer
    from detectron2.data import MetadataCatalog, DatasetCatalog
    
    def setup_config(configfile):
        cfg = get_cfg()
        # add project-specific config (e.g., TensorMask) here if you're not running a model in detectron2's core library
        cfg.merge_from_file(model_zoo.get_config_file(configfile))
        cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.5  # set threshold for this model
        # Find a model from detectron2's model zoo. You can use the https://dl.fbaipublicfiles... url as well
        cfg.MODEL.WEIGHTS = model_zoo.get_checkpoint_url(configfile)
        return cfg
    
    def look_instance(outputs):
        # インスタンス・セグメンテーションの結果の確認
        # look at the outputs. See https://detectron2.readthedocs.io/tutorials/models.html#model-output-format for specification
        print(outputs["instances"].pred_classes)
        print(outputs["instances"].pred_boxes)
    
    def visualize_instance(im, cfg, outputs):
        # 画面表示
        # We can use `Visualizer` to draw the predictions on the image.
        v = Visualizer(im[:, :, ::-1], MetadataCatalog.get(cfg.DATASETS.TRAIN[0]), scale=1.2)
        out = v.draw_instance_predictions(outputs["instances"].to("cpu"))
        cv2.imshow("", out.get_image()[:, :, ::-1])
        cv2.waitKey(15)
    
    import cv2
    im = cv2.imread('000000439715.jpg')
    cfg = setup_config('COCO-InstanceSegmentation/mask_rcnn_R_101_FPN_3x.yaml')
    predictor = DefaultPredictor(cfg)
    outputs = predictor(im)
    look_instance(outputs)
    visualize_instance(im, cfg, outputs)
    

    [image]

    [image]

パノプティック・セグメンテーションのPython プログラム

  1. Windows のコマンドプロンプトを開く
  2. Python プログラムを実行する

    Python プログラムの実行: 別ページ »で説明

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

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

    cd %HOMEPATH%\detectron2-windows
    python
    

    次の Python プログラムを実行する

    Panoptic FPN, R101, 3x によるパノプティック・セグメンテーション. COCO データセットによる学習済みモデルを使用.

    https://colab.research.google.com/drive/16jcaJoc6bCFAQ96jDe2HwtXj7BMD_-m5#scrollTo=FsePPpwZSmqt のプログラムをもとに作成

    Detectron2 の学習済みモデルは https://github.com/facebookresearch/detectron2/blob/main/MODEL_ZOO.md

    「im = cv2.imread('000000439715.jpg')」で,処理したい画像ファイルをロードしている.

    import detectron2
    from detectron2 import model_zoo
    from detectron2.engine import DefaultPredictor
    from detectron2.config import get_cfg
    from detectron2.utils.visualizer import Visualizer
    from detectron2.data import MetadataCatalog, DatasetCatalog
    
    def setup_config(configfile):
        cfg = get_cfg()
        # add project-specific config (e.g., TensorMask) here if you're not running a model in detectron2's core library
        cfg.merge_from_file(model_zoo.get_config_file(configfile))
        cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.5  # set threshold for this model
        # Find a model from detectron2's model zoo. You can use the https://dl.fbaipublicfiles... url as well
        cfg.MODEL.WEIGHTS = model_zoo.get_checkpoint_url(configfile)
        return cfg
    
    def look_instance(outputs):
        # インスタンス・セグメンテーションの結果の確認
        # look at the outputs. See https://detectron2.readthedocs.io/tutorials/models.html#model-output-format for specification
        print(outputs["instances"].pred_classes)
        print(outputs["instances"].pred_boxes)
    
    def visualize_instance(im, cfg, outputs):
        # 画面表示
        # We can use `Visualizer` to draw the predictions on the image.
        v = Visualizer(im[:, :, ::-1], MetadataCatalog.get(cfg.DATASETS.TRAIN[0]), scale=1.2)
        out = v.draw_instance_predictions(outputs["instances"].to("cpu"))
        cv2.imshow("", out.get_image()[:, :, ::-1])
        cv2.waitKey(15)
    
    import cv2
    im = cv2.imread('000000439715.jpg')
    cfg = setup_config('COCO-PanopticSegmentation/panoptic_fpn_R_101_3x.yaml')
    predictor = DefaultPredictor(cfg)
    outputs = predictor(im)
    look_instance(outputs)
    visualize_instance(im, cfg, outputs)
    

    [image]

    [image]

    次の Python プログラムを実行する

    Panoptic FPN R101 によるパノプティック・セグメンテーション.

    https://colab.research.google.com/drive/16jcaJoc6bCFAQ96jDe2HwtXj7BMD_-m5#scrollTo=FsePPpwZSmqt のプログラムをもとに作成

    Detectron2 の学習済みモデルは https://github.com/facebookresearch/detectron2/blob/main/MODEL_ZOO.md

    「im = cv2.imread('000000439715.jpg')」で,処理したい画像ファイルをロードしている.

    import detectron2
    from detectron2 import model_zoo
    from detectron2.engine import DefaultPredictor
    from detectron2.config import get_cfg
    from detectron2.utils.visualizer import Visualizer
    from detectron2.data import MetadataCatalog, DatasetCatalog
    
    def setup_config(configfile):
        cfg = get_cfg()
        # add project-specific config (e.g., TensorMask) here if you're not running a model in detectron2's core library
        cfg.merge_from_file(model_zoo.get_config_file(configfile))
        cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.5  # set threshold for this model
        # Find a model from detectron2's model zoo. You can use the https://dl.fbaipublicfiles... url as well
        cfg.MODEL.WEIGHTS = model_zoo.get_checkpoint_url(configfile)
        return cfg
    
    def look_instance(outputs):
        # インスタンス・セグメンテーションの結果の確認
        # look at the outputs. See https://detectron2.readthedocs.io/tutorials/models.html#model-output-format for specification
        print(outputs["instances"].pred_classes)
        print(outputs["instances"].pred_boxes)
    
    def visualize_instance(im, cfg, outputs):
        # 画面表示
        # We can use `Visualizer` to draw the predictions on the image.
        v = Visualizer(im[:, :, ::-1], MetadataCatalog.get(cfg.DATASETS.TRAIN[0]), scale=1.2)
        out = v.draw_instance_predictions(outputs["instances"].to("cpu"))
        cv2.imshow("", out.get_image()[:, :, ::-1])
        cv2.waitKey(15)
    
    import cv2
    im = cv2.imread('000000439715.jpg')
    cfg = setup_config('Misc/panoptic_fpn_R_101_dconv_cascade_gn_3x.yaml')
    predictor = DefaultPredictor(cfg)
    outputs = predictor(im)
    look_instance(outputs)
    visualize_instance(im, cfg, outputs)
    

    [image]

    [image]