XML转YOLO数据集

import os
import xml.etree.ElementTree as ET
 # VOC数据集路径
voc_ann_path = "\\Annotations\\"
voc_img_path = "\\JPEGImages\\"
# YOLO数据集路径
yolo_out_path = "\\OUT\\"
# VOC类别名称和对应的编号
classes = {"target": 0}  # 根据实际情况修改
 # 遍历VOC数据集文件夹
for filename in os.listdir(voc_ann_path):
    # 解析XML文件
    tree = ET.parse(voc_ann_path + filename)
    root = tree.getroot()
    # 获取图片尺寸
    size = root.find("size")
    width = int(size.find("width").text)
    height = int(size.find("height").text)
    # 创建YOLO标注文件
    yolo_filename = filename.replace(".xml", ".txt")
    yolo_file = open(yolo_out_path + yolo_filename, "w")
    # 遍历XML文件中的所有目标
    for obj in root.findall("object"):
        # 获取目标类别名称和边界框坐标
        name = obj.find("name").text
        xmin = int(obj.find("bndbox").find("xmin").text)
        ymin = int(obj.find("bndbox").find("ymin").text)
        xmax = int(obj.find("bndbox").find("xmax").text)
        ymax = int(obj.find("bndbox").find("ymax").text)
        # 计算边界框中心点坐标和宽高
        x = (xmin + xmax) / 2 / width
        y = (ymin + ymax) / 2 / height
        w = (xmax - xmin) / width
        h = (ymax - ymin) / height
        # 将目标写入YOLO标注文件
        class_id = classes[name]
        yolo_file.write(f"{class_id} {x} {y} {w} {h}\n")
    yolo_file.close()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值