2023 年の最新 - yolov8 を使用して独自のデータセットをトレーニングする

1. コードのダウンロード

まず、公式 Web サイトからyolov8をダウンロードする
ここに画像の説明を挿入
か、git を使用してダウンロードします。

git clone https://github.com/ultralytics/ultralytics

次のようにpycharmで開きます
ここに画像の説明を挿入

2. 環境構築

2.1 新しい環境を作成する

スタート メニューで次のウィンドウを見つけて
ここに画像の説明を挿入

ここに画像の説明を挿入
[新しい環境の作成] yolov8 をクリックします。

conda create -n yolov8 python=3.8

新しい環境をアクティブ化する

conda activate yolov8

2.2 pytorchのインストール

対応するインストール コマンドは pytorch 公式 Web サイトにあります。ここでのバージョン要件は torch=1.12.0+ を推奨します。torch=1.12.0 のインストール コマンドは以下に掲載されています。コンピュータの状況に応じて CUDA 11.8 を選択してください

pip install torch==2.0.0+cu118 torchvision==0.15.1+cu118 torchaudio==2.0.1 --index-url https://download.pytorch.org/whl/cu118

CUDA 11.7

pip install torch==1.13.1+cu117 torchvision==0.14.1+cu117 torchaudio==0.13.1 --extra-index-url https://download.pytorch.org/whl/cu117

CUDA 11.6

pip install torch==1.12.0+cu116 torchvision==0.13.0+cu116 --extra-index-url https://download.pytorch.org/whl/cu116

CUDA 11.3

pip install torch==1.12.0+cu113 torchvision==0.13.0+cu113 --extra-index-url https://download.pytorch.org/whl/cu113

CUDA 10.2

pip install torch==1.12.0+cu102 torchvision==0.13.0+cu102 --extra-index-url https://download.pytorch.org/whl/cu102

CPUのみ

pip install torch==1.12.0+cpu torchvision==0.13.0+cpu --extra-index-url https://download.pytorch.org/whl/cpu

2.3 サードパーティパッケージのインストール

ここに画像の説明を挿入
ここには、インストールする必要があるさまざまなサードパーティ パッケージがあります。
ここに画像の説明を挿入
まず、環境の場所から要件の場所を見つけて、次のコマンドを入力します。

pip install -r requirements.txt -i https://mirrors.bfsu.edu.cn/pypi/web/simple/

2.4 ウルトラリティクスのインストール

Ultralytics は、yolo のさまざまなパッケージとモデルを統合します。

pip install ultralytics

2.5 バグの解決

[警告: エンコード エラーのため、setup.cfg の distutils 設定を無視する] がインストール プロセス中に発生した場合は、setup.cfg を txt ファイルとして直接保存できます。
ここに画像の説明を挿入

2.6 重みを手動でダウンロードする

yolov8 は重みを自動的にダウンロードしてくれますが、結局のところ、Web サイトが海外にあるため、ダウンロードに失敗することがよくあります。したがって、必要なモデルが何であれ、最初に手動でダウンロードすると、github プロジェクトで利用できるようになります。
ここに画像の説明を挿入
次に、それを検出ファイルに貼り付けます。
ここに画像の説明を挿入

2.7 空き状況を確認する

公式画像を使用して予測します。コマンドは次のとおりです

yolo task=detect mode=predict model=yolov8n.pt source=assets/  device=cpu save=True

ここに画像の説明を挿入

3. 独自のデータセットをトレーニングする

3.1 データセットの処理

私は主にターゲット検出を行うため、すべてのデータセットを detect に置きます。
ここに画像の説明を挿入
ここに画像の説明を挿入

データセットは voc 形式なので、yolo 形式に変換する必要がありますので、まずこのようなフォルダーを作成します。
xml2txt.py を実行すると、このファイルで Annotations の XML 形式の注釈ファイルが txt の yolo 形式の注釈ファイルに変換されます。

import xml.etree.ElementTree as ET
import os, cv2
import numpy as np
from os import listdir
from os.path import join

classes = []

def convert(size, box):
    dw = 1. / (size[0])
    dh = 1. / (size[1])
    x = (box[0] + box[1]) / 2.0 - 1
    y = (box[2] + box[3]) / 2.0 - 1
    w = box[1] - box[0]
    h = box[3] - box[2]
    x = x * dw
    w = w * dw
    y = y * dh
    h = h * dh
    return (x, y, w, h)


def convert_annotation(xmlpath, xmlname):
    with open(xmlpath, "r", encoding='utf-8') as in_file:
        txtname = xmlname[:-4] + '.txt'
        txtfile = os.path.join(txtpath, txtname)
        tree = ET.parse(in_file)
        root = tree.getroot()
        filename = root.find('filename')
        img = cv2.imdecode(np.fromfile('{}/{}.{}'.format(imgpath, xmlname[:-4], postfix), np.uint8), cv2.IMREAD_COLOR)
        h, w = img.shape[:2]
        res = []
        for obj in root.iter('object'):
            cls = obj.find('name').text
            if cls not in classes:
                classes.append(cls)
            cls_id = classes.index(cls)
            xmlbox = obj.find('bndbox')
            b = (float(xmlbox.find('xmin').text), float(xmlbox.find('xmax').text), float(xmlbox.find('ymin').text),
                 float(xmlbox.find('ymax').text))
            bb = convert((w, h), b)
            res.append(str(cls_id) + " " + " ".join([str(a) for a in bb]))
        if len(res) != 0:
            with open(txtfile, 'w+') as f:
                f.write('\n'.join(res))


