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}')
相关推荐
Data_agent7 分钟前
OOPBUY模式淘宝1688代购系统搭建指南
开发语言·爬虫·python
张哈大11 分钟前
AI Ping 上新限免:GLM-4.7 与 MiniMax-M2.1 实测对比
人工智能·python
乘凉~12 分钟前
【Linux作业】Limux下的python多线程爬虫程序设计
linux·爬虫·python
那雨倾城17 分钟前
YOLO + MediaPipe 在PiscCode上解决多脸 Landmark 中「人脸数量固定」的问题
图像处理·人工智能·深度学习·yolo·目标检测·计算机视觉
xwill*23 分钟前
pytorch中项目配置文件的管理与导入方式
人工智能·python
BBB努力学习程序设计41 分钟前
Python模块与包:构建可维护的代码结构
python
BBB努力学习程序设计42 分钟前
Python函数深度解析:从基础到高级装饰器
python·pycharm
智驱力人工智能44 分钟前
从合规到习惯 海上作业未穿救生衣AI识别系统的工程实践与体系价值 未穿救生衣检测 AI救生衣状态识别 边缘计算救生衣监测设备
人工智能·深度学习·opencv·算法·目标检测·边缘计算
抹除不掉的轻狂丶1 小时前
Java 日志框架完整指南:发展历史、核心组成与最佳实践
java·开发语言·python
目标是分享一切1 小时前
python卸载的时候出现0x80070643如何解决
python