.xml数据集转yolo.txt数据集

.xml数据集转yolo.txt数据集

import os
import xml.etree.ElementTree as ET

# 设置数据集路径和YOLOv5格式的标注文件保存路径
data_dir = 'C:/Users/Administrator/Desktop/图片/labels2'
output_dir = 'C:/Users/Administrator/Desktop/图片/yolo'

# 创建输出目录
if not os.path.exists(output_dir):
    os.makedirs(output_dir)

# 遍历数据集文件夹
for xml_file in os.listdir(data_dir):
    if xml_file.endswith('.xml'):
        # 解析XML文件
        tree = ET.parse(os.path.join(data_dir, xml_file))
        root = tree.getroot()

        # 提取图像宽度和高度
        width = int(root.find('size/width').text)
        height = int(root.find('size/height').text)

        # 创建YOLOv5格式的TXT文件
        txt_file = os.path.splitext(xml_file)[0] + '.txt'
        with open(os.path.join(output_dir, txt_file), 'w') as txt:
            for obj in root.findall('object'):
                class_name = obj.find('name').text
                x_min = int(obj.find('bndbox/xmin').text)
                y_min = int(obj.find('bndbox/ymin').text)
                x_max = int(obj.find('bndbox/xmax').text)
                y_max = int(obj.find('bndbox/ymax').text)

                # 计算中心点和归一化坐标
                x_center = (x_min + x_max) / (2 * width)
                y_center = (y_min + y_max) / (2 * height)
                width_norm = (x_max - x_min) / width
                height_norm = (y_max - y_min) / height

                # 将信息写入TXT文件
                txt.write(f'{class_name} {x_center} {y_center} {width_norm} {height_norm}\n')

print("已将XML数据集转换为YOLOv5格式的TXT文件。")

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值