1. VOC数据集
VOC数据集格式如下(以2007为例):
其中JPEGImages文件夹存放图片,Anootations下放的是标注框的信息,格式为xml;但YOLOv5所需要的格式为txt,且txt内容格式为:id x_center y_center w h,且都是标准化(0~1之间)后的值,所以需要做相应的转换。
附:
VOC2007训练集下载地址
VOC2007测试集下载地址
2. YOLOV5
V5对于V4而言,在数据增强和网络结构上并没有太大的改变。但相比于V4官方给出的版本,V5更倾向于应用,所以V5考虑到了很多现实应用场景中会遇到的细节问题(所以总体的代码量也是大的惊人),github源码的地址:
(https://github.com/ultralytics/yolov5)
ps:要是认真细品源码的话真的会感叹一波作者的coding功底,其中很多方法可以借鉴到我们的项目中
其中数据集标签格式的转换代码,注释写的很详细:
import os
import xml.etree.ElementTree as ET
classes = ["aeroplane", "bicycle", "bird", "boat", "bottle", "bus", "car", "cat", "chair", "cow", "diningtable", "dog",
"horse", "motorbike", "person", "pottedplant", "sheep", "sofa", "train", "tvmonitor"]
# 将x1, y1, x2, y2转换成yolov5所需要的x, y, w, h格式
def xyxy2xywh(size, box):
dw = 1. / size[0]
dh = 1. / size[1]
x = (box[0] + box[2]) / 2 * dw
y = (box[1] + box[3]) / 2 * dh
w = (box[2] - box[0]) * dw
h = (box[3] - box[1]) * dh
return (x, y, w, h) # 返回的都是标准化后的值
def voc2yolo(path):
# 可以打印看看该路径是否正确
print(len(os.listdir(path)))
# 遍历每一个xml文件
for file in os.listdir(path):
# xml文件的完整路径, 注意:因为是路径所以要确保准确,我是直接使用了字符串拼接, 为了保险可以用os.path.join(path, file)
label_file = path + file
# 最终要改成的txt格式文件,这里我是放在voc2007/labels/下面
# 注意: labels文件夹必须存在,没有就先创建,不然会报错
out_file = open(path.replace('Annotations', 'labels') + file.replace('xml', 'txt'), 'w')
# print(label_file)
# 开始解析xml文件
tree = ET.parse(label_file)
root = tree.getroot()
size = root.find('size') # 图片的shape值
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
# 将名称转换为id下标
cls_id = classes.index(cls)
# 获取整个bounding box框
bndbox = obj.find('bndbox')
# xml给出的是x1, y1, x2, y2
box = [float(bndbox.find('xmin').text), float(bndbox.find('ymin').text), float(bndbox.find('xmax').text),
float(bndbox.find('ymax').text)]
# 将x1, y1, x2, y2转换成yolov5所需要的x_center, y_center, w, h格式
bbox = xyxy2xywh((w, h), box)
# 写入目标文件中,格式为 id x y w h
out_file.write(str(cls_id) + " " + " ".join(str(x) for x in bbox) + '\n')
if __name__ == '__main__':
# 这里要改成自己数据集路径的格式
path = 'E:/VOC2007/Annotations/'
voc2yolo(path)