金子邦彦研究室人工知能Windows で動く人工知能関係 Pythonアプリケーション,オープンソースソフトウエア)物体検出,インスタンス・セグメンテーション,パノプティック・セグメンテーションの実行(Detectron2,PyTorch, Python を使用)(Windows 上)

物体検出,インスタンス・セグメンテーション,パノプティック・セグメンテーションの実行(Detectron2,PyTorch, Python を使用)(Windows 上)

Detectron2 を使用した物体検出,インスタンス・セグメンテーション,パノプティック・セグメンテーションの設定と実行を説明する.内容は,Windows上での前準備,関連ツールとライブラリのインストール,および物体検出とセグメンテーションを行うPythonプログラムのソースコードと実行手順の説明である.プログラムはCOCOデータセットに基づいている.外部リンクや参考文献も説明しており,関連する詳細な情報にアクセスできる.

物体検出

インスタンス・セグメンテーション

パノプティック・セグメンテーション

目次

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

Detectron2

文献

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

関連する外部ページ

関連項目ADE20K データセット, インスタンス・セグメンテーション (instance segmentation)

前準備

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

Gitは,バージョン管理システム.ソースコードの管理や複数人での共同に役立つ.

サイト内の関連ページ

Windows での Git のインストール: 別ページ »で説明している.

関連する外部ページ

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

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

サイト内の関連ページ

関連する外部ページ

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

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

サイト内の関連ページ

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

関連する外部ページ

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

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

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

  2. PyTorch のページを確認

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

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

    次のコマンドは, PyTorch 2.0 (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 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())" 
    

    [image]

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

    サイト内の関連ページ

    関連する外部ページ

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

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

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

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

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

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

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

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

pycocotools のインストールを行う.

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

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

  2. pycocotools, COCO 2018 Panoptic Segmentation Task API のインストール

    COCOデータセットをPythonで扱うためには,pycocotools を使う. pycocotools を使うことで,COCOデータセットのアノテーションを扱いやすくなる.

    次のコマンドを実行

    python -m pip install -U --ignore-installed pip
    python -m pip install -U cython wheel
    python -m pip install "git+https://github.com/philferriere/cocoapi.git#egg=pycocotools&subdirectory=PythonAPI"
    python -m pip install git+https://github.com/cocodataset/panopticapi.git
    

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

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

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

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

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

  2. Detectron2 のダウンロード
    python -m pip uninstall -y detectron2
    cd %HOMEPATH%
    rmdir /s /q detectron2
    git clone --recursive https://github.com/facebookresearch/detectron2
    cd detectron2
    

    [image]
  3. ソースコードの書き換え
    notepad detectron2\layers\csrc\nms_rotated\nms_rotated_cuda.cu
    

    [image]

    次のように書き換える

    [image]
  4. インストール
    cd %HOMEPATH%\detectron2
    python -m pip install -e .
    

    [image]
    (以下省略)
  5. 引き続き,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
curl -O http://images.cocodataset.org/val2017/000000439715.jpg

[image]

物体検出

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

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

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

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

    cd %HOMEPATH%\detectron2
    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
    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
    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]