yolo格式的txt与labelimg的xml文件互转

本文介绍了一种用于将YOLOv5格式的TXT标签文件转换为Pascal VOC XML格式,并能逆向转换的方法。该工具通过Python脚本实现,能够处理图像目录下的图片尺寸信息并将其写入XML文件中,同时也能从XML文件中读取目标框坐标信息并转换回TXT格式。

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

txt2xml.py

import cv2
from pathlib import Path
from xml.dom.minidom import Document
 

img_dir = './dir/img/'              # 图片文件路径
txt_dir = './dir/txt/'              # txt文件路径
xml_dir = './dir/xml/'              # xml文件路径   
labels = {'0':'person', '1':'car'}  # 标签名

files = Path(txt_dir).glob('*txt')

for file in files:
    print(file)
    xmlBuilder = Document()
    annotation = xmlBuilder.createElement('annotation')  # 创建annotation标签
    xmlBuilder.appendChild(annotation)
    txtFile = open(file)
    txtList = txtFile.readlines()
    img = cv2.imread(img_dir + file.stem + '.jpg')
    h, w, d = img.shape

    filename = xmlBuilder.createElement('filename')  # filename标签
    filenamecontent = xmlBuilder.createTextNode(img_dir + file.stem + '.jpg')
    filename.appendChild(filenamecontent)
    annotation.appendChild(filename)  # filename标签结束

    size = xmlBuilder.createElement('size')  # size标签
    width = xmlBuilder.createElement('width')  # size子标签width
    widthcontent = xmlBuilder.createTextNode(str(w))
    width.appendChild(widthcontent)
    size.appendChild(width)  # size子标签width结束

    height = xmlBuilder.createElement('height')  # size子标签height
    heightcontent = xmlBuilder.createTextNode(str(h))
    height.appendChild(heightcontent)
    size.appendChild(height)  # size子标签height结束

    depth = xmlBuilder.createElement('depth')  # size子标签depth
    depthcontent = xmlBuilder.createTextNode(str(d))
    depth.appendChild(depthcontent)
    size.appendChild(depth)  # size子标签depth结束

    annotation.appendChild(size)  # size标签结束

    for line in txtList:
        oneline = line.strip().split(' ')
        object = xmlBuilder.createElement('object')  # object 标签
        picname = xmlBuilder.createElement('name')  # name标签
        namecontent = xmlBuilder.createTextNode(labels[oneline[0]])
        picname.appendChild(namecontent)
        object.appendChild(picname)  # name标签结束

        bndbox = xmlBuilder.createElement('bndbox')  # bndbox标签
        xmin = xmlBuilder.createElement('xmin')  # xmin标签
        mathData = int(((float(oneline[1])) * w) - (float(oneline[3])) * 0.5 * w)
        xminContent = xmlBuilder.createTextNode(str(mathData))
        xmin.appendChild(xminContent)
        bndbox.appendChild(xmin)  # xmin标签结束

        ymin = xmlBuilder.createElement('ymin')  # ymin标签
        mathData = int(((float(oneline[2])) * h) - (float(oneline[4])) * 0.5 * h)
        yminContent = xmlBuilder.createTextNode(str(mathData))
        ymin.appendChild(yminContent)
        bndbox.appendChild(ymin)  # ymin标签结束

        xmax = xmlBuilder.createElement('xmax')  # xmax标签
        mathData = int(((float(oneline[1])) * w) + (float(oneline[3])) * 0.5 * w)
        xmaxContent = xmlBuilder.createTextNode(str(mathData))
        xmax.appendChild(xmaxContent)
        bndbox.appendChild(xmax)  # xmax标签结束

        ymax = xmlBuilder.createElement('ymax')  # ymax标签
        mathData = int(((float(oneline[2])) * h) + (float(oneline[4])) * 0.5 * h)
        ymaxContent = xmlBuilder.createTextNode(str(mathData))
        ymax.appendChild(ymaxContent)
        bndbox.appendChild(ymax)  # ymax标签结束

        object.appendChild(bndbox)  # bndbox标签结束

        annotation.appendChild(object)  # object标签结束

    f = open(xml_dir + file.stem + '.xml', 'w')
    xmlBuilder.writexml(f, indent='\t', newl='\n', addindent='\t', encoding='utf-8')
    f.close()

xml2txt.py

from pathlib import Path
import xml.etree.ElementTree as ET

xml_dir = r'./dir/xml/'         # xml文件路径
txt_dir = r'./dir/txt/'         # txt文件路径
labels = {'0': "person", '1': "car"} # 标签名


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

    x = x / dw
    y = y / dh
    w = w / dw
    h = h / dh

    return x,y,w,h


files = Path(xml_dir).glob('*xml')

for file in files:
    print(file)
    name = file.stem
    xml_o = open(xml_dir + '%s.xml'%name)
    txt_o = open(txt_dir + '%s.txt'%name,'w')

    pares = ET.parse(xml_o)
    root = pares.getroot()
    objects = root.findall('object')
    size = root.find('size')
    dw = int(size.find('width').text)
    dh = int(size.find('height').text)

    for obj in objects:
        cls = list(labels.values()).index(obj.find('name').text)
        bnd = obj.find('bndbox')
        b = (float(bnd.find('xmin').text),float(bnd.find('ymin').text), float(bnd.find('xmax').text),float(bnd.find('ymax').text))
        x,y,w,h = convert(b,dw,dh)
        write_t = '{} {:.5f} {:.5f} {:.5f} {:.5f}\n'.format(cls,x,y,w,h)
        txt_o.write(write_t)

    xml_o.close()
    txt_o.close()
