数据集标签转换,XML转YOLO

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

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

似苦又甜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值