if __name__ == "__main__":
    postfix = 'jpg'
    imgpath = 'VOCdevkit/JPEGImages'
    xmlpath = 'VOCdevkit/Annotations'
    txtpath = 'VOCdevkit/txt'
    
    if not os.path.exists(txtpath):
        os.makedirs(txtpath, exist_ok=True)
    
    list = os.listdir(xmlpath)
    error_file_list = []
    for i in range(0, len(list)):
        try:
            path = os.path.join(xmlpath, list[i])
            if ('.xml' in path) or ('.XML' in path):
                convert_annotation(path, list[i])
                print(f'file {
      
      list[i]} convert success.')
            else:
                print(f'file {
      
      list[i]} is not xml format.')
        except Exception as e:
            print(f'file {
      
      list[i]} convert error.')
            print(f'error message:\n{
      
      e}')
            error_file_list.append(list[i])
    print(f'this file convert failure\n{
      
      error_file_list}')
    print(f'Dataset Classes:{
      
      classes}')

ここに画像の説明を挿入
これを保存し、後で yaml ファイルに入力する必要があります。
Split_data.py を実行します。このファイルは、トレーニング、検証、およびテスト セットを分割します。

import os, shutil
from sklearn.model_selection import train_test_split

val_size = 0.1
test_size = 0.2
postfix = 'jpg'
imgpath = 'VOCdevkit/JPEGImages'
txtpath = 'VOCdevkit/txt'

os.makedirs('images/train', exist_ok=True)
os.makedirs('images/val', exist_ok=True)
os.makedirs('images/test', exist_ok=True)
os.makedirs('labels/train', exist_ok=True)
os.makedirs('labels/val', exist_ok=True)
os.makedirs('labels/test', exist_ok=True)

listdir = [i for i in os.listdir(txtpath) if 'txt' in i]
train, test = train_test_split(listdir, test_size=test_size, shuffle=True, random_state=0)
train, val = train_test_split(train, test_size=val_size, shuffle=True, random_state=0)
print(f'train set size:{
      
      len(train)} val set size:{
      
      len(val)} test set size:{
      
      len(test)}')

for i in train:
    shutil.copy('{}/{}.{}'.format(imgpath, i[:-4], postfix), 'images/train/{}.{}'.format(i[:-4], postfix))
    shutil.copy('{}/{}'.format(txtpath, i), 'labels/train/{}'.format(i))

for i in val:
    shutil.copy('{}/{}.{}'.format(imgpath, i[:-4], postfix), 'images/val/{}.{}'.format(i[:-4], postfix))
    shutil.copy('{}/{}'.format(txtpath, i), 'labels/val/{}'.format(i))

for i in test:
    shutil.copy('{}/{}.{}'.format(imgpath, i[:-4], postfix), 'images/test/{}.{}'.format(i[:-4], postfix))
    shutil.copy('{}/{}'.format(txtpath, i), 'labels/test/{}'.format(i))

新しい data.yaml を作成する

ここに画像の説明を挿入
パスは絶対パスとして記述する必要があります。そうでないとエラーが報告されます。
このようにしてデータセットが処理されます。

3.2 トレーニングデータ

トレーニングコマンドを入力してください

yolo task=detect mode=train model=yolov8s.yaml data=yolo/v8/detect/fish_datasets/data.yaml epochs=100 batch=4

3.3 検証データ

検証コマンドを入力し、トレーニングされたモデルを使用して検証します。

yolo task=detect mode=val model=ultralytics/yolo/v8/detect/runs/detect/train5/weights/best.pt  data=ultralytics/yolo/v8/detect/fish_datasets/data.yaml device=cpu

ここに画像の説明を挿入

3.4 予測データ

yolo task=detect mode=predict model=ultralytics/yolo/v8/detect/runs/detect/train5/weights/best.pt source=ultralytics/yolo/v8/detect/fish_datasets/images/val  device=cpu

ここに画像の説明を挿入

3.5 モデルのエクスポート

次のコマンドを使用してモデルをエクスポートします

yolo task=detect mode=export model=ultralytics/yolo/v8/detect/runs/detect/train5/weights/best.pt 

この記事では、多くの専門家によって書かれた記事も参照しており、彼らのチュートリアルを確認することもできます。
YOLOV8の最強操作チュートリアル
YOLOv8チュートリアルシリーズ: 1. カスタムデータセットを使用してYOLOv8モデルをトレーニングします(チュートリアルの詳細版、1つの記事を読むだけで済みます -> パラメータ調整ガイド)(環境構築/データ準備/モデルトレーニングを含む) /prediction/verification/ Export他
YOLOv8環境構築から推論訓練まで

おすすめ

転載: blog.csdn.net/weixin_44752340/article/details/130846432