### 将YOLO格式txt标注文件转换为Pascal VOC XML格式 #### 创建必要的目录结构 为了便于管理和处理不同格式的数据,建议创建如下所示的三个文件夹: - `txt` 文件夹用于存储原始 YOLO 格式txt 标签文件。 - `xml` 文件夹专门用来保存转换后的 Pascal VOC xml 标签文件。 - `picture` 文件夹放置对应的图像文件。 确保将 yolo 数据集中的图片和 txt 标签按照上述分类存放在相应的文件夹内[^1]。 #### 清理TXT标签文件 在进行转换之前,需清理 `txt` 文件夹内的所有 txt 文件,移除其中可能存在的类别名称或其他不必要的信息,仅保留目标边界框坐标等必要参数。这一步骤对于后续顺利执行转换至关重要。 #### 编写Python脚本实现自动转换 下面提供一段 Python 脚本来完成从 YOLO 到 Pascal VOC 的自动化转换过程: ```python import os from xml.etree.ElementTree import Element, SubElement, tostring from xml.dom.minidom import parseString def create_pascal_voc_xml(image_name, image_size, objects): node_root = Element('annotation') node_folder = SubElement(node_root, 'folder') node_folder.text = 'VOC' node_filename = SubElement(node_root, 'filename') node_filename.text = image_name node_source = SubElement(node_root, 'source') node_database = SubElement(node_source, 'database') node_database.text = 'Unknown' node_size = SubElement(node_root, 'size') node_width = SubElement(node_size, 'width') node_height = SubElement(node_size, 'height') node_depth = SubElement(node_size, 'depth') width, height, depth = image_size node_width.text = str(width) node_height.text = str(height) node_depth.text = str(depth) for obj in objects: class_label, xmin, ymin, xmax, ymax = obj node_object = SubElement(node_root, 'object') node_name = SubElement(node_object, 'name') node_pose = SubElement(node_object, 'pose') node_truncated = SubElement(node_object, 'truncated') node_difficult = SubElement(node_object, 'difficult') node_bndbox = SubElement(node_object, 'bndbox') node_name.text = class_label node_pose.text = 'Unspecified' node_truncated.text = '0' node_difficult.text = '0' node_xmin = SubElement(node_bndbox, 'xmin') node_ymin = SubElement(node_bndbox, 'ymin') node_xmax = SubElement(node_bndbox, 'xmax') node_ymax = SubElement(node_bndbox, 'ymax') node_xmin.text = str(xmin) node_ymin.text = str(ymin) node_xmax.text = str(xmax) node_ymax.text = str(ymax) return node_root def convert_yolo_to_pascal_voc(txt_path, img_info_dict): with open(txt_path, 'r') as f: lines = f.readlines() objs = [] for line in lines: parts = line.strip().split() cls_id = int(parts[0]) center_x = float(parts[1]) * img_info_dict['width'] center_y = float(parts[2]) * img_info_dict['height'] bbox_w = float(parts[3]) * img_info_dict['width'] bbox_h = float(parts[4]) * img_info_dict['height'] xmin = max(int(center_x - (bbox_w / 2)), 0) ymin = max(int(center_y - (bbox_h / 2)), 0) xmax = min(int(center_x + (bbox_w / 2)), img_info_dict['width']) ymax = min(int(center_y + (bbox_h / 2)), img_info_dict['height']) label = list(img_info_dict["classes"])[cls_id] objs.append((label, xmin, ymin, xmax, ymax)) tree = create_pascal_voc_xml( os.path.basename(img_info_dict['path']), ( img_info_dict['width'], img_info_dict['height'], img_info_dict.get('channels', 3), ), objs, ) dom = parseString(tostring(tree)).toprettyxml(indent=" ") output_file = os.path.join(os.getcwd(), "xml", os.path.splitext(os.path.basename(txt_path))[0]+".xml") with open(output_file, 'w+') as out_f: out_f.write(dom) if __name__ == "__main__": images_dir = './pictures' # 图片所在路径 labels_dir = './txt' # 原始YOLO标签所在的路径 classes = ['person'] # 类别列表,按实际情况修改 files = [f for f in os.listdir(labels_dir) if f.endswith('.txt')] for file in files: path = os.path.join(images_dir, os.path.splitext(file)[0] + '.jpg') size = {'width': 800, 'height': 600} # 替换为实际尺寸获取方式 info = { 'path': path, 'width': size['width'], 'height': size['height'], 'classes': set(classes), } convert_yolo_to_pascal_voc(os.path.join(labels_dir, file), info) ``` 此代码片段展示了如何读取 YOLO 风格的目标检测标签并将其转换为符合 Pascal VOC 规范的 XML 文档。需要注意的是,在真实应用场景中应当动态获取每张图片的实际宽度高度而不是硬编码固定值,并且应根据具体项目调整类名映射关系表[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

给算法爸爸上香

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值