Python batch modify the label label name of the json file marked by labelme (COCO)

Python batch modify the label label name of the json file marked by labelme (COCO)

In the practice of deep learning, after using labelme labeling software to label the data set, if the label name is incorrectly labeled or needs to be modified, the huge amount of data depends on manual modification is a huge workload. At this time, you can refer to the following code, which is easy Help you solve the label name problem, and is suitable for mass revision.
This is the information of the json format file marked with labelme: what
The content of the opened json file
needs to be achieved is to modify the label label, here is "photovoltaics". Its position here is the key value of the shapes key under a dictionary. The shapes key value is a list. Each item of the list is composed of a dictionary, and the label name is the key value of the label key of the second-level dictionary.

The modified code is as follows, see the code for specific explanation:


# !/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!')

After running the code, here, the name of the label is uniformly changed to'photovoltaics123'

Guess you like

Origin blog.csdn.net/qq_44442727/article/details/112785978