python批量修改labelme(COCO)标注的json文件的label标签名称

python批量修改labelme(COCO)标注的json文件的label标签名称

在深度学习的实践中,使用labelme标注软件标注好数据集之后,如果标签的名称标注错误或者需要修改,庞大的数据量依靠人工修改是一项庞大的工作量,这时可以参考以下代码,轻松帮你解决标签名称问题,并且适合大批量修改。
这是使用labelme标注好的json格式文件的信息:
打开的json文件的内容
需要实现的是修改label标签,这里是“photovoltaics”。它在这里的位置是一个字典下的shapes键的键值,shapes键值是一个列表,列表的每项内容又是由字典组成,而标签名称是第二层字典的label键的键值。

进行修改的代码如下,具体解释看代码:


# !/usr/bin/env python
# -*- encoding: utf-8 -*-

import os
import json
from ipdb import set_trace

json_dir = './xj_json1'
json_files = os.listdir(json_dir)

json_dict = {
    
    }
# 需要修改的新名称
new_name = 'photovoltaics123'

for json_file in json_files:
    
    jsonfile = json_dir +'/'+ json_file
    # 读单个json文件
    with open(jsonfile,'r',encoding = 'utf-8') as jf:

        info = json.load(jf)
        # print(type(info))
        # 找到位置进行修改
        for i,label in enumerate(info['shapes']):
            info['shapes'][i]['label'] = new_name
        # 使用新字典替换修改后的字典
        json_dict = info
        print(json_dict) 
    # set_trace()
    # 将替换后的内容写入原文件 
    with open(jsonfile,'w') as new_jf:
        json.dump(json_dict,new_jf)       

print('change name over!')

运行完代码,在这里,标签的名称就统一变成’photovoltaics123’

猜你喜欢

转载自blog.csdn.net/qq_44442727/article/details/112785978
今日推荐