YOLO数据集格式转换(xml转txt)
其中每行包含图像中每个对象的类别 ID 和边界框坐标(通常是中心坐标和宽度高度)。而 XML 文件格式是另一种常见的标注数据格式,特别是在 Pascal VOC 数据集中。YOLO(You Only Look Once)是一种流行的目标检测算法,它通常使用特定的文件格式来存储标注数据。YOLO 使用的标签文件格式是。本文的作用是转换voc数据集的格式为yolo所用。
·
前言:
YOLO(You Only Look Once)是一种流行的目标检测算法,它通常使用特定的文件格式来存储标注数据。YOLO 使用的标签文件格式是 .txt
,其中每行包含图像中每个对象的类别 ID 和边界框坐标(通常是中心坐标和宽度高度)。而 XML 文件格式是另一种常见的标注数据格式,特别是在 Pascal VOC 数据集中。
本文的作用是转换voc数据集的格式为yolo所用。
代码:
import os
import xml.etree.ElementTree as ET
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(xml_file, classes, output_dir):
tree = ET.parse(xml_file)
root = tree.getroot()
size = root.find('size')
w = int(size.find('width').text)
h = int(size.find('height').text)
with open(os.path.join(output_dir, os.path.basename(xml_file).split('.')[0] + '.txt'), 'w') as out_file:
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')
def convert_all_annotations(xml_dir, classes, output_dir):
if not os.path.exists(output_dir):
os.makedirs(output_dir)
for xml_file in os.listdir(xml_dir):
if xml_file.endswith('.xml'):
convert_annotation(os.path.join(xml_dir, xml_file), classes, output_dir)
if __name__ == "__main__":
# 替换为实际的类别名称列表,nc(number of class)有几个就写几个
classes = ["class1", "class2", "class3"]
# XML 文件所在的目录,建议写绝对路径
xml_dir = "path/to/xml/files"
# 输出 txt 文件所在的目录,建议写绝对路径
output_dir = "path/to/output/txt/files"
convert_all_annotations(xml_dir, classes, output_dir)
使用说明:
- 替换类别名称:将
classes
列表替换为你的数据集中的实际类别名称。 - 设置目录路径:将
xml_dir
设置为包含 XML 文件的目录路径,将output_dir
设置为你想保存生成的.txt
文件的目录路径。

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐
所有评论(0)