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} {height:.6f}\n")
def process_all_xml(directory, img_width, img_height):
output_dir = os.path.join(directory, "yolo_labels")
if not os.path.exists(output_dir):
os.makedirs(output_dir)
for filename in os.listdir(directory):
if filename.endswith('.xml'):
xml_file_path = os.path.join(directory, filename)
convert_xml_to_yolo(xml_file_path, img_width, img_height, output_dir)
print(f"Processed {xml_file_path} to {output_dir}")
# Example usage
directory = r'D:\Dataset\original\annotations'
img_width = 1920 # Replace with actual image width
img_height = 1080 # Replace with actual image height
process_all_xml(directory, img_width, img_height)
将XML标签文件夹的地址给directory;
输入图像像素1920,1080
脚本会在你的XML标签文件夹内生成一个子文件夹名为:yolo_labels