参看了一些文章,自己编写了一个简单的py脚本,测试可用
把这段代码拷贝粘贴,保存json2dataset.py(名字随意哈,自己起)。
把这个文件修改一下其中的 json_file 为自己的训练图像以及labelme标记后生成json的目录。
我的jpeg图像和labelme生成的json文件都在这一个目录下。如果你的文件存储位置不在同一个目录,自行修改一下代码吧,很简单。
import os
import subprocess
import shutil
json_file = r'G:/Software/Mask_RCNN/Mask_RCNN/samples/xray/1417N' # 根据存放的json文件位置进行修改
#创建目录
list = os.listdir(json_file)
if not os.path.exists(json_file + '/' + 'pic'):
os.makedirs(json_file + '/' + 'pic')
if not os.path.exists(json_file + '/' + 'cv2_mask'):
os.makedirs(json_file + '/' + 'cv2_mask')
if not os.path.exists(json_file + '/' + 'labelme_json'):
os.makedirs(json_file + '/' + 'labelme_json')
if not os.path.exists(json_file + '/' + 'json'):
os.makedirs(json_file + '/' + 'json')
#把jpg图像放置到pic目录下
for picfile in list:
if not picfile.endswith(".jpeg"):
continue
from_dir = json_file+'/'+ picfile
to_dir=json_file+'/pic/'+picfile
shutil.move(from_dir, to_dir)
#批量调用labelme_json_to_dataset,并把labelme创建的json文件放置到json目录下
for jsfile in list:
if not jsfile.endswith(".json"):
continue
cmd="labelme_json_to_dataset %s" % (jsfile)
subprocess.run(["cmd","/c",cmd],shell=True)
from_dir = json_file+'/'+ jsfile
to_dir = json_file+'/json/'+jsfile
shutil.move(from_dir, to_dir)
from_dir = json_file+ '/'+jsfile[:-5]+'_json'
to_dir=json_file+'/labelme_json/'+jsfile[:-5]+'_json'
shutil.move(from_dir, to_dir)
#把生成的label掩膜拷贝到cv2_mask目录下
for dir_name in os.listdir(json_file+'/labelme_json'):
pic_name = dir_name[:-5] + '.png'
from_dir =json_file+ '/labelme_json/'+dir_name+'./label.png'
to_dir = json_file+'/cv2_mask/'+pic_name
shutil.copyfile(from_dir, to_dir)
print (from_dir)
print (to_dir)
最后会自动生成pic,json,labelme_json,cv2_mask目录,并且各个文件都放置到位。
如果因为版本较新,不会生成info.yaml,需要人为修改G:\ProgramData\anaconda3\envs\maskrcnn\Lib\site-packages\labelme\cli\json_to_dataset.py(根据自己的anaconda安装目录和虚拟环境找到正确的目录),修正不会生成info.yaml的bug
#在文件头添加
import yaml
#在if __name__ == "__main__":前添加如下代码
logger.warning('info.yaml is being replaced by label_names.txt')
info = dict(label_names=label_names)
with open(osp.join(out_dir, 'info.yaml'), 'w') as f:
yaml.safe_dump(info, f, default_flow_style=False)
logger.info('Saved to: {}'.format(out_dir))