wjs/yolo_safehat_num_v8/datasets/voc2txt.py

35 lines
1.3 KiB
Python

import os
import xml.etree.ElementTree as ET
dirpath = r'D:\1BNS_projects\yolo_safehat_num_v8\datasets\labels1' # 原始XML文件的目录
newdir = r'D:\1BNS_projects\yolo_safehat_num_v8\datasets\label_lll' # 存放转换后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('转换完成!')