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


Posted in Python onAugust 07, 2021

json文件格式

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

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

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

{
 "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 相关文章推荐
利用Django框架中select_related和prefetch_related函数对数据库查询优化
Apr 01 Python
Python实现比较两个列表(list)范围
Jun 12 Python
利用Python循环(包括while&amp;for)各种打印九九乘法表的实例
Nov 06 Python
解决Python pandas df 写入excel 出现的问题
Jul 04 Python
详解Python中的正则表达式
Jul 08 Python
用Python实现读写锁的示例代码
Nov 05 Python
python获取Pandas列名的几种方法
Aug 07 Python
python爬虫爬取幽默笑话网站
Oct 24 Python
python opencv 图像边框(填充)添加及图像混合的实现方法(末尾实现类似幻灯片渐变的效果)
Mar 09 Python
OpenCV Python实现图像指定区域裁剪
Mar 12 Python
python 绘制正态曲线的示例
Sep 24 Python
Python Http请求json解析库用法解析
Nov 28 Python
一篇文章弄懂Python中的内建函数
Aug 07 #Python
Python 可迭代对象 iterable的具体使用
Aug 07 #Python
Python pandas之求和运算和非空值个数统计
Aug 07 #Python
关于Python中*args和**kwargs的深入理解
Aug 07 #Python
python3操作redis实现List列表实例
Aug 04 #Python
Python pandas求方差和标准差的方法实例
Aug 04 #Python
pandas求平均数和中位数的方法实例
Aug 04 #Python
You might like
PHP中CURL的CURLOPT_POSTFIELDS参数使用细节
2014/03/17 PHP
PHP图片裁剪函数(保持图像不变形)
2014/05/04 PHP
PHP合并discuz用户脚本的方法
2015/08/04 PHP
php 使用fopen函数创建、打开文件详解及实例代码
2016/09/24 PHP
document.getElementById的简写方式(获取id对象的简略写法)
2010/09/10 Javascript
div失去焦点事件实现思路
2014/04/22 Javascript
JS实现Select的option上下移动的方法
2016/03/01 Javascript
ajax实现动态下拉框示例
2017/01/10 Javascript
vue使用watch 观察路由变化,重新获取内容
2017/03/08 Javascript
浅谈Angular4实现热加载开发旅程
2017/09/08 Javascript
快速解决vue动态绑定多个class的官方实例语法无效的问题
2018/09/05 Javascript
React Component存在的几种形式详解
2018/11/06 Javascript
js类的继承定义与用法分析
2019/06/21 Javascript
vant 时间选择器--开始时间和结束时间实例
2020/11/04 Javascript
Node快速切换版本、版本回退(降级)、版本更新(升级)
2021/01/07 Javascript
在Python中利用Pandas库处理大数据的简单介绍
2015/04/07 Python
Python实现优先级队列结构的方法详解
2016/06/02 Python
Python实现的堆排序算法原理与用法实例分析
2017/11/22 Python
解决pycharm 误删掉项目文件的处理方法
2018/10/22 Python
对python3中, print横向输出的方法详解
2019/01/28 Python
python的pytest框架之命令行参数详解(上)
2019/06/27 Python
python适合人工智能的理由和优势
2019/06/28 Python
python实现人工智能Ai抠图功能
2019/09/05 Python
Python远程方法调用实现过程解析
2020/07/28 Python
Python实现迪杰斯特拉算法并生成最短路径的示例代码
2020/12/01 Python
新西兰珠宝品牌:Michael Hill
2017/09/16 全球购物
巴西电子产品购物网站:Saldão da Informática
2018/01/09 全球购物
Ajxa常见问题都有哪些
2014/03/26 面试题
机电专业个人求职信范文
2013/12/30 职场文书
开学季活动策划方案
2014/02/28 职场文书
乡镇办公室工作决心书
2014/03/11 职场文书
小学生竞选班干部演讲稿
2014/04/24 职场文书
市委召开党的群众路线教育实践活动总结大会报告
2014/10/21 职场文书
2014年团委工作总结
2014/11/13 职场文书
2014年生产部工作总结
2014/12/17 职场文书
运动会200米广播稿
2015/08/19 职场文书