将PASCAL VOC数据集格式转换为YOLOV5 所需的格式
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 ETclasses = ["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 * dwy = (box[1] + box[3]) / 2 * dhw = (box[2] - box[0]) * dwh = (box[3] - box[1]) * dhreturn (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').textcls = obj.find('name').textif 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, y2box = [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 hout_file.write(str(cls_id) + " " + " ".join(str(x) for x in bbox) + '\n')if __name__ == '__main__':# 这里要改成自己数据集路径的格式path = 'E:/VOC2007/Annotations/'voc2yolo(path)
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
