The python code batch modifies the json files labeled by Labelme: delete all labels of the same category

Code reference: https://blog.csdn.net/Sharonnn_/article/details/124365542

When creating your own dataset, you don't intend to split the object named "thread", so remove the label of the thread object. But in the labelme software, the label list category on the right cannot be changed, that is to say, to delete labels in labelme one by one, it is a waste of time. Another way of thinking: delete the "label" in the "shapes" in the .json file for the shape corresponding to the label to be deleted, then you can delete the labels in batches by operating the .json file, and the processing speed is very fast.

In the original text , when there are multiple objects of the same type in a picture, the effect is not good, and all tags cannot be deleted. In this paper, the for loop is changed to a reverse loop and then the label is deleted, which can solve the problem of deleting multiple objects of the same type.

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

import os
import json

# 这里写你自己的存放照片和json文件的路径
json_dir = 'D:\DeepLearningExercises\matlab_files\image1234\json_files/'
json_files = os.listdir(json_dir)

# 这里写你要删除的标签名
delete_name = "thread"

for json_file in json_files:
    json_file_ext = os.path.splitext(json_file)

    if json_file_ext[1] == '.json':
        # 判断是否为json文件
        jsonfile = json_dir + '\\' + json_file

        with open(jsonfile, 'r', encoding='utf-8') as jf:
            info = json.load(jf)

            # for i, label in enumerate(info['shapes']):
            for i in range(len(info['shapes'])-1,0,-1):
                if info['shapes'][i]['label'] == delete_name:
                    # 找到位置进行删除
                    del info['shapes'][i]
            # 使用新字典替换修改后的字典
            json_dict = info

        # 将替换后的内容写入原文件
        with open(jsonfile, 'w') as new_jf:
            json.dump(json_dict, new_jf)

print('delete label over!')

Guess you like

Origin blog.csdn.net/qq_36674060/article/details/124644755