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}')
相关推荐
ELI_He9992 分钟前
CLIP-ReID初尝试
人工智能·深度学习
yaoh.wang3 分钟前
力扣(LeetCode) 58: 最后一个单词的长度 - 解法思路
python·程序人生·算法·leetcode·面试·职场和发展·跳槽
深蓝海拓6 分钟前
PySide6从0开始学习的笔记(七) 控件(Widget)之文字输入类控件
笔记·python·qt·学习·pyqt
free-elcmacom6 分钟前
机器学习高阶教程<4>因果机器学习:因果推断、可解释AI与科学发现的新革命
人工智能·python·机器学习·因果机器学习
SACKings7 分钟前
神经元是什么?在深度学习中的数学表达是什么?
人工智能·深度学习
smile_Iris7 分钟前
Day 41 早停策略和模型权重的保存
开发语言·python
Coovally AI模型快速验证11 分钟前
复杂工业场景如何实现3D实例与部件一体化分割?多视角贝叶斯融合的分层图像引导框
人工智能·深度学习·计算机视觉·3d·语言模型·机器人
MediaTea13 分钟前
Python:接口隔离原则(ISP)
开发语言·网络·python·接口隔离原则
CoovallyAIHub15 分钟前
下一代驾驶员监测系统如何工作?视觉AI接管驾驶舱
深度学习·算法·计算机视觉
破烂pan17 分钟前
Elasticsearch 8.x + Python 官方客户端实战教程
python·elasticsearch