yolo数据集xml转txt
时间: 2023-11-10 22:07:18 浏览: 151
您可以使用以下代码将YOLO数据集的XML文件转换为TXT文件:
```python
import os
import glob
import xml.etree.ElementTree as ET
classes = ['class1', 'class2', 'class3'] # 标注的类别
def convert_annotation(xml_file):
tree = ET.parse(xml_file)
root = tree.getroot()
txt_file = os.path.splitext(xml_file)[0] + '.txt'
with open(txt_file, 'w') as f:
for obj in root.iter('object'):
cls = obj.find('name').text
if cls not in classes:
continue
cls_id = classes.index(cls)
xmlbox = obj.find('bndbox')
b = (int(xmlbox.find('xmin').text), int(xmlbox.find('ymin').text), int(xmlbox.find('xmax').text), int(xmlbox.find('ymax').text))
bb = convert((w,h), b)
f.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')
def convert(size, box):
dw = 1./size[0]
dh = 1./size[1]
x = (box[0] + box[2])/2.0
y = (box[1] + box[3])/2.0
w = box[2] - box[0]
h = box[3] - box[1]
x = x*dw
w = w*dw
y = y*dh
h = h*dh
return (x,y,w,h)
if __name__ == '__main__':
xml_files = glob.glob('path/to/xml/files/*.xml')
for xml_file in xml_files:
convert_annotation(xml_file)
```
其中,`classes`是标注的类别,`convert_annotation`函数将一个XML文件转换为一个TXT文件,`convert`函数将一个边界框的坐标转换为YOLO格式。
阅读全文