Visdrone2019数据集.txt标签文件转换为voc格式.XML标签文件

最近有同学问是否有Visdrone数据集的xml文件,由于本人之前训练数据的时候没有保存xml文件,所以无法共享。

为了解决这个问题,重新写了转换代码并贴出,供大家共同学习使用。(文末附上数据下载网盘地址)

# coding: utf-8
# author: HXY
# 2020-4-17

"""
该脚本用于visdrone数据处理;
将annatations文件夹中的txt标签文件转换为XML文件;
txt标签内容为:
<bbox_left>,<bbox_top>,<bbox_width>,<bbox_height>,<score>,<object_category>,<truncation>,<occlusion>
类别:
ignored regions(0), pedestrian(1),
people(2), bicycle(3), car(4), van(5),
truck(6), tricycle(7), awning-tricycle(8),
bus(9), motor(10), others(11)
"""

import os
import cv2
import time
from xml.dom import minidom

name_dict = {'0': 'ignored regions', '1': 'pedestrian', '2': 'people',
             '3': 'bicycle', '4': 'car', '5': 'van', '6': 'truck',
             '7': 'tricycle', '8': 'awning-tricycle', '9': 'bus',
             '10': 'motor', '11': 'others'}


def transfer_to_xml(pic, txt, file_name):
    xml_save_path = 'xml'  # 生成的xml文件存储的文件夹
    if not os.path.exists(xml_save_path):
        os.mkdir(xml_save_path)

    img = cv2.imread(pic)
    img_w = img.shape[1]
    img_h = img.shape[0]
    img_d = img.shape[2]
    doc = minidom.Document()

    annotation = doc.createElement("annotation")
    doc.appendChild(annotation)
    folder = doc.createElement('folder')
    folder.appendChild(doc.createTextNode('visdrone'))
    annotation.appendChild(folder)

    filename = doc.createElement('filename')
    filename.appendChild(doc.createTextNode(file_name))
    annotation.appendChild(filename)

    source = doc.createElement('source')
    database = doc.createElement('database')
    database.appendChild(doc.createTextNode("Unknown"))
    source.appendChild(database)

    annotation.appendChild(source)

    size = doc.createElement('size')
    width = doc.createElement('width')
    width.appendChild(doc.createTextNode(str(img_w)))
    size.appendChild(width)
    height = doc.createElement('height')
    height.appendChild(doc.createTextNode(str(img_h)))
    size.appendChild(height)
    depth = doc.createElement('depth')
    depth.appendChild(doc.createTextNode(str(img_d)))
    size.appendChild(depth)
    annotation.appendChild(size)

    segmented = doc.createElement('segmented')
    segmented.appendChild(doc.createTextNode("0"))
    annotation.appendChild(segmented)

    with open(txt, 'r') as f:
        lines = [f.readlines()]
        for line in lines:
            for boxes in line:
                box = boxes.strip('\n')
                box = box.split(',')
                x_min = box[0]
                y_min = box[1]
                x_max = int(box[0]) + int(box[2])
                y_max = int(box[1]) + int(box[3])
                object_name = name_dict[box[5]]

                # if object_name is 'ignored regions' or 'others':
                #     continue

                object = doc.createElement('object')
                nm = doc.createElement('name')
                nm.appendChild(doc.createTextNode(object_name))
                object.appendChild(nm)
                pose = doc.createElement('pose')
                pose.appendChild(doc.createTextNode("Unspecified"))
                object.appendChild(pose)
                truncated = doc.createElement('truncated')
                truncated.appendChild(doc.createTextNode("1"))
                object.appendChild(truncated)
                difficult = doc.createElement('difficult')
                difficult.appendChild(doc.createTextNode("0"))
                object.appendChild(difficult)
                bndbox = doc.createElement('bndbox')
                xmin = doc.createElement('xmin')
                xmin.appendChild(doc.createTextNode(x_min))
                bndbox.appendChild(xmin)
                ymin = doc.createElement('ymin')
                ymin.appendChild(doc.createTextNode(y_min))
                bndbox.appendChild(ymin)
                xmax = doc.createElement('xmax')
                xmax.appendChild(doc.createTextNode(str(x_max)))
                bndbox.appendChild(xmax)
                ymax = doc.createElement('ymax')
                ymax.appendChild(doc.createTextNode(str(y_max)))
                bndbox.appendChild(ymax)
                object.appendChild(bndbox)
                annotation.appendChild(object)
                with open(os.path.join(xml_save_path, file_name + '.xml'), 'w') as x:
                    x.write(doc.toprettyxml())
                x.close()
    f.close()


if __name__ == '__main__':
    t = time.time()
    print('Transfer .txt to .xml...ing....')
    txt_folder = 'annotations'  # visdrone txt标签文件夹
    txt_file = os.listdir(txt_folder)
    img_folder = 'images'  # visdrone 照片所在文件夹

    for txt in txt_file:
        txt_full_path = os.path.join(txt_folder, txt)
        img_full_path = os.path.join(img_folder, txt.split('.')[0] + '.jpg')

        try:
            transfer_to_xml(img_full_path, txt_full_path, txt.split('.')[0])
        except Exception as e:
            print(e)

    print("Transfer .txt to .XML sucessed. costed: {:.3f}s...".format(time.time() - t))

最后附上数据集网盘地址:链接: https://pan.baidu.com/s/1lu79cvI1Dq5WVs-ggC8yDg 提取码: tieb

互相学习,共同进步!

  • 16
    点赞
  • 68
    收藏
    觉得还不错? 一键收藏
  • 17
    评论
在VS Code中将XML格式转换VOC格式,您可以按照以下步骤进行操作: 1. 首先,确保您已经安装了Python和所需的库。您可以使用以下命令安装所需的库: ``` pip install xmltodict ``` 2. 创建一个Python脚本文件(例如convert_xml_to_voc.py),并在VS Code中打开它。 3. 在脚本文件中,导入所需的库和模块: ```python import os import xml.etree.ElementTree as ET import xmltodict ``` 4. 定义一个函数来解析XML文件并生成VOC格式的标注数据: ```python def convert_xml_to_voc(xml_file): with open(xml_file, 'r') as f: xml_data = f.read() data_dict = xmltodict.parse(xml_data) # 提取图像尺寸信息 image_width = int(data_dict['annotation']['size']['width']) image_height = int(data_dict['annotation']['size']['height']) image_depth = int(data_dict['annotation']['size']['depth']) # 创建VOC格式的标注数据字符串 voc_data = f"{image_width}\n{image_height}\n{image_depth}\n" # 提取目标对象信息并生成VOC格式的标注数据字符串 for obj in data_dict['annotation']['object']: xmin = int(obj['bndbox']['xmin']) ymin = int(obj['bndbox']['ymin']) xmax = int(obj['bndbox']['xmax']) ymax = int(obj['bndbox']['ymax']) label = obj['name'] voc_data += f"{label} {xmin} {ymin} {xmax} {ymax}\n" return voc_data ``` 5. 定义一个函数来遍历指定目录下的所有XML文件,并调用上面的函数进行转换: ```python def batch_convert_xml_to_voc(xml_dir, output_dir): for xml_file in os.listdir(xml_dir): if xml_file.endswith('.xml'): xml_path = os.path.join(xml_dir, xml_file) voc_data = convert_xml_to_voc(xml_path) # 生成VOC格式的标注数据文件 output_file = os.path.splitext(xml_file)[0] + '.txt' output_path = os.path.join(output_dir, output_file) with open(output_path, 'w') as f: f.write(voc_data) ``` 6. 在脚本文件中,调用上面的函数并传入您的XML文件目录和输出目录: ```python xml_dir = 'path/to/xml/files' output_dir = 'path/to/output/directory' batch_convert_xml_to_voc(xml_dir, output_dir) ``` 7. 保存并运行脚本文件,它将遍历指定目录下的所有XML文件,并将转换后的VOC格式标注数据保存到指定的输出目录中。 请注意,上述代码仅提供了一个简单的示例,并假设XML文件的结构符合您的需求。您可能需要根据自己的数据集结构进行适当的修改。
评论 17
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值