代码参考:https://blog.csdn.net/qq_44442727/article/details/112785978
创建自己的数据集时,经常需要一些调整,比如说修改某一批文件中已经标好的一个对象的标签名,或者是不打算分割某一类对象,需要删除对其的标注。自己参考学习写了以下两个小工具同大家分享。
case1:批量修改某一类对象的标签名比如说,我之前把标注的一类对象写成了“dog”,现在我想全部修改为“puppy”。
文件结构默认使用了在labelme标注时,JPG图片和JSON文件都放在同一个文件夹里的习惯。
# !/usr/bin/env python
# -*- encoding: utf-8 -*-
import os
import json
#写入自己放了照片和json文件的文件夹路径
json_dir = 'C:\Users\Sharon\Desktop\label_images\.....'
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!')
case2:批量删除某一类对象标注
比如说,我之前标注了“cat",“dog”,现在我不想要"dog"这个类型了,批量删除。
# !/usr/bin/env python
# -*- encoding: utf-8 -*-
import os
import json
#这里写你自己的存放照片和json文件的路径
json_dir = 'C:\Users\Sharon\Desktop\label_images\....'
json_files = os.listdir(json_dir)
#这里写你要删除的标签名
delete_name = "nozzle"
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再检查一下自己的新图片标注是否达到想要的效果。
觉得ok,点赞再走呀~



