python代码批量修改Labelme标注的json文件:删除同一类的所有标签

python代码批量修改Labelme标注的json文件:删除同一类的所有标签,第1张

代码参考:https://blog.csdn.net/Sharonnn_/article/details/124365542

创建自己的数据集时,不打算分割名为"thread"的对象,因此要删除thread对象的标签。但是在labelme软件中,右侧的label list类别是不能改动的,也就是说在labelme中删除标签得一张一张的删除,很浪费时间。换一种思路:对.json文件中的"shapes"中"label"为要删除标注对应的shape进行删除,那么就能够通过 *** 作.json文件,完成批量删除标签,处理速度很快。

原文中一张图片中同一类物体有多个时,效果不好,不能把标签全部删除。本文把for循环改成了倒序循环再删除标签,可以解决同类多物体删除问题。

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

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/875887.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-13
下一篇 2022-05-13

发表评论

登录后才能评论

评论列表(0条)

保存