当前位置: 首页 > news >正文

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

这里写自定义目录标题

  • xml转化为txt数据的脚本

xml转化为txt数据的脚本

代码如下:

import xml.etree.ElementTree as ET
import os, cv2
import numpy as np
from os import listdir
from os.path import joinclasses = []def convert(size, box):dw = 1. / (size[0])dh = 1. / (size[1])x = (box[0] + box[1]) / 2.0 - 1y = (box[2] + box[3]) / 2.0 - 1w = box[1] - box[0]h = box[3] - box[2]x = x * dww = w * dwy = y * dhh = h * dhreturn (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').textif 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}')
http://www.lryc.cn/news/149183.html

相关文章:

  • 【H5页面嵌入到小程序或APP中实现手机号点击复制和拨号功能】
  • Kubernetes技术--k8s核心技术 configMap
  • Springboot动态修改日志级别
  • 新手将最简单的springboot部署上tomcat出现的意外问题
  • P1177 【模板】排序(Sort排序)
  • 软件测试(黑盒测试、白盒测试、灰盒测试)
  • 昨天面试的时候被提问到的问题集合。
  • 广电运营商三网融合监控运维方案
  • 数据库锁简析
  • 说说广播流与普通流
  • 内卷的本质和大数据在计量经济学领域的运用思考
  • 毕业设计-摄像头识别二维码
  • 封装动态表单组件
  • 提高Python并发性能 - asyncio/aiohttp介绍
  • 网络性能的四大指标:带宽、时延、抖动、丢包
  • MySQL高阶查询语句
  • 未来科技城携手加速科技 共建集成电路测试公共服务平台!
  • 渗透测试漏洞原理之---【失效的访问控制】
  • opencv的使用(Ubuntu linux环境,AS jni,AS java)
  • ChatGPT(对话AI)汇总
  • 【Docker】用Dockerfile制作个人的镜像文件
  • 前端面试基础面试题——4
  • 【08期】ArrayList常见面试题
  • Android studio之GridView使用
  • Ubuntu系统环境搭建(七)——Ubuntu安装MySQL8.0
  • Nginx详解 三:高级配置
  • mysql 表备份 遇到的问题 【全网最全】
  • 11.添加侧边栏,并导入数据
  • ThinkPHP 通用的API格式封装
  • 自己动手写数据库:实现一个小型 SQL 解释器(下)