深度學習_目標檢測_YOLOv5訓練Pascal VOC格式的數據集教程

1.搭建環境

要求Python版本>=3.7,PyTorch版本>=1.5。

並且安裝需要的庫源:

pip install -U -r requirements.txt

2.開始準備Pascal VOC格式的數據

在這裏插入圖片描述

上圖是Pascal VOC格式數據集的標準格式。

爲了應對YOLOv5的darknet格式 ,我們使用如下代碼生成labels標籤文件(爲了簡單起見,我們對train和test標籤進行生成):

import xml.etree.ElementTree as ET
import pickle
import os
from os import listdir, getcwd
from os.path import join

sets = ['train', 'test']

classes = ['XO', 'PN', 'PI', 'NP', 'HD', 'FP', 'FB', 'FO']  # 自己訓練的類別


def convert(size, box):
    dw = 1. / size[0]
    dh = 1. / size[1]
    x = (box[0] + box[1]) / 2.0
    y = (box[2] + box[3]) / 2.0
    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(image_id):
    in_file = open('./Annotations/%s.xml' % (image_id))
    out_file = open('./labels/%s.txt' % (image_id), 'w')
    tree = ET.parse(in_file)
    root = tree.getroot()
    size = root.find('size')
    w = int(size.find('width').text)
    h = int(size.find('height').text)

    for obj in root.iter('object'):
        difficult = obj.find('difficult').text
        cls = obj.find('name').text
        if cls not in classes or int(difficult) == 1:
            continue
        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)
        out_file.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')


wd = getcwd()
for image_set in sets:
    if not os.path.exists('./labels/'):
        os.makedirs('./labels/')
    image_ids = open('./ImageSets/Main/%s.txt' % (image_set)).read().strip().split()
    list_file = open('./%s.txt' % (image_set), 'w')
    for image_id in image_ids:
        list_file.write('./JPEGImages/%s.jpg\n' % (image_id))
        convert_annotation(image_id)
    list_file.close()

結果如下所示:

在這裏插入圖片描述

我們可以看到生成了train.txt、test.txt和labels文件。

3.數據集整合

在模型官方的github中給出了數據集整合的方法:Train Custom Data

我首先講一講官方的方法

在這裏插入圖片描述

從上圖可以看到,我們需要將labels文件夾中的.txt文件分別對應的放入train2017和val2017中;同樣的,JPEGImages文件夾中的.jpg圖像文件也分別對應的放入train2017和val2017中。

我使用的方法

我是將labels裏的文件全都複製到JPEGImages文件夾中。

這兩種方法對應着下面配置訓練文件的路徑設置不同。

4. 配置訓練文件

在data目錄下新建VOC.yaml,配置訓練的數據:

# COCO 2017 dataset http://cocodataset.org - first 128 training images
# Download command:  python -c "from yolov5.utils.google_utils import gdrive_download; gdrive_download('1n_oKgR81BJtqk75b00eAjdv03qVCQn2f','coco128.zip')"
# Train command: python train.py --data ./data/coco128.yaml
# Dataset should be placed next to yolov5 folder:
#   /parent_folder
#     /coco128
#     /yolov5


# train and val datasets (image directory or *.txt file with image paths)

#(上面第三步的不同體現在讀取數據的路徑,如果是官方的方法,我們填寫如下路徑:
#COCO/images/train2017/  
#COCO/images/val2017/  
#;如果使用我的方法,我們可以用上面生成labels時同時生成的train.txt和test.txt路徑)
train: /root/yolov5-master/data/train.txt 
val: /root/yolov5-master/data/test.txt

# number of classes
nc: 8

# class names
names: ['XO', 'PN', 'PI', 'NP', 'HD', 'FP', 'FB', 'FO']

models文件修改(我們想使用哪個模型就對應改哪個yaml),例如我們使用yolov5s.yaml:

# parameters
nc: 8  # number of classes   <------------------  UPDATE to match your dataset(一般我們只需要改這個)
depth_multiple: 0.33  # model depth multiple
width_multiple: 0.50  # layer channel multiple

# anchors
anchors:
  - [10,13, 16,30, 33,23]  # P3/8
  - [30,61, 62,45, 59,119]  # P4/16
  - [116,90, 156,198, 373,326]  # P5/32

# yolov5 backbone
backbone:
  # [from, number, module, args]
  [[-1, 1, Focus, [64, 3]],  # 1-P1/2
   [-1, 1, Conv, [128, 3, 2]],  # 2-P2/4
   [-1, 3, Bottleneck, [128]],
   [-1, 1, Conv, [256, 3, 2]],  # 4-P3/8
   [-1, 9, BottleneckCSP, [256, False]],
   [-1, 1, Conv, [512, 3, 2]],  # 6-P4/16
   [-1, 9, BottleneckCSP, [512, False]],
   [-1, 1, Conv, [1024, 3, 2]], # 8-P5/32
   [-1, 1, SPP, [1024, [5, 9, 13]]],
   [-1, 12, BottleneckCSP, [1024, False]],  # 10
  ]

# yolov5 head
head:
  [[-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1, 0]],  # 12 (P5/32-large)

   [-2, 1, nn.Upsample, [None, 2, 'nearest']],
   [[-1, 6], 1, Concat, [1]],  # cat backbone P4
   [-1, 1, Conv, [512, 1, 1]],
   [-1, 3, BottleneckCSP, [512, False]],
   [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1, 0]],  # 16 (P4/16-medium)

   [-2, 1, nn.Upsample, [None, 2, 'nearest']],
   [[-1, 4], 1, Concat, [1]],  # cat backbone P3
   [-1, 1, Conv, [256, 1, 1]],
   [-1, 3, BottleneckCSP, [256, False]],
   [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1, 0]],  # 21 (P3/8-small)

   [[], 1, Detect, [nc, anchors]],  # Detect(P3, P4, P5)
  ]

5.訓練

接下來我們就可以進行訓練啦,可以使用如下代碼,也可自己的修改參數:

python train.py --data data/VOC.yaml --cfg models/yolov5s.yaml --weights '' --batch-size 16 --epochs 5
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章