【labelme格式json转为labelimg格式的xml(VOC)】

2023-05-16

@TOC

readme

用labelme标注图片,得到的是json格式文件,有时候需要voc格式的数据,可以使用以下转换脚本,只需把文件路径替换。

code

# -*- coding: utf-8 -*-
import numpy as np
import json
 
# 读取json 标签内容
# 当中有2种模式,一种rectangle,表示json文件是通过labelme的rectangle方式标注,
# 一种polygon,表示json文件是通过labelme的polygon方式标注。根据实际情况进行变换。
##### 1 
class ReadAnno:
    def __init__(self, json_path, process_mode="rectangle"):
        self.json_data = json.load(open(json_path))
        self.filename = self.json_data['imagePath']
        self.width = self.json_data['imageWidth']
        self.height = self.json_data['imageHeight']
 
        self.coordis = []
        assert process_mode in ["rectangle", "polygon"]
        if process_mode == "rectangle":
            self.process_polygon_shapes()
        elif process_mode == "polygon":
            self.process_polygon_shapes()
 
    def process_rectangle_shapes(self):
        for single_shape in self.json_data['shapes']:
            bbox_class = single_shape['label']
            xmin = single_shape['points'][0][0]
            ymin = single_shape['points'][0][1]
            xmax = single_shape['points'][1][0]
            ymax = single_shape['points'][1][1]
            self.coordis.append([xmin,ymin,xmax,ymax,bbox_class])
 
    def process_polygon_shapes(self):
        for single_shape in self.json_data['shapes']:
            bbox_class = single_shape['label']
            temp_points = []
            for couple_point in single_shape['points']:
                x = float(couple_point[0])
                y = float(couple_point[1])
                temp_points.append([x,y])
            temp_points = np.array(temp_points)
            xmin, ymin = temp_points.min(axis=0)
            xmax, ymax = temp_points.max(axis=0)
            self.coordis.append([xmin,ymin,xmax,ymax,bbox_class])
 
    def get_width_height(self):
        return self.width, self.height
 
    def get_filename(self):
        return self.filename
 
    def get_coordis(self):
        return self.coordis

##### 2
from xml.dom.minidom import Document
 
#  创建labelimg标注格式的xml文件标签  并添加读取的数据,进行转换
class CreateAnno:
    def __init__(self,):
        self.doc = Document()  # 创建DOM文档对象
        self.anno = self.doc.createElement('annotation')  # 创建根元素
        self.doc.appendChild(self.anno)
 
        self.add_folder()
        self.add_path()
        self.add_source()
        self.add_segmented()
 
        # self.add_filename()
        # self.add_pic_size(width_text_str=str(width), height_text_str=str(height), depth_text_str=str(depth))
 
    def add_folder(self, floder_text_str='JPEGImages'):
        floder = self.doc.createElement('floder')  ##建立自己的开头
        floder_text = self.doc.createTextNode(floder_text_str)  ##建立自己的文本信息
        floder.appendChild(floder_text)  ##自己的内容
        self.anno.appendChild(floder)
 
    def add_filename(self, filename_text_str='00000.jpg'):
        filename = self.doc.createElement('filename')
        filename_text = self.doc.createTextNode(filename_text_str)
        filename.appendChild(filename_text)
        self.anno.appendChild(filename)
 
    def add_path(self, path_text_str="None"):
        path = self.doc.createElement('path')
        path_text = self.doc.createTextNode(path_text_str)
        path.appendChild(path_text)
        self.anno.appendChild(path)
 
    def add_source(self, database_text_str="Unknow"):
        source = self.doc.createElement('source')
        database = self.doc.createElement('database')
        database_text = self.doc.createTextNode(database_text_str)  # 元素内容写入
        database.appendChild(database_text)
        source.appendChild(database)
        self.anno.appendChild(source)
 
    def add_pic_size(self, width_text_str="0", height_text_str="0", depth_text_str="3"):
        size = self.doc.createElement('size')
        width = self.doc.createElement('width')
        width_text = self.doc.createTextNode(width_text_str)  # 元素内容写入
        width.appendChild(width_text)
        size.appendChild(width)
 
        height = self.doc.createElement('height')
        height_text = self.doc.createTextNode(height_text_str)
        height.appendChild(height_text)
        size.appendChild(height)
 
        depth = self.doc.createElement('depth')
        depth_text = self.doc.createTextNode(depth_text_str)
        depth.appendChild(depth_text)
        size.appendChild(depth)
 
        self.anno.appendChild(size)
 
    def add_segmented(self, segmented_text_str="0"):
        segmented = self.doc.createElement('segmented')
        segmented_text = self.doc.createTextNode(segmented_text_str)
        segmented.appendChild(segmented_text)
        self.anno.appendChild(segmented)
 
    def add_object(self,
                   name_text_str="None",
                   xmin_text_str="0",
                   ymin_text_str="0",
                   xmax_text_str="0",
                   ymax_text_str="0",
                   pose_text_str="Unspecified",
                   truncated_text_str="0",
                   difficult_text_str="0"):
        object = self.doc.createElement('object')
        name = self.doc.createElement('name')
        name_text = self.doc.createTextNode(name_text_str)
        name.appendChild(name_text)
        object.appendChild(name)
 
        pose = self.doc.createElement('pose')
        pose_text = self.doc.createTextNode(pose_text_str)
        pose.appendChild(pose_text)
        object.appendChild(pose)
 
        truncated = self.doc.createElement('truncated')
        truncated_text = self.doc.createTextNode(truncated_text_str)
        truncated.appendChild(truncated_text)
        object.appendChild(truncated)
 
        difficult = self.doc.createElement('difficult')
        difficult_text = self.doc.createTextNode(difficult_text_str)
        difficult.appendChild(difficult_text)
        object.appendChild(difficult)
 
        bndbox = self.doc.createElement('bndbox')
        xmin = self.doc.createElement('xmin')
        xmin_text = self.doc.createTextNode(xmin_text_str)
        xmin.appendChild(xmin_text)
        bndbox.appendChild(xmin)
 
        ymin = self.doc.createElement('ymin')
        ymin_text = self.doc.createTextNode(ymin_text_str)
        ymin.appendChild(ymin_text)
        bndbox.appendChild(ymin)
 
        xmax = self.doc.createElement('xmax')
        xmax_text = self.doc.createTextNode(xmax_text_str)
        xmax.appendChild(xmax_text)
        bndbox.appendChild(xmax)
 
        ymax = self.doc.createElement('ymax')
        ymax_text = self.doc.createTextNode(ymax_text_str)
        ymax.appendChild(ymax_text)
        bndbox.appendChild(ymax)
        object.appendChild(bndbox)
 
        self.anno.appendChild(object)
 
    def get_anno(self):
        return self.anno
 
    def get_doc(self):
        return self.doc
 
    def save_doc(self, save_path):
        with open(save_path, "w") as f:
            self.doc.writexml(f, indent='\t', newl='\n', addindent='\t', encoding='utf-8')

