将labelme生成的json文件转换成png图
生活随笔
收集整理的這篇文章主要介紹了
将labelme生成的json文件转换成png图
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
將labelme生成的json文件轉換成png圖
我圖片的每個標記只有一類,所以轉換成png圖后,png只有0和1像素,因為單通道圖的范圍是0~255,0和1的區別很小,下面的程序可以對你標記的mask做可視化,但是生成的png還是像素值為0和1的,如果自己有需要可以改像素值。
首先要把所有你需要轉換的json文件放在一個文件夾里,然后把這個文件夾的路徑填入到下面的json_file就可以了。程序運行完會在文件下生成兩個文件夾:mask和mask_viz
mask中有png圖,和兩個標簽文件
mask_viz中是可視化的mask圖
程序:
#!/usr/bin/python # -*- coding: UTF-8 -*- # !H:\Anaconda3\envs\new_labelme\python.exe import argparse import json import os import os.path as osp import base64 import warningsimport PIL.Image import yamlfrom labelme import utilsimport cv2 import numpy as np from skimage import img_as_ubyte# from sys import argvdef main():warnings.warn("This script is aimed to demonstrate how to convert the\n""JSON file to a single image dataset, and not to handle\n""multiple JSON files to generate a real-use dataset.")json_file = "/home/jfw/needlabel/6_json/"# freedomlist_path = os.listdir(json_file)print('freedom =', json_file)for i in range(0, len(list_path)):path = os.path.join(json_file, list_path[i])if os.path.isfile(path):data = json.load(open(path))img = utils.img_b64_to_arr(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(path).replace('.', '_')out_dir = osp.basename(path).split('.json')[0]save_file_name = out_dir# out_dir = osp.join(osp.dirname(path), out_dir)if not osp.exists(json_file + 'mask'):os.mkdir(json_file + 'mask')maskdir = json_file + 'mask'if not osp.exists(json_file + 'mask_viz'):os.mkdir(json_file + 'mask_viz')maskvizdir = json_file + 'mask_viz'out_dir1 = maskdir# if not osp.exists(out_dir1):# os.mkdir(out_dir1)# PIL.Image.fromarray(img).save(out_dir1 + '\\' + save_file_name + '_img.png')PIL.Image.fromarray(lbl).save(out_dir1 +'/'+ save_file_name + '.png')PIL.Image.fromarray(lbl_viz).save(maskvizdir + '/' + save_file_name +'_label_viz.png')# if not osp.exists(json_file + '\\' + 'mask_png'):# os.mkdir(json_file + '\\' + 'mask_png')# mask_save2png_path = json_file + '\\' + 'mask_png'################################# mask_pic = cv2.imread(out_dir1+'\\'+save_file_name+'_label.png',)# print('pic1_deep:',mask_pic.dtype)# mask_dst = img_as_ubyte(lbl) # mask_pic# print('pic2_deep:', mask_dst.dtype)# cv2.imwrite(mask_save2png_path + '\\' + save_file_name + '_label.png', mask_dst)##################################with open(osp.join(out_dir1, '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_dir1, 'info.yaml'), 'w') as f:yaml.safe_dump(info, f, default_flow_style=False)print('Saved to: %s' % out_dir1)if __name__ == '__main__':# base64path = argv[1]main()總結
以上是生活随笔為你收集整理的将labelme生成的json文件转换成png图的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: led拼接屏报价_lcd是什么意思?lc
- 下一篇: 报错--01