做yolo5目标检测训练时,很多小伙伴遇到了xml转txt数据集的问题,我把转换代码贴到下面,有需要自取。
```python
import xml.etree.ElementTree as ET
import os
from os import listdir, getcwd
from os.path import join
outpath = "E:\\Documents\\person\\labels"
xmlpaths = "E:\\Documents\\person\\xml"
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 xmlTotxt():
xmls = os.listdir(xmlpaths)
for xml in xmls:
xmlpath = os.path.join(xmlpaths, xml)
tree = ET.parse(xmlpath)
root = tree.getroot()
size = root.find('size')
w = int(size.find('width').text)
h = int(size.find('height').text)
out_file = os.path.join(outpath, xml.split('.')[0] + '.txt')
out_txt_f = open(out_file, 'w')
for obj in root.iter('object'):
cls_id = 1
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_txt_f.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')
out_txt_f.close()
def main():
xmlTotxt()
print("finished")
if __name__ == "__main__":
main()