在网上找了一大圈YOLOV5数据集的制作,都没有合适的,不是流程太复杂就是给出的代码有问题。所以我在这里记录一下YOLOV5数据集简单的制作过程。
-
Annotations
这里是标注信息,我用的是labelimg。
-
images
存放了标注的图像,最好都是jpg格式的。
split_train_val.py
# coding:utf-8
import os
import random
import argparse
parser = argparse.ArgumentParser()
#xml文件的地址,根据自己的数据进行修改 xml一般存放在Annotations下
parser.add_argument('--xml_path', default=r'Annotations', type=str, help='input xml label path')
#数据集的划分,没有这个文件夹的话,程序会自动创建
parser.add_argument('--txt_path', default=r'ImageSets', type=str, help='output txt label path')
opt = parser.parse_args()
trainval_percent = 1.0
train_percent = 0.9
xmlfilepath = opt.xml_path
txtsavepath = opt.txt_path
total_xml = os.listdir(xmlfilepath)
if not os.path.exists(txtsavepath):
os.makedirs(txtsavepath)
num = len(total_xml)
list_index = range(num)
tv = int(num * trainval_percent)
tr = int(tv * train_percent)
trainval = random.sample(list_index, tv)
train = random.sample(trainval, tr)
file_train = open(txtsavepath + '/train.txt', 'w')
file_val = open(txtsavepath + '/val.txt', 'w')
for i in list_index:
name = total_xml[i][:-4] + '\n'
if i in trainval:
if i in train:
file_train.write(name)
else:
file_val.write(name)
file_train.close()
file_val.close()
- voc_label.py
import xml.etree.ElementTree as ET
import pickle
import os
from os import listdir, getcwd
from os.path import join
sets = ['train', 'val']
classes = ["car", "person"] #根据自己的项目改
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(r'Annotations/%s.xml' % (image_id), 'r', encoding="UTF-8")
out_file = open(r'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()
print(wd)
for image_set in sets:
if not os.path.exists('labels/'):
os.makedirs('labels/')
image_ids = open(r'ImageSets/%s.txt' % (image_set)).read().strip().split()
list_file = open(r'%s.txt' % (image_set), 'w')
for image_id in image_ids:
list_file.write(r'C:/F/cardata/images/%s.jpg' % (image_id)) #写入绝对路径
list_file.write('\n')
convert_annotation(image_id)
list_file.close()
然后依次运行split_train_val.py和voc_label.py就行。
注意:唯一2处需要改的就是voc_label.py我写了注释的地方。