【目次】
Gitは,バージョン管理システム.ソースコードの管理や複数人での共同に役立つ.
【サイト内の関連ページ】
Windows での Git のインストール: 別ページ »で説明している.
【関連する外部ページ】
Git の公式ページ: https://git-scm.com/
【サイト内の関連ページ】
【関連する外部ページ】
Python の公式ページ: https://www.python.org/
【サイト内の関連ページ】
NVIDIA グラフィックスボードを搭載しているパソコンの場合には, NVIDIA ドライバ, NVIDIA CUDA ツールキット, NVIDIA cuDNN のインストールを行う.
【関連する外部ページ】
コマンドプロンプトを管理者として実行: 別ページ »で説明
PyTorch のページ: https://pytorch.org/index.html
次のコマンドは, 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())"
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 の公式の GitHub のページ https://github.com/ultralytics/yolov5 に従ってインストールする.
コマンドプロンプトを管理者として実行: 別ページ »で説明
python -m pip install -U pillow cd %HOMEPATH% rmdir /s /q yolov5 git clone https://github.com/ultralytics/yolov5 cd yolov5 pip install -r requirements.txt
YOLOv5 の公式の GitHub のページ https://github.com/ultralytics/yolov5 に従う.
runs\detect\predict\bus.jpg の「predict」は実行のたびにpredict2, predict3 のように変えてください.
物体検出の学習済みモデルは, yolov5n.pt, yolov5s.pt, yolov5m.pt, yolov5l.pt, yolov5x.pt から選択できる.物体学習済みモデルは,いずれもCOCO データセットで学習済みのモデルである。詳しくは公式ページの https://github.com/ultralytics/yolov5/tree/master/models
cd %HOMEPATH% cd yolov5 python detect.py --weights yolov5s.pt --source=https://ultralytics.com/images/bus.jpg runs\detect\exp\bus.jpg
今度は「--visualize」を付けて実行
cd %HOMEPATH% cd yolov5 python detect.py --weights yolov5s.pt --source=https://ultralytics.com/images/bus.jpg --visualize runs\detect\exp2\bus.jpg
「--visualize」を付けたので,次のようなファイルができる.
次の Python プログラムで,物体検出の結果を得ることができる.
詳しくは公式ページの https://github.com/ultralytics/yolov5/blob/main/ultralytics/cfg/datasets/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()
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 をダウンロードし,次の処理の上で,学習を行う
├── images/ ├─train/ └─val/ ├── labels/ ├─train/ └─val/
Kaggleへ登録するか,Google アカウントなどでサインイン.
次のようにする.
cd C:\archive python
このプログラムは,"ts/ts/"ディレクトリ内の900個のテキストファイル("00000.txt"から"00899.txt")を処理する。 各ファイルの最初の行からクラス番号(0, 1, 2, 3)を取り出し,その値が80未満の場合,80を加算してファイルに書き戻す。 ファイルが存在しない場合,エラーメッセージが表示される.
for i in range(0, 900): # 00000.txt から 00899.txt まで filename = f"ts/ts/{i:05}.txt" try: with open(filename, "r", encoding="utf-8") as file: # 先頭行を使う lines = file.readlines() first_line = lines[0].strip() parts = first_line.split() 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" lines[0] = updated_line with open(filename, "w", encoding="utf-8") as file: file.writelines(lines) # 確認表示 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} が見つかりませんでした") exit()
このプログラムの実行により,クラス番号 80, 81, 82, 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()
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
エディタを起動
cd %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 %HOMEPATH% cd yolov5 python train.py --data ts.yaml --weights yolov5s.pt --img 640 --epochs 30
GPU を使わないときは,次のように「--device cpu」を付ける.このときは,実行に10時間ほどかかる.
cd %HOMEPATH% cd yolov5 python train.py --data ts.yaml --weights yolov5s.pt --img 640 --epochs 30 --device cpu
学習が実質開始する前にエラーメッセージが出た場合,YOLOv5 のインストールを再度行うことで改善する可能性がある.
このとき,結果が保存されているディレクトリを確認する. 最後のところに「Results saved to runs\detect\...」のように表示されるので確認
「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\...」のように表示されるので確認
結果が保存されているディレクトリに画像があるので表示してみる.