如果是单张图进行转换,则使用命令:labelme_json_to_dataset<图片路径>.json
如果是多张图,则使用下面程序替换将json转变为文件夹(内含label.png,image.png,label_vision等)限于二分类:
import argparse
import json
import os
import os.path as osp
import warnings
import numpy as np
import PIL.Image
import yaml
from labelme import utils
def main():
parser = argparse.ArgumentParser()
parser.add_argument('json_file')
parser.add_argument('-o', '--out', default=None)
args = parser.parse_args()
json_file = args.json_file
list = os.listdir(json_file)
for i in range(0, len(list)):
path = os.path.join(json_file, list[i])
if os.path.isfile(path):
data = json.load(open(path))
img = utils.img_b64_to_array(data['imageData'])
lbl, lbl_names = utils.labelme_shapes_to_label(img.shape, data['shapes'])
captions = ['%d: %s' % (l, name) for l, name in enumerate(lbl_names)]
lbl_viz = utils.draw_label(lbl, img, captions)
out_dir = osp.basename(list[i]).replace('.', '_')
out_dir = osp.join(osp.dirname(list[i]), out_dir)
if not osp.exists(out_dir):
os.mkdir(out_dir)
PIL.Image.fromarray(img).save(osp.join(out_dir, 'img.png'))
PIL.Image.fromarray(lbl).save(osp.join(out_dir, 'label.png'))
PIL.Image.fromarray(lbl_viz).save(osp.join(out_dir, 'label_viz.png'))
with open(osp.join(out_dir, 'label_names.txt'), 'w') as f:
for lbl_name in lbl_names:
f.write(lbl_name + '\n')
warnings.warn('info.yaml is being replaced by label_names.txt')
info = dict(label_names=lbl_names)
with open(osp.join(out_dir, 'info.yaml'), 'w') as f:
yaml.safe_dump(info, f, default_flow_style=False)
print('Saved to: %s' % out_dir)
if __name__ == '__main__':
main()
然后将image.png以及label.png保存到另外的文件夹:
import cv2 as cv
import random
import glob
import os
from PIL import Image
import shutil
def get_samples(foldername,savePath):
print('savePath:',savePath)
if os.path.exists(savePath) is False:
os.makedirs(savePath)
filenames = os.listdir(foldername)
for filename in filenames:
full_path = os.path.join(foldername, filename)
new_name = filename[:-5]+'.png'
label_png = os.listdir(full_path)[3]#如果报错或者出来的不对,可以改一下数值
#os.rename(os.path.join(filename, label_png),os.path.join(filename, name))
shutil.copy(os.path.join(full_path, label_png), os.path.join(savePath, label_png))
os.rename(os.path.join(savePath, label_png),os.path.join(savePath, new_name))
#print(os.listdir(filename))
savePath = '/home/customer/Desktop/1/chage/'
get_samples('/home/customer/Desktop/1/ori/',savePath )