废话少说,直接上干货!
标签:xml,box,YOLO,classes,path,txt,find From: https://blog.csdn.net/mywhyyds/article/details/142901427首先,我先介绍一下代码的使用,编程语言为“Python”,共有三处需按照自己的需求修改的,我都放在代码最下面了。
xml_root_path:输入你的xml格式的文件存放位置,建议全部用绝对路径txt_save_path:输入你的txt格式的文件导出后的存放位置classes_path:输入你的labels.txt格式的文件的存放位置(这里注意,在随便哪个地方新建一个labels.txt文件,必须叫这个名哈不然错了别找我,输入你数据集的类别名,有几类输几类,一行一个类别名,不需要加任何标点符号,逗号冒号的统统不要加,大小写一定要对,空格也不要多加,和你xml里面的类别名必须一样,不知道类别名的打开你的xml文件自己看看确认,不然输出的txt文件内容为空你也别找我,自己好好看)import os import glob import xml.etree.ElementTree as ET def 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.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_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 = 0 if obj.find('difficult') is not None: difficult = obj.find('difficult').text cls = obj.find('name').text print("Class found:", cls) if cls not in classes or int(difficult) == 1: continue cls_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"C:\Users\DELL\Desktop\seaships\Annotations" txt_save_path = r"C:\Users\DELL\Desktop\Seaships(7000)\labels" classes_path = r"C:\Users\DELL\Desktop\labels.txt" convert_xml_to_yolo(xml_root_path, txt_save_path, classes_path)