VOC格式转化YOLO格式

import xml.etree.ElementTree as ET
import os

# xml文件所在目录
xml_dir = "C:/Users/"
# Yolo格式文件保存目录
yolo_dir = "C:/Users/"
# 类别名称和数字标签的映射
class_map = {"Cyclist": 0,"Car": 1}

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

    # 解析XML文件
    tree = ET.parse(os.path.join(xml_dir, 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"):
        # 获取类别和边界框坐标
        cls_name = obj.find("name").text
        if cls_name not in class_map:
            continue

        cls_id = class_map[cls_name]

        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)

        # 计算归一化坐标
        x = (xmin + xmax) / (2 * width)
        y = (ymin + ymax) / (2 * height)
        w = (xmax - xmin) / width
        h = (ymax - ymin) / height

        # 将信息写入Yolo格式文件
        yolo_file = os.path.splitext(xml_file)[0] + ".txt"
        with open(os.path.join(yolo_dir, yolo_file), "a") as f:
            f.write(f"{cls_id} {x:.6f} {y:.6f} {w:.6f} {h:.6f}\n")

VOC格式转化YOLO格式,需要补充xml文件所在目录,Yolo格式文件保存目录和类别名称和数字标签的映射。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值