数据集的标签格式为xml格式,转为yolo的训练格式:
1.创建一个格式转化的.py文件将下面代码复制:
import os
import glob
import xml.etree.ElementTree as ETdef get_classes(classes_path):with open(classes_path, encoding='utf-8') as f:class_names = f.readlines()class_names = [c.strip() for c in class_names]print("Classes loaded:", class_names)return class_names, len(class_names)def convert(size, box):dw = 1.0 / size[0]dh = 1.0 / size[1]x = (box[0] + box[1]) / 2.0y = (box[2] + box[3]) / 2.0w = box[1] - box[0]h = box[3] - box[2]x = x * dww = w * dwy = y * dhh = h * dhreturn (x, y, w, h)def convert_xml_to_yolo(xml_root_path, txt_save_path, classes_path):print("XML root path:", xml_root_path)print("TXT save path:", txt_save_path)print("Classes path:", classes_path)if not os.path.exists(txt_save_path):os.makedirs(txt_save_path)print("Directory created:", txt_save_path)xml_paths = glob.glob(os.path.join(xml_root_path, '*.xml'))print("XML files found:", xml_paths)classes, _ = get_classes(classes_path)for xml_id in xml_paths:print("Processing file:", xml_id)txt_id = os.path.join(txt_save_path, os.path.basename(xml_id)[:-4] + '.txt')txt = open(txt_id, 'w')xml = open(xml_id, encoding='utf-8')tree = ET.parse(xml)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 = 0if obj.find('difficult') is not None:difficult = obj.find('difficult').textcls = obj.find('name').textprint("Class found:", cls)if cls not in classes or int(difficult) == 1:continuecls_id = classes.index(cls)xmlbox = obj.find('bndbox')b = (int(float(xmlbox.find('xmin').text)), int(float(xmlbox.find('xmax').text)),int(float(xmlbox.find('ymin').text)), int(float(xmlbox.find('ymax').text)))box = convert((w, h), b)txt.write(str(cls_id) + ' ' + ' '.join([str(a) for a in box]) + '\n')txt.close()print("TXT file created:", txt_id)
if __name__ == '__main__':# 用户输入XML文件路径和TXT文件存放路径xml_root_path = r"D:\CVproject\ultralytics-main\datatrans\labels"txt_save_path = r"D:\CVproject\ultralytics-main\datatrans\txt"classes_path = r"D:\CVproject\ultralytics-main\datatrans\labels.txt"convert_xml_to_yolo(xml_root_path, txt_save_path, classes_path)
2.使用方法
xml_root_path里边复制你的xml文件夹的绝对路径
txt_save_path里边复制你转换后的标签的存放地址
classes_path里边复制你的数据集类别的说明文件的存放地址(第三步细讲)
xml_root_path = r"D:\CVproject\ultralytics-main\datatrans\Annotations"
txt_save_path = r"D:\CVproject\ultralytics-main\datatrans\txt1"
classes_path = r"D:\CVproject\ultralytics-main\datatrans\labels.txt"
3.labels.txt
这个文件需要你自己创建一个txt文件,名字要用这个labels别换,里边的内容放你的数据集的标签,一个类别一行,注意大小写,不要有多余的标点符号
如果你的标签里类别的首字母大小写不一,那就回出错,处理方法请看我的另外一篇博客!!!!