python之json文件转xml文件案例讲解

 更新时间:2021年08月06日 09:05:06   作者:G果  
这篇文章主要介绍了python之json文件转xml文件案例讲解,本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下

json文件格式

这是yolov4模型跑出来的检测结果result.json

在这里插入图片描述

下面是截取的一张图的检测结果

{
 "frame_id":1, #图片的序号
 "filename":"/media/wuzhou/Gap/rgb-piglet/test/00000000.jpg", #图片的路径
 "objects": [ #该图中所有的目标:目标类别、目标名称、归一化的框的坐标(xywh格式)、置信度
  {"class_id":0, "name":"pp", "relative_coordinates":{"center_x":0.750913, "center_y":0.402691, "width":0.038380, "height":0.193304}, "confidence":0.995435}, 
  {"class_id":0, "name":"pp", "relative_coordinates":{"center_x":0.764775, "center_y":0.199255, "width":0.049979, "height":0.130169}, "confidence":0.994495}, 
  {"class_id":0, "name":"pp", "relative_coordinates":{"center_x":0.560050, "center_y":0.482614, "width":0.036331, "height":0.166377}, "confidence":0.994460}, 
  {"class_id":0, "name":"pp", "relative_coordinates":{"center_x":0.710756, "center_y":0.406446, "width":0.041782, "height":0.191297}, "confidence":0.993540}, 
  {"class_id":0, "name":"pp", "relative_coordinates":{"center_x":0.638335, "center_y":0.238725, "width":0.107689, "height":0.092282}, "confidence":0.992926}, 
  {"class_id":0, "name":"pp", "relative_coordinates":{"center_x":0.780232, "center_y":0.448454, "width":0.041550, "height":0.179540}, "confidence":0.990020}, 
  {"class_id":0, "name":"pp", "relative_coordinates":{"center_x":0.563412, "center_y":0.350035, "width":0.103184, "height":0.059460}, "confidence":0.979756}, 
  {"class_id":0, "name":"pp", "relative_coordinates":{"center_x":0.522591, "center_y":0.195170, "width":0.083014, "height":0.071478}, "confidence":0.970642}, 
  {"class_id":0, "name":"pp", "relative_coordinates":{"center_x":0.658721, "center_y":0.154640, "width":0.103852, "height":0.055686}, "confidence":0.967082}, 
  {"class_id":0, "name":"pp", "relative_coordinates":{"center_x":0.537660, "center_y":0.256810, "width":0.101619, "height":0.095211}, "confidence":0.918135}, 
  {"class_id":0, "name":"pp", "relative_coordinates":{"center_x":0.528618, "center_y":0.481005, "width":0.033226, "height":0.177723}, "confidence":0.310291}
 ] 
}, 

完整代码

代码需要指定图片的路径,例如 file_dir = "H:/rgb-piglet/five/test"
注意:result.json文件要跟图片放一起

代码生成的xml与图片在同一个路径下

import json
import time
import os
from PIL import Image
import cv2
import numpy as np

'''人为构造xml文件的格式'''
out0 ='''<annotation>
    <folder>%(folder)s</folder>
    <filename>%(name)s</filename>
    <path>%(path)s</path>
    <source>
        <database>None</database>
    </source>
    <size>
        <width>%(width)d</width>
        <height>%(height)d</height>
        <depth>3</depth>
    </size>
    <segmented>0</segmented>
'''
out1 = '''    <object>
        <name>%(class)s</name>
        <pose>Unspecified</pose>
        <truncated>0</truncated>
        <difficult>0</difficult>
        <bndbox>
            <xmin>%(xmin)d</xmin>
            <ymin>%(ymin)d</ymin>
            <xmax>%(xmax)d</xmax>
            <ymax>%(ymax)d</ymax>
        </bndbox>
    </object>
'''

out2 = '''</annotation>
'''

def read_json(json_dir):
    with open(json_dir,"r") as f:
        data = json.load(f)
        print(type(data),len(data),type(data[0]),data[0]['frame_id'])
    return data


