将 VOC 格式 XML 转换为 YOLO 格式 TXT

目录

[1. 导入必要的模块](#1. 导入必要的模块)

[2. 定义类别名称](#2. 定义类别名称)

[3. 设置文件路径](#3. 设置文件路径)

完整代码


1. 导入必要的模块

import os

import xml.etree.ElementTree as ET

os:用于文件和目录操作,例如创建目录、遍历文件等。

xml.etree.ElementTree:用于解析XML文件,从中提取信息。

2. 定义类别名称

class_names = ['nest', 'balloon', 'kite', 'trash']

这是一个列表,定义了数据集中所有物体的类别名称。类别名称的顺序非常重要,因为它们的索引(从0开始)将作为YOLO格式中的class_id。

3. 设置文件路径

xmlpath = 'C:/Users/10431/Desktop/4517+VOC/Annotations/Annotations/'

txtpath = 'C:/Users/10431/Desktop/4517+VOC/Annotations/yolo/'

xmlpath:VOC格式的XML文件所在的目录路径。

txtpath:转换后的YOLO格式TXT文件将保存的目录路径。

完整代码

python 复制代码
import os
import xml.etree.ElementTree as ET

# 定义类别名称
class_names = ['nest', 'balloon', 'kite', 'trash']

# 设置输入和输出路径
xmlpath = 'C:/Users/10431/Desktop/4517+VOC/Annotations/Annotations/'
txtpath = 'C:/Users/10431/Desktop/4517+VOC/Annotations/yolo/'

# 如果输出目录不存在,则创建
if not os.path.exists(txtpath):
    os.makedirs(txtpath)

# 收集所有 XML 文件
files = [os.path.join(root, file) for root, _, files in os.walk(xmlpath) for file in files if file.endswith('.xml')]
number = len(files)
print(f"找到 {number} 个 XML 文件")

# 遍历并转换每个 XML 文件
for i, xml_file_path in enumerate(files):
    # 提取文件名并构建输出路径
    name = os.path.splitext(os.path.basename(xml_file_path))[0]
    txt_file_path = os.path.join(txtpath, name + '.txt')

    # 解析 XML 文件
    with open(xml_file_path, 'r') as xml_file:
        tree = ET.parse(xml_file)
        root = tree.getroot()
        w = int(root.find('size').find('width').text)  # 图像宽度
        h = int(root.find('size').find('height').text)  # 图像高度

    # 写入 TXT 文件
    with open(txt_file_path, 'w') as f_txt:
        content = ""
        first = True
        for obj in root.iter('object'):
            # 获取类别和边界框信息
            class_name = obj.find('name').text
            class_num = class_names.index(class_name)  # 类别的索引
            xmlbox = obj.find('bndbox')
            x1 = int(xmlbox.find('xmin').text)
            x2 = int(xmlbox.find('xmax').text)
            y1 = int(xmlbox.find('ymin').text)
            y2 = int(xmlbox.find('ymax').text)

            # 转换为 YOLO 格式
            x_center = (x1 + x2) / 2 / w
            y_center = (y1 + y2) / 2 / h
            width = (x2 - x1) / w
            height = (y2 - y1) / h

            # 构建 YOLO 格式的标注行
            line = f"{class_num} {x_center} {y_center} {width} {height}"
            content += line if first else f"\n{line}"
            first = False

        # 写入内容到 TXT 文件
        f_txt.write(content)
        print(f"已将 {name}.xml 转换为 {name}.txt")

print("转换完成!")
相关推荐
搞全栈小苏9 小时前
基于Qt QML和C++的MQTT测试客户端(CMakeLists实现)
xml·c++·qt
dragon_perfect15 小时前
全流程基于Yolov8实现在Label-Studio实现半自动标注,已经把整个流程理清楚,把所有的坑解决。
开发语言·python·yolo·labelstudio
HUIMU_15 小时前
YOLOv5实战-GPU版本的pytorch虚拟环境配置
人工智能·pytorch·深度学习·yolo
Coovally AI模型快速验证15 小时前
基于YOLO集成模型的无人机多光谱风电部件缺陷检测
人工智能·安全·yolo·目标跟踪·无人机
羊羊小栈15 小时前
基于「YOLO目标检测 + 多模态AI分析」的PCB缺陷检测分析系统(vue+flask+数据集+模型训练)
vue.js·人工智能·yolo·目标检测·flask·毕业设计·大作业
郭庆汝16 小时前
模型部署:(三)安卓端部署Yolov8-v8.2.99目标检测项目全流程记录
android·yolo·目标检测·yolov8
fatiaozhang952716 小时前
中国移动云电脑一体机-创维LB2004_瑞芯微RK3566_2G+32G_开启ADB ROOT安卓固件-方法3
android·xml·adb·电脑·电视盒子·刷机固件
格林威17 小时前
工业相机如何通过光度立体成像技术实现高效精准的2.5D缺陷检测
人工智能·深度学习·数码相机·yolo·计算机视觉
羊羊小栈17 小时前
基于「YOLO目标检测 + 多模态AI分析」的植物病害检测分析系统(vue+flask+数据集+模型训练)
人工智能·yolo·目标检测·毕业设计·创业创新·大作业
m_1368717 小时前
YOLOv8 mac-intel芯片 部署指南
yolo