labelimg标注的xml文件转为labelme的json格式

本文介绍了图像标注工具LabelImg和LabelMe的标注格式,并提供了将LabelImg的XML标注转换为LabelMe的JSON格式的Python脚本。脚本详细展示了如何解析XML文件,提取关键信息如图像路径、尺寸、边界框坐标,并将其转化为LabelMe所用的JSON结构。此外,还展示了Params类用于读取和更新JSON配置文件的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录

labelimg标注的xml是这样

labelme标注的格式是这样

labelimg的xml转labelme的json

附上一个json文件创建编辑的脚本例子


labelimg标注的xml是这样

<annotation>
	<folder>22</folder>
	<filename>1.jpg</filename>
	<path>.\1.jpg</path>
	<source>
		<database>Unknown</database>
	</source>
	<size>
		<width>815</width>
		<height>692</height>
		<depth>3</depth>
	</size>
	<segmented>0</segmented>
	<object>
		<name>normal</name>
		<pose>Unspecified</pose>
		<truncated>0</truncated>
		<difficult>0</difficult>
		<bndbox>
			<xmin>205</xmin>
			<ymin>98</ymin>
			<xmax>805</xmax>
			<ymax>624</ymax>
		</bndbox>
	</object>
</annotation>

labelme标注的格式是这样

{
  "version": "5.0.0",
  "flags": {},
  "shapes": [
    {
      "label": "normal",
      "points": [
        [
          206.1290322580645,
          61.16129032258067
        ],
        [
          799.6774193548387,
          645.0322580645161
        ]
      ],
      "group_id": null,
      "shape_type": "rectangle",
      "flags": {}
    }
  ],
  "imagePath": "..\\22\\1.jpg",
  "imageData": "/9j/4AAQSkZJRgABAQAAAQABAAD",
  "imageHeight": 692,
  "imageWidth": 815
}

labelimg的xml转labelme的json

import xml.etree.ElementTree as ET
import os
import json
import cv2
from io import BytesIO
import base64
from PIL import Image

def makefile(path,content):
    with open(path, 'w') as f:  # 创建一个params.json文件
        f.write(content)  # 将json_str写到文件中

    # if os.path.exists(path):
    #     if os.path.isdir(path):
    #         #**
    #     else:
    #         print('please input the dir name')
    # else:
    #     print('the path is not exists')

def toJson(imagePath, imageHeight, imageWidth, shape_type, label, points, xml_path):
    print(imagePath)

    coco = dict()
    coco['version'] = "5.0.0"
    coco['flags'] = dict()
    coco['shapes'] = [1]
    coco['shapes'][0]=dict()
    coco['shapes'][0]['label'] = label
    coco['shapes'][0]['points'] = points
    coco['shapes'][0]['group_id'] = None
    coco['shapes'][0]['shape_type'] = "rectangle"
    coco['shapes'][0]['flags'] = dict()

    coco['imagePath'] = imagePath

    img = cv2.imread(imagePath)
    pil_img = Image.fromarray(img)
    buff = BytesIO()
    pil_img.save(buff, format="JPEG")
    new_image_string = base64.b64encode(buff.getvalue()).decode("utf-8")
    coco['imageData'] = new_image_string

    coco['imageHeight'] = imageHeight
    coco['imageWidth'] = imageWidth

    makefile(imagePath[:-4]+"_1.json",json.dumps(coco, indent=4))


def parseXmlFiles(xml_path):
    for f in os.listdir(xml_path):
        if not f.endswith('.xml'):
            continue

        size = dict()
        size['width'] = None
        size['height'] = None
        size['depth'] = None

        xml_file = os.path.join(xml_path, f)
        print(xml_file)

        tree = ET.parse(xml_file)
        root = tree.getroot()
        if root.tag != 'annotation':
            raise Exception('pascal voc xml root element should be annotation, rather than {}'.format(root.tag))

        imagePath = ""
        imageHeight = 0
        imageWidth = 0
        shape_type = "rectangle"
        label = "normal"
        points = [[0,0],[0,0]]
        for elem in root:
            if elem.tag == 'folder' or elem.tag == 'filename' or elem.tag == 'source' or elem.tag == 'segmented':
                continue
            elif elem.tag == 'path':
                imagePath = elem.text
            elif elem.tag == 'size':
                for subelem in elem:
                    if subelem.tag == 'width':
                        imageWidth = subelem.text
                    elif subelem.tag == 'height':
                        imageHeight = subelem.text
            elif  elem.tag == 'object':
                for subelem in elem:
                    if subelem.tag == 'bndbox':
                        for item in subelem:
                            if item.tag == 'xmin':
                                points[0][0] = int(item.text)
                            if item.tag == 'ymin':
                                points[0][1] = int(item.text)
                            if item.tag == 'xmax':
                                points[1][0] = int(item.text)
                            if item.tag == 'ymax':
                                points[1][1] = int(item.text)
        toJson(imagePath, imageHeight, imageWidth, shape_type, label, points, xml_path)


if __name__ == '__main__':
    xml_path = './'  # 这是xml文件所在的地址
    parseXmlFiles(xml_path)

附上一个json文件创建编辑的脚本例子

import json

class Params():
    """Class that loads hyperparameters from a json file.
        Example:
        ```
        params = Params(json_path)
        print(params.learning_rate)
        params.learning_rate = 0.5  # change the value of learning_rate in params
        ```
        """
    def __init__(self, json_path):
        with open(json_path) as f:
            params = json.load(f)  # 将json格式数据转换为字典
            self.__dict__.update(params)

    def save(self, json_path):
        with open(json_path, 'w') as f:
            json.dump(self.__dict__, f, indent=4)  # indent缩进级别进行漂亮打印

    def update(self, json_path):
        """Loads parameters from json file"""
        with open(json_path) as f:
            params = json.load(f)
            self.__dict__.update(params)

    @property  # Python内置的@property装饰器就是负责把一个方法变成属性调用的
    def dict(self):
        """Gives dict-like access to Params instance by `params.dict['learning_rate']"""
        return self.__dict__


if __name__ == '__main__':
    parameters = {"SEED": 1,
                  "dataset": "Omniglot",
                  "meta_lr": 1e-3,
                  "num_episodes": 5000,
                  "num_classes": 5,
                  "num_samples": 1,
                  "num_query": 10,
                  "num_steps": 100,
                  "num_inner_tasks": 8,
                  "num_train_updates": 1,
                  "num_eval_updates": 1,
                  "save_summary_steps": 100,
                  "num_workers": 1
                  }
    json_str = json.dumps(parameters, indent=4)

    with open('params.json', 'w') as f:  # 创建一个params.json文件
        f.write(json_str)  # 将json_str写到文件中

    params = Params('params.json')
    params.SEED2 = 2   # 修改json中的数据
    params.save('params.json')  # 将修改后的数据保存

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值