'''txt转xml函数'''
def translate(fdir,lists): 
    source = {}
    label = {}
    data = read_json(fdir+"/result.json")
    k = 0
    for jpg in lists:
        print(jpg)
        if jpg[-4:] == '.jpg':
            image= cv2.imread(jpg)#路径不能有中文
            h,w,_ = image.shape #图片大小
            
            fxml = jpg.replace('.jpg','.xml')
            fxml = open(fxml, 'w');
            imgfile = jpg.split('/')[-1]
            source['name'] = imgfile 
            source['path'] = jpg
            source['folder'] = os.path.basename(fdir)

            source['width'] = w
            source['height'] = h
            
            fxml.write(out0 % source)
                       
            for obj in data[k]["objects"]:
                label['class'] = obj["class_id"]
                box = obj["relative_coordinates"]
                
                '''把txt上的数字(归一化)转成xml上框的坐标'''
                xmin = float(box["center_x"] - 0.5*box["width"])*w
                ymin = float(box["center_y"] - 0.5*box["height"])*h
                xmax = float(xmin + box["width"]*w)
                ymax = float(ymin + box["height"]*h)
                
                label['xmin'] = xmin
                label['ymin'] = ymin
                label['xmax'] = xmax
                label['ymax'] = ymax
                    
                fxml.write(out1 % label)
                
            k = k+1
            fxml.write(out2)

if __name__ == '__main__':
    file_dir = "H:/rgb-piglet/five/test"
    lists=[]
    for i in os.listdir(file_dir):
        if i[-3:]=='jpg':
            lists.append(file_dir+'/'+i)       
    #print(lists)
    translate(file_dir,lists)
    print('---------------Done!!!--------------')            
                

到此这篇关于python之json文件转xml文件案例讲解的文章就介绍到这了,更多相关python之json文件转xml内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Python小程序之在图片上加入数字的代码

    Python小程序之在图片上加入数字的代码

    这篇文章主要介绍了Python小程序之在图片上加入数字的代码,这个是小编今天练手的小程序,代码简单易懂,具有一定的参考借鉴价值,需要的朋友可以参考下
    2019-11-11
  • Python字符串三种格式化输出

    Python字符串三种格式化输出

    这篇文章主要介绍了Python字符串三种格式化输出,需要的朋友可以参考下
    2020-09-09
  • python中的装饰器详解

    python中的装饰器详解

    这篇文章主要介绍了python中的装饰器详解,本文讲解了装饰器语法、简单装饰器、带内嵌函数装饰器、带参数的装饰器等内容,需要的朋友可以参考下
    2015-04-04
  • Python利用PyPDF2库处理PDF文件的基本操作

    Python利用PyPDF2库处理PDF文件的基本操作

    PyPDF2是一个Python库,用于处理PDF文件,包括合并、分割、旋转和提取文本等操作,它是一个功能强大且灵活的工具,可用于自动化处理PDF文件,适用于各种应用,从文档管理到数据分析,本文将深入介绍PyPDF2库,掌握如何利用它来处理PDF文件,需要的朋友可以参考下
    2023-11-11
  • python join方法使用详解

    python join方法使用详解

    这篇文章主要介绍了python join方法使用详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-07-07
  • python的pytest框架之命令行参数详解(下)

    python的pytest框架之命令行参数详解(下)

    这篇文章主要介绍了python的pytest框架之命令行参数详解,今天将继续更新其他一些命令选项的使用,和pytest收集测试用例的规则,需要的朋友可以参考下
    2019-06-06
  • windows下python连接oracle数据库

    windows下python连接oracle数据库

    这篇文章主要为大家详细介绍了windows下python连接oracle数据库,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-06-06
  • Python之urlencode和urldecode案例讲解

    Python之urlencode和urldecode案例讲解

    这篇文章主要介绍了Python之urlencode和urldecode案例讲解,本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下
    2021-08-08
  • 如何解决flask修改静态资源后缓存文件不能及时更改问题

    如何解决flask修改静态资源后缓存文件不能及时更改问题

    在本篇内容里小编给大家整理的是关于如何解决flask修改静态资源后缓存文件不能及时更改问题,需要的朋友们可以学习下。
    2020-08-08
  • 在Python 3中实现类型检查器的简单方法

    在Python 3中实现类型检查器的简单方法

    这篇文章主要介绍了在Python 3中实现类型检查器的简单方法,包括对函数注解这个新特性的介绍,需要的朋友可以参考下
    2015-07-07

最新评论