# 更改参数运行: json格式文件所在的文件夹,将要保存的xml文件夹,以及原数据的标注方式。
##### 3
import os
from tqdm import tqdm
 
# from read_json_anno import ReadAnno
# from create_xml_anno import CreateAnno
 
 
def json_transform_xml(json_path, xml_path, process_mode="rectangle"):
    json_path = json_path
    json_anno = ReadAnno(json_path, process_mode=process_mode)
    width, height = json_anno.get_width_height()
    filename = json_anno.get_filename()
    coordis = json_anno.get_coordis()
 
    xml_anno = CreateAnno()
    xml_anno.add_filename(filename)
    xml_anno.add_pic_size(width_text_str=str(width), height_text_str=str(height), depth_text_str=str(3))
    for xmin,ymin,xmax,ymax,label in coordis:
        xml_anno.add_object(name_text_str=str(label),
                            xmin_text_str=str(int(xmin)),
                            ymin_text_str=str(int(ymin)),
                            xmax_text_str=str(int(xmax)),
                            ymax_text_str=str(int(ymax)))
    xml_anno.save_doc(xml_path)
 
if __name__ == "__main__":
    root_json_dir = r"E:/002_GIT/labels_json/"  
    root_save_xml_dir =  r"E:/002_GIT/labels_xml/" 
    for json_filename in tqdm(os.listdir(root_json_dir)):
        json_path = os.path.join(root_json_dir, json_filename)
        save_xml_path = os.path.join(root_save_xml_dir, json_filename.replace(".json", ".xml"))
        json_transform_xml(json_path, save_xml_path, process_mode="rectangle")


本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

