物体検出,物体検出のための学習の実行(YOLOv5,PyTorch,Python を使用)(Windows 上)
【目次】
前準備
Build Tools for Visual Studio 2022 (ビルドツール for Visual Studio 2022)または Visual Studio 2022 のインストール(Windows 上)
【インストールの判断】 Build Tools for Visual Studio は,開発ツールセットである. Visual Studio は統合開発環境であり,いくつかの種類があり,Build Tools for Visual Studioの機能を含むか連携して使用するものである.インストールは以下の基準で判断してください:
- Build Tools for Visual Studio の機能のみが必要な場合
- Visual Studio の機能が必要である,あるいは,よく分からない場合
Visual Studio 2022 をインストールする際に,「C++ によるデスクトップ開発」を選択することで, Build Tools for Visual Studio 2022 の機能も一緒にインストールされる.
不明な点がある場合は,Visual Studio 全体をインストール を行う方が良い.
Build Tools for Visual Studio 2022 のインストール(Windows 上)
- Windows で,コマンドプロンプトを管理者として実行
コマンドプロンプトを管理者として実行: 別ページ »で説明
次のコマンドを実行
次のコマンドは,Build Tools for Visual Studio 2022と VC2015 再配布可能パッケージをインストールするものである.
- Build Tools for Visual Studio 2022 での C++ によるデスクトップ開発,CLI,ATL,MFC のインストール(Windows 上)
- Visual Studio Installer の起動
起動方法: スタートメニューの「Visual Studio Installer」を選ぶ.
- Visual Studio Build Tools 2022 で「変更」を選ぶ.
- 「C++ によるデスクトップ開発」をクリック.そして,画面右側の「インストール」の詳細で「v143 ビルドツール用 C++/CLI サポート(最新)」,「ATL」,「MFC」をチェックする.その後,「変更」をクリック.
- Visual Studio Installer の起動
Visual Studio のインストール(Windows 上)
- Windows で,コマンドプロンプトを管理者として実行
コマンドプロンプトを管理者として実行: 別ページ »で説明
次のコマンドを実行
次のコマンドは,Visual Studio Community 2022と VC2015 再配布可能パッケージをインストールするものである.
- Visual Studio での C++ によるデスクトップ開発,CLI のインストール(Windows 上)
- Visual Studio Installer の起動
起動方法: スタートメニューの「Visual Studio Installer」を選ぶ.
- Visual Studio Community 2022 で「変更」を選ぶ.
- 「C++ によるデスクトップ開発」をチェック.そして,画面右側の「インストール」の詳細で「v143 ビルドツール用 C++/CLI サポート(最新)」をチェックする.その後,「インストール」をクリック.
- Visual Studio Installer の起動
Python 3.10,Git のインストール(Windows 上)
Pythonは,プログラミング言語の1つ. Gitは,分散型のバージョン管理システム.
【手順】
- Windows で,コマンドプロンプトを管理者として実行
コマンドプロンプトを管理者として実行: 別ページ »で説明
次のコマンドを実行
次のコマンドは,Python ランチャーとPython 3.10とGitをインストールし,Gitにパスを通すものである.
次のコマンドでインストールされるGitは 「git for Windows」と呼ばれるものであり, Git,MinGW などから構成されている.
winget install --scope machine Python.Launcher winget install --scope machine Python.Python.3.10 winget install --scope machine Git.Git powershell -command "$oldpath = [System.Environment]::GetEnvironmentVariable(\"Path\", \"Machine\"); $oldpath += \";c:\Program Files\Git\cmd\"; [System.Environment]::SetEnvironmentVariable(\"Path\", $oldpath, \"Machine\")"
【関連する外部ページ】
- 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.6 のインストール(Windows 上)
【サイト内の関連ページ】 NVIDIA グラフィックスボードを搭載しているパソコンの場合には, NVIDIA ドライバ, NVIDIA CUDA ツールキット, NVIDIA cuDNN のインストールを行う.
- Windows での Build Tools for Visual Studio 2022,NVIDIA ドライバ,NVIDIA CUDA ツールキット 11.8,NVIDIA cuDNN v5.6 のインストールと動作確認: 別ページ »で説明
【関連する外部ページ】
- 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 で,コマンドプロンプトを管理者として実行
コマンドプロンプトを管理者として実行: 別ページ »で説明
- 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())"
【サイト内の関連ページ】
【関連する外部ページ】
YOLOv5 のインストールと実行手順(Windows環境)
YOLOv5 の公式リポジトリ https://github.com/ultralytics/yolov5 の手順に従ってインストールを実施する.
- Windows で,コマンドプロンプトを管理者として実行
コマンドプロンプトを管理者として実行: 別ページ »で説明
- 必要なパッケージのインストールとソースコードの取得
python -m pip install -U pillow wandb clearml comet_ml cd /d c:%HOMEPATH% rmdir /s /q yolov5 git clone https://github.com/ultralytics/yolov5 cd yolov5 pip install -r requirements.txt icacls . /grant Everyone:F /T
- Windows で,コマンドプロンプトを実行
- 物体検出の実行プロセス
YOLOv5 の公式リポジトリ https://github.com/ultralytics/yolov5 の手順に従って進める.
物体検出には,COCO データセットで学習済みの以下のモデルから選択が可能: yolov5n.pt, yolov5s.pt, yolov5m.pt, yolov5l.pt, yolov5x.pt.詳細は公式ドキュメント https://github.com/ultralytics/yolov5/tree/master/models を参照
cd /d c:%HOMEPATH% cd yolov5 python detect.py --weights yolov5s.pt --source=https://ultralytics.com/images/bus.jpg --exist-ok runs\detect\exp\bus.jpg
続いて「--visualize」オプションを追加して実行
cd /d c:%HOMEPATH% cd yolov5 python detect.py --weights yolov5s.pt --source=https://ultralytics.com/images/bus.jpg --visualize --exist-ok runs\detect\exp\bus.jpg
「--visualize」オプションにより,以下の可視化結果が生成される.
物体検出プログラムの実装(YOLOv5使用)(Windows環境)
以下のPythonプログラムで物体検出を実行できる.
- Python環境の起動
Python実行環境の選択
- Windows では python (Python ランチャーは py)
- Ubuntu では python3
開発環境オプション: Jupyter Qt Console, Jupyter Notebook, Jupyter Lab, Nteract, Spyder, PyCharm, PyScripter
Python関連情報: 別ページ »
python
- 物体検出の実装例
yolov5s はCOCOデータセットで事前学習済みのモデル.
詳細は公式ドキュメント https://github.com/ultralytics/yolov5/blob/master/data/coco.yaml を参照
import torch model = torch.hub.load("ultralytics/yolov5", "yolov5s") img = "https://ultralytics.com/images/zidane.jpg" # or file, Path, PIL, OpenCV, numpy, list results = model(img) results.pandas() results.show() # or .print(), .save(), .crop(), .pandas(), etc. exit()
-
より高性能な yolov5m モデルの使用例
物体検出には,COCOデータセットで学習済みの以下のモデルから選択可能:
yolov5n.pt,
yolov5s.pt,
yolov5m.pt,
yolov5l.pt,
yolov5x.pt.詳細は公式ドキュメント https://github.com/ultralytics/yolov5/blob/master/data/coco.yaml を参照
import torch model = torch.hub.load("ultralytics/yolov5", "yolov5m") img = "https://ultralytics.com/images/zidane.jpg" # or file, Path, PIL, OpenCV, numpy, list results = model(img) results.pandas() results.show() # or .print(), .save(), .crop(), .pandas(), etc. exit()
YOLO形式オープンデータを用いた新規クラスの物体検出学習(開発中)
画像データと物体検出アノテーション(クラス名とバウンディングボックス)を活用し, Traffic Signs Datasetを使用した学習を実施する.
Traffic Signs Datasetのダウンロードと前処理後,以下の手順で学習を進める:
- クラス番号の調整:COCOデータセット使用の0-79を避け, Traffic Signs Datasetでは80-83を使用
- データセットの分割:学習用(train)と検証用(validation)データの準備
- 以下のディレクトリ構造でファイルを配置
├── images/ ├─train/ └─val/ ├── labels/ ├─train/ └─val/
- 画像サイズの標準化:横幅を640ピクセルに統一
- Traffic Signs Dataset in YOLO format へアクセス
- 「Download」ボタンをクリック
- Kaggleアカウント登録またはGoogleアカウントでのサインインが必要な場合は指示に従い,再度「Download」をクリック
- archive.zipのダウンロード完了
- C:\archive ディレクトリを作成し,archive.zipを展開
下図のように配置:
- Windows でコマンドプロンプトを起動
- 以下のコマンドでディレクトリを移動しPythonを起動
cd C:\archive python
- クラス番号更新プログラムの実行
このプログラムは900個のアノテーションファイル(00000.txt~00899.txt)を処理し, 各ファイルの行頭のクラス番号(0-3)に対して,80未満の場合は80を加算して更新する. ファイルが存在しない場合はエラーを出力.
def update_class_number(filename): with open(filename, "r", encoding="utf-8") as file: lines = file.readlines() updated_lines = [] for line in lines: parts = line.strip().split() if len(parts) >= 5: class_number = int(parts[0]) # もともとのクラス番号 (class_number) は 0, 1, 2, 3 である。80を加えて,元のファイルのクラス番号を更新する if class_number < 80: updated_class_number = class_number + 80 x1, y1, x2, y2 = map(float, parts[1:]) updated_line = f"{updated_class_number} {x1} {y1} {x2} {y2}\n" updated_lines.append(updated_line) else: updated_lines.append(line) else: updated_lines.append(line) with open(filename, "w", encoding="utf-8") as file: file.writelines(updated_lines) file_not_found = False for i in range(0, 900): # 00000.txt から 00899.txt まで filename = f"ts/{i:05}.txt" try: update_class_number(filename) # 確認表示 with open(filename, "r", encoding="utf-8") as file: first_line = file.readline().strip() print(f"filename: {filename} , {first_line}") except FileNotFoundError: print(f"{filename} が見つかりませんでした") file_not_found = True exit()
- 処理完了の確認
このプログラムにより,クラス番号を80-83に変更.
クラス番号とクラス名の対応は c:\archive\classes.names に以下の通り定義:
80, prohibitory 81, danger 82, mandatory 83, other
- 画像サイズの標準化
以下のコマンドを実行:
cd c:\archive\ts\ts python
次のPythonプログラムを実行
from PIL import Image import os # 新しい幅 new_width = 640 # カレントディレクトリ内のすべてのファイル for filename in os.listdir('.'): # .jpgファイルのみを処理 if filename.endswith('.jpg'): print(f"{filename} を変換") with Image.open(filename) as img: # アスペクト比を保持した高さを計算 aspect_ratio = new_width / img.width new_height = int(img.height * aspect_ratio) # リサイズ resized_img = img.resize((new_width, new_height)) # 元のファイルを上書き resized_img.save(filename) exit()
- validation 用のディレクトリを用意する.これらのディレクトリにいくつかのファイルを移動する.
mkdir c:\archive\ts\ts\images mkdir c:\archive\ts\ts\images\train mkdir c:\archive\ts\ts\images\val mkdir c:\archive\ts\ts\labels mkdir c:\archive\ts\ts\labels\train mkdir c:\archive\ts\ts\labels\val cd c:\archive\ts\ts move *1.txt labels\val move *1.jpg images\val move *.txt labels\train move *.jpg images\train icacls c:\archive\ts /grant Everyone:F /T
- ファイル ts.yaml を作成する
エディタを起動
cd /d c:%HOMEPATH% cd yolov5 notepad ts.yaml
エディタで次のように作成し保存する.
names は 84 個の文字列のリストである.最初の 80 個は COCO データセットのクラス名.残りの 4 個は,いまから学習を行うデータセットのクラス名になる.
path: c:/archive/ts/ts train: images/train val: images/val nc: 84 names: 0: person 1: bicycle 2: car 3: motorcycle 4: airplane 5: bus 6: train 7: truck 8: boat 9: traffic light 10: fire hydrant 11: stop sign 12: parking meter 13: bench 14: bird 15: cat 16: dog 17: horse 18: sheep 19: cow 20: elephant 21: bear 22: zebra 23: giraffe 24: backpack 25: umbrella 26: handbag 27: tie 28: suitcase 29: frisbee 30: skis 31: snowboard 32: sports ball 33: kite 34: baseball bat 35: baseball glove 36: skateboard 37: surfboard 38: tennis racket 39: bottle 40: wine glass 41: cup 42: fork 43: knife 44: spoon 45: bowl 46: banana 47: apple 48: sandwich 49: orange 50: broccoli 51: carrot 52: hot dog 53: pizza 54: donut 55: cake 56: chair 57: couch 58: potted plant 59: bed 60: dining table 61: toilet 62: tv 63: laptop 64: mouse 65: remote 66: keyboard 67: cell phone 68: microwave 69: oven 70: toaster 71: sink 72: refrigerator 73: book 74: clock 75: vase 76: scissors 77: teddy bear 78: hair drier 79: toothbrush 80: prohibitory 81: danger 82: mandatory 83: other
- 学習の実行
実行にかかる時間の目安は10分から数十分である.
cd /d c:%HOMEPATH% python yolov5/train.py --data yolov5/ts.yaml --weights yolov5/yolov5s.pt --img 640 --epochs 30
GPU を使わないときは,次のように「--device cpu」を付ける.このときは,実行に10時間ほどかかる.
cd /d c:%HOMEPATH% cd yolov5 python train.py --data ts.yaml --weights yolov5s.pt --img 640 --epochs 30 --device cpu
学習が実質開始する前にエラーメッセージが出た場合,YOLOv5 のインストールを再度行うことで改善する可能性がある.
- 学習の終了の確認
このとき,結果が保存されているディレクトリを確認する. 最後のところに「Results saved to runs\detect\...」のように表示されるので確認
- dir コマンドでファイルを確認.
「runs\train\exp2」のところには,「結果が保存されているディレクトリ」を指定すること.
dir runs\train\exp2 dir runs\train\exp2\weights
- 学習したデータで物体検出してみる
「runs\train\exp2」のところには,「結果が保存されているディレクトリ」を指定すること.
python detect.py --weights ./runs/train/exp2/weights/best.pt --source=c:/archive/ts/ts/images/val/00001.jpg
このとき,結果が保存されているディレクトリを確認する. 最後のところに「Results saved to runs\detect\...」のように表示されるので確認
結果が保存されているディレクトリに画像があるので表示してみる.