将目标检测数据集中的xml标签转换为txt文件,方便训练
import os
import xml.etree.ElementTree as ET
dirpath = './1/' # 原始XML文件的目录
newdir = './3/' # 存放转换后TXT文件的目录
if not os.path.exists(newdir):
os.makedirs(newdir)
for xml_file in os.listdir(dirpath):
xml_path = os.path.join(dirpath, xml_file)
tree = ET.parse(xml_path)
root = tree.getroot()
filename = root.find('filename').text
with open(os.path.join(newdir, xml_file.split('.')[0] + '.txt'), 'w') as txt_file:
for obj in root.findall('object'):
label = obj.find('name').text
bbox = obj.find('bndbox')
xmin = float(bbox.find('xmin').text)
ymin = float(bbox.find('ymin').text)
xmax = float(bbox.find('xmax').text)
ymax = float(bbox.find('ymax').text)
width = float(root.find('size').find('width').text)
height = float(root.find('size').find('height').text)
x_center = (xmin + xmax) / (2 * width)
y_center = (ymin + ymax) / (2 * height)
w = (xmax - xmin) / width
h = (ymax - ymin) / height
txt_file.write(f"{label} {x_center} {y_center} {w} {h}\n")
print('转换完成!')