【labelme格式json转为labelimg格式的xml(VOC)】 的相关文章

  • Android REST API 连接

    我有点傻 对此感到抱歉 我编写了一个 API 它返回一些 JSON 我的目标是从 Android 应用程序使用此 API 我已经尝试过使用 AsyncTask 但失败了 我想像这样使用它 调用该类 告知 URL 和结果的类型 哪个json
  • 将 JSON 文件读入 Spark 时出现 _corrupt_record 错误

    我有这个 JSON 文件 a 1 b 2 这是通过Python json dump方法获得的 现在 我想使用 pyspark 将此文件读入 Spark 中的 DataFrame 根据文档 我正在这样做 sc SparkContext sql
  • Newtonsoft.Json.JsonReaderException

    我的 Newtonsoft Json 有问题 我正在尝试从 URL 解析 JSON 但收到错误 这是 JSON ID 0 Nome we Data 2013 09 16 Orario 00 00 16 Prestazione dfg Sta
  • 为什么这些冲突出现在以下 XML 的 yacc 语法中

    我有以下 XML 语法 效果很好 program lt ID attribute list gt root root lt ID attribute list gt node list lt ID gt node list node s n
  • 从流中过滤/删除无效的 xml 字符

    首先 我无法更改 xml 的输出 它是由第三方生成的 他们在 xml 中插入无效字符 我得到了 xml 字节流表示形式的 InputStream 除了将流消耗到字符串中并对其进行处理之外 是否有一种更干净的方法来过滤掉有问题的字符 我找到了
  • bash 脚本抱怨文件名太长

    所以我有一个脚本可以执行此操作 jq 是命令行 JSON 处理器 echo Getting LB Node IDs echo LB STATUS jq loadBalancer nodes id 最后一行的输出是 1 2 3 但是当我尝试将
  • XML 渲染错误 Android 预览 N

    更新后我已将 android SDK 更新为 android Preview N 但收到此 xml 渲染错误 单击详细信息后 它显示以下堆栈跟踪如何避免这种情况 org jetbrains android uipreview Renderi
  • 读取完 JSON 内容和意外标记后遇到的其他文本(在我的 json 中)

    我使用 JSON Net 创建的 json feed 遇到一些问题 当我尝试解析它时 它给了我 读取完 JSON 内容后遇到的附加文本 路径 第 17 行 位置 4 我尝试用以下方法验证它http json parser online fr
  • strings.xml 中的 Android 变量

    我在某处读到如何在 XML 文档中使用变量 他们说这很简单 我想也是如此 我在 Android strings xml 文件中成功地使用了它 我一整天都这样使用它 直到突然 android 停止解析它并停止将它视为变量 我这样使用它
  • PyQt:数据不可 JSON 序列化

    我是 PyQt GUI 的新手 我想获取a的数据QLineEdit文本框 为此我正在使用text 方法 我正在获取数据 但数据类型是QString 我需要将其作为 json 数据传输到服务器 为此我使用json dumps 方法 但我收到错
  • 使用 ElementTree 在 python 中解析 xml

    我对 python 很陌生 我需要解析一些脏的 xml 文件 这些文件需要先清理 我有以下 python 代码 import arff import xml etree ElementTree import re totstring wit
  • 关闭 XDOCUMENT 的实例

    我收到这个错误 该进程无法访问文件 C test Person xml 因为它是 被另一个进程使用 IOException 未处理 保存文件内容后如何关闭 xml 文件的实例 using System using System Collec
  • 如何在 C# 中使用 XmlDsigC14NTransform 类

    我正在尝试使用规范化 xml 节点System Security Cryptography Xml XMLDsigC14nTransformC net Framework 2 0 的类 该实例需要三种不同的输入类型 NodeList Str
  • 将 JSON 数据导入 Google 表格

    我从 Web 服务中提取数据 其格式为 JSON 我正在为 Google Sheets 编写一个 Google Apps 脚本 它将为我填充数据 我的问题是 我似乎无法解析它 Doing var dataset myJSONtext Bro
  • 从响应中获取标头(Retrofit / OkHttp 客户端)

    我正在使用 Retrofit 与 OkHttp 客户端和 Jackson 进行 Json 序列化 并希望获取响应的标头 我知道我可以扩展 OkClient 并拦截它 但这发生在反序列化过程开始之前 我基本上需要的是获取标头以及反序列化的 J
  • 将MongoDb atlas数据库导出到本机Mongo compass

    我在 Atlas 中有一个名为 test 的远程数据库 我想将集合名称 image table 下载为 JSON 文件 在 Mac 终端中 mongoexport db test collection image table image j
  • 在 Play2 和 Scala 中解析没有数据类型的 JSON

    people name Jack age 15 name Tony age 23 name Mike age 19 这是我试图解析的 json 示例 我希望能够对每个人进行 foreach 操作并打印他们的姓名和年龄 我知道当 json 数
  • 使用 KnockoutJs 映射插件进行递归模板化

    我正在尝试使用以下方法在树上进行递归模板化ko映射 插入 http knockoutjs com documentation plugins mapping html 但我无法渲染它 除非我定义separate每个级别的模板 在以下情况下
  • 如何在谷歌地图android上显示多个标记

    我想在谷歌地图android上显示带有多个标记的位置 问题是当我运行我的应用程序时 它只显示一个位置 标记 这是我的代码 public class koordinatTask extends AsyncTask
  • 在 Android 应用程序资源中使用 JSON 文件

    假设我的应用程序的原始资源文件夹中有一个包含 JSON 内容的文件 我如何将其读入应用程序 以便我可以解析 JSON See 开放原始资源 http developer android com reference android conte

随机推荐