python读取dair-v2x数据集的json文件,并将其转为voc格式(仅使用2D数据)

dair-v2x数据集json文件如下:

python读取dair-v2x数据集的json文件,并将其转为voc格式(仅使用2D数据)_第1张图片

仅读取2D检测相关数据

import xml.etree.ElementTree as ET
from xml.dom.minidom import Document
import os
import time
import json


def ConvertVOCXml(file_path="", file_name=""):

    xml_file = open(('/home/songcq/datatest/xml/'+file_name[:-5] + '.xml'), 'w')

    xml_file.write('\n')
    xml_file.write('    VOC2007\n')
    xml_file.write('    \n')
    xml_file.write('        ' + '1920' + '\n')
    xml_file.write('        ' + '1080' + '\n')
    xml_file.write('        3\n')
    xml_file.write('    \n')
    
    f =open(('/home/songcq/datatest/json/'+file_name))
    
    content = json.load(f)
    for i in range(len(content)):
        gt_label = content[i]['type']
        xmin = content[i]['2d_box']['xmin']
        ymin = content[i]['2d_box']['ymin']
        xmax = content[i]['2d_box']['xmax']
        ymax = content[i]['2d_box']['ymax']
        xmin,ymin,xmax,ymax= int(xmin),int(ymin),int(xmax),int(ymax)
        
        xml_file.write('    \n')
        xml_file.write('        '+str(gt_label)+'\n')
        xml_file.write('        Unspecified\n')
        xml_file.write('        0\n')
        xml_file.write('        0\n')
        xml_file.write('        \n')
        xml_file.write('            '+str(xmin)+'\n')
        xml_file.write('            '+str(ymin)+'\n')
        xml_file.write('            '+str(xmax)+'\n')
        xml_file.write('            '+str(ymax)+'\n')
        xml_file.write('        \n')
        xml_file.write('    \n')
    xml_file.write('')    
    xml_file.close()


if __name__ == "__main__":
    basePath = '/home/songcq/datatest/json/'   #dair-v2x数据集的json文件放置位置
    totaljson = os.listdir(basePath)
    totaljson.sort()
    total_num = 0
    flag = False
    print("正在转换")
    saveBasePath = '/home/songcq/datatest/xml/'       #voc格式的xml文件放置位置
    if os.path.exists(saveBasePath) == False:  # 判断文件夹是否存在
        os.makedirs(saveBasePath)

    # ConvertVOCXml(file_path="samplexml",file_name="000009.xml")
    # Start time
    start = time.time()
    for json1 in totaljson:
        file_name = os.path.join(basePath, json1)
        print(file_name)
        
        ConvertVOCXml(file_path=saveBasePath, file_name=json1)

    # End time
    end = time.time()
    seconds = end - start
    print("Time taken : {0} seconds".format(seconds))

转换后的xml文件如下

python读取dair-v2x数据集的json文件,并将其转为voc格式(仅使用2D数据)_第2张图片

你可能感兴趣的:(python,json,xml)