xml转化为txt数据的脚本,为yolo提供训练

这里写自定义目录标题

xml转化为txt数据的脚本

代码如下:

bash 复制代码
import xml.etree.ElementTree as ET
import os, cv2
import numpy as np
from os import listdir
from os.path import join

classes = []


def convert(size, box):
    dw = 1. / (size[0])
    dh = 1. / (size[1])
    x = (box[0] + box[1]) / 2.0 - 1
    y = (box[2] + box[3]) / 2.0 - 1
    w = box[1] - box[0]
    h = box[3] - box[2]
    x = x * dw
    w = w * dw
    y = y * dh
    h = h * dh
    return (x, y, w, h)


def convert_annotation(xmlpath, xmlname):
    with open(xmlpath, "r", encoding='utf-8') as in_file:
        txtname = xmlname[:-4] + '.txt'
        txtfile = os.path.join(txtpath, txtname)
        tree = ET.parse(in_file)
        root = tree.getroot()
        filename = root.find('filename')
        img = cv2.imdecode(np.fromfile('{}/{}.{}'.format(imgpath, xmlname[:-4], postfix), np.uint8), cv2.IMREAD_COLOR)
        h, w = img.shape[:2]
        res = []
        for obj in root.iter('object'):
            cls = obj.find('name').text
            if cls not in classes:
                classes.append(cls)
            cls_id = classes.index(cls)
            xmlbox = obj.find('bndbox')
            b = (float(xmlbox.find('xmin').text), float(xmlbox.find('xmax').text), float(xmlbox.find('ymin').text),
                 float(xmlbox.find('ymax').text))
            bb = convert((w, h), b)
            res.append(str(cls_id) + " " + " ".join([str(a) for a in bb]))
        if len(res) != 0:
            with open(txtfile, 'w+') as f:
                f.write('\n'.join(res))


if __name__ == "__main__":
    postfix = 'jpg'
    imgpath = 'JPEGImages_Val'
    xmlpath = 'Annotations_Val'
    txtpath = 'labels_Val'

    if not os.path.exists(txtpath):
        os.makedirs(txtpath, exist_ok=True)

    list = os.listdir(xmlpath)
    error_file_list = []
    for i in range(0, len(list)):
        try:
            path = os.path.join(xmlpath, list[i])
            if ('.xml' in path) or ('.XML' in path):
                convert_annotation(path, list[i])
                print(f'file {list[i]} convert success.')
            else:
                print(f'file {list[i]} is not xml format.')
        except Exception as e:
            print(f'file {list[i]} convert error.')
            print(f'error message:\n{e}')
            error_file_list.append(list[i])
    print(f'this file convert failure\n{error_file_list}')
    print(f'Dataset Classes:{classes}')
相关推荐
whcyhhh9 分钟前
头歌实践教学平台:数据科学与大数据技术导论(十八4)
大数据·开发语言·python
编码者卢布9 分钟前
【Azure Developer】通过 API 获取 Azure VM 信息实践指南 Part 2(Azure China)
python·flask·azure
65岁退休Coder18 分钟前
LangGraph v1.2.9 核心概念 & 流程控制
后端·python·langchain
磁场转动100万匹21 分钟前
深度学习入门:从神经网络到反向传播的完整解析
人工智能·深度学习·神经网络
IPdodo_25 分钟前
2026年AI 数据采集代理 IP 选型:成功率、并发、轮换与成本评估
前端·网络·人工智能·chrome·python·http·网络调试
啥都想学点的研究生31 分钟前
一篇文章讲清楚:超参数的选择方法——交叉验证和网格搜索
人工智能·深度学习·机器学习
点PY1 小时前
《一种基于深度学习的超分辨率重建方法及系统》专利精读
人工智能·深度学习·超分辨率重建
烂蜻蜓1 小时前
Flask入门教程(七):请求与响应——Web应用的核心数据流
前端·python·flask
web行路人1 小时前
AI 全栈学习之旅 - Week4:容器化部署与生产环境实战
python·学习
春涧草茶1 小时前
慢就是快 - 10-2函数 特殊字面量 返回值
python