将VOC数据集转化为YOLO(TXT)格式

本文讲述的是将VOC的(xml)转化为YOLO(txt)格式

分别在自己的python内创建一个txt文件夹和xml文件夹

xml文件夹里面存放voc的xml文件

import os
import xml.etree.ElementTree as ET

# 定义标签名称和类别映射
label_map = {"face": "0","face_mask":"1"}

# 输入和输出文件夹路径
xml_folder = "xml"
txt_folder = "txt"

# 遍历所有的XML文件
for xml_file in os.listdir(xml_folder):
    if not xml_file.endswith(".xml"):
        continue

    # 解析XML文件
    tree = ET.parse(os.path.join(xml_folder, xml_file))
    root = tree.getroot()

    # 获取图像大小
    size = root.find("size")
    width = int(size.find("width").text)
    height = int(size.find("height").text)

    # 遍历所有的标注框
    for obj in root.iter("object"):
        label = obj.find("name").text
        if label not in label_map:
            continue

        # 获取标注框的位置
        bbox = obj.find("bndbox")
        xmin = float(bbox.find("xmin").text)
        ymin = float(bbox.find("ymin").text)
        xmax = float(bbox.find("xmax").text)
        ymax = float(bbox.find("ymax").text)

        # 将坐标转换为YOLO格式
        x_center = (xmin + xmax) / 2 / width
        y_center = (ymin + ymax) / 2 / height
        w = (xmax - xmin) / width
        h = (ymax - ymin) / height

        # 写入到txt文件中
        txt_file = os.path.splitext(xml_file)[0] + ".txt"
        with open(os.path.join(txt_folder, txt_file), "a") as f:
            f.write(f"{label_map[label]} {x_center:.6f} {y_center:.6f} {w:.6f} {h:.6f}\n")

label_map:存放类别名称

xml_folder和txt_folder:分别是xml数据 和一个空的txt文件夹 用于存放处理好的文件

以下是处理后的结果:⏬️  0代表类别名

刚开始做可能写的不够好  如有不足的地方可以提出谢谢🙏 ❤️

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

299KMG

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

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

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

打赏作者

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

抵扣说明:

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

余额充值