import os
import xml.etree.ElementTree as ET
def convert_xml_to_yolo(xml_file, img_width, img_height, output_dir):
base_name = os.path.splitext(os.path.basename(xml_file))[0]
txt_file_path = os.path.join(output_dir, f"{base_name}.txt")
tree = ET.parse(xml_file)
root = tree.getroot()
with open(txt_file_path, 'w') as file:
for obj in root.findall('object'):
class_id = 0 # Assuming all objects are 'vehicle' and are class 0
bndbox = obj.find('bndbox')
xmin = int(bndbox.find('xmin').text)
ymin = int(bndbox.find('ymin').text)
xmax = int(bndbox.find('xmax').text)
ymax = int(bndbox.find('ymax').text)
x_center = ((xmin + xmax) / 2) / img_width
y_center = ((ymin + ymax) / 2) / img_height
width = (xmax - xmin) / img_width
height = (ymax - ymin) / img_height
file.write(f"{class_id} {x_center:.6f} {y_center:.6f} {width:.6f}
数据集标签转换,XML转YOLO
于 2024-07-31 11:14:32 首次发布