将txt转换成xml的代码

本文介绍如何利用编程将YoloV3检测结果的txt文件转换为XML格式,适用于目标检测数据集的管理和进一步处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

yolov3将检测出的目标坐标并保存到本地。

import os,shutil
import cv2
from lxml.etree import Element, SubElement, tostring

def txt_xml(img_path, img_name, txt_path, img_txt, xml_path, img_xml):
    #读取txt的信息
    clas=[]
    img=cv2.imread(os.path.join(img_path,img_name))
    imh, imw = img.shape[0:2]
    txt_img=os.path.join(txt_path,img_txt)
    with open(txt_img,"r") as f:
        next(f)
        for line in f.readlines():
            line = line.strip('\n')
            list = line.split(" ")
            # print(list)
            clas.append(list)
    node_root = Element('annotation')
    node_folder = SubElement(node_root, 'folder')
    node_folder.text = 'JPEGImages'
    node_filename = SubElement(node_root, 'filename')
    #图像名称
    node_filename.text = img_name
    node_size = SubElement(node_root, 'size')
    node_width = SubElement(node_size, 'width')
    node_width.text = str(imw)
    node_height = SubElement(node_size, 'height')
    node_height.text = str(imh)
    node_depth = SubElement(node_size, 'depth')
    node_depth.text = '3'
    for i in range(len(clas)):
        node_object = SubElement(node_root, 'object')
        node_name = SubElement(node_object, 'name')
        node_name.text = str(clas[i][0])
        node_pose=SubElement(node_object, 'pose')
        node_pose.text="Unspecified"
        node_truncated=SubElement(node_object, 'truncated')
        node_truncated.text="truncated"
        node_difficult = SubElement(node_object, 'difficult')
        node_difficult.text = '0'
        node_bndbox = SubElement(node_object, 'bndbox')

        node_xmin = SubElement(node_bndbox, 'xmin')
        node_xmin.text = str(clas[i][2])

        node_ymin = SubElement(node_bndbox, 'ymin')
        node_ymin.text = str(clas[i][3])

        node_xmax = SubElement(node_bndbox, 'xmax')
        node_xmax.text = str(int(clas[i][2])+int(clas[i][4]))

        node_ymax = SubElement(node_bndbox, 'ymax')
        node_ymax.text = str(int(clas[i][3])+int(clas[i][5]))

    xml = tostring(node_root, pretty_print=True)  # 格式化显示,该换行的换行
    img_newxml = os.path.join(xml_path, img_xml)
    file_object = open(img_newxml, 'wb')
    file_object.write(xml)
    file_object.close()

if __name__ == "__main__":
    #图像文件夹所在位置
    img_path = r"E:\PythonCode\YOLOv3-txt-xml\P"
    #标注文件夹所在位置
    txt_path = r"E:\PythonCode\YOLOv3-txt-xml\T"
    #txt转化成xml格式后存放的文件夹
    xml_path = r"E:\PythonCode\YOLOv3-txt-xml\X"
    for img_name in os.listdir(img_path):
        print(img_name)
        img_xml=img_name.split(".")[0]+".xml"
        img_txt=img_name.split(".")[0]+".txt"
        txt_xml(img_path, img_name, txt_path, img_txt, xml_path, img_xml)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值