1、批量修改标签名
使用labelme标注数据时,由于是多人标注,不同人在标注时错误的把同一类对象的标签名连同文件名编号一起赋给了label,现在我想全部修改为只有标签名(把文件名编号去掉)。
代码如下:
# coding:utf-8
'''
功能描述:批量修改labelme标注的json文件中的标签名,
原标签名为FCD1 FCD1187 FCD1186 FCD1185等,统一修改为FCD
'''
import os
import json
json_dir = 'json_label/' # 写入json文件的文件夹路径
json_files = os.listdir(json_dir)
for json_file in json_files:
json_file_ext = os.path.splitext(json_file)
if json_file_ext[1] == '.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']):
label_name = info['shapes'][i]['label'] # 获取json文件中原标签名,FCD1 FCD1187 FCD1186 FCD1185 等等
label_name_new = label_name[0:3] # 提取字符串前3位字符,FCD
info['shapes'][i]['label'] = label_name_new # 将json文件中标签名进行统一修改替换
# print(info['shapes'][i]['label'])
# 使用新字典替换修改后的字典
json_dict = info
# 将替换后的内容写入原文件
with open(jsonfile, 'w') as new_jf:
json.dump(json_dict, new_jf)
print('change name over!')
2、批量修改某一类对象的标签名
比如之前把标注的一类对象写成了“dog”,现在我想全部修改为“puppy”。
代码如下:
# coding:utf-8
import os
import json
json_dir = 'json_label/' # 写入json文件的文件夹路径
json_files = os.listdir(json_dir)
#写自己的旧标签名和新标签名
old_name = "dog"
new_name = "puppy"
for json_file in json_files:
json_file_ext = os.path.splitext(json_file)
if json_file_ext[1] == '.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']):
if info['shapes'][i]['label'] == old_name:
info['shapes'][i]['label'] = new_name
# 找到位置进行修改
# 使用新字典替换修改后的字典
json_dict = info
# 将替换后的内容写入原文件
with open(jsonfile,'w') as new_jf:
json.dump(json_dict,new_jf)
print('change name over!')
3、批量删除某一类对象标注
比如之前标注了“cat",“dog”,现在我不想要"dog"这个类型了,批量删除。
代码如下:
# !/usr/bin/env python
# -*- encoding: utf-8 -*-
import os
import json
json_dir = 'json_label/' # 写入json文件的文件夹路径
json_files = os.listdir(json_dir)
#这里写你要删除的标签名
delete_name = "dog"
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']):
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!')
批量处理完后,大家一定要打开labelme再检查一下自己的图片和修改后的json文件标注是否达到想要的效果。
参考:https://blog.csdn.net/Sharonnn_/article/details/124365542