json2mask.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. """
  2. # File : json2mask.py
  3. # Time :2024-04-22 10:01
  4. # Author :FEANGYANG
  5. # version :python 3.7
  6. # Contact :1071082183@qq.com
  7. # Description:
  8. """
  9. import argparse
  10. import json
  11. import os
  12. import os.path as osp
  13. import warnings
  14. import copy
  15. import numpy as np
  16. import PIL.Image
  17. from skimage import io
  18. import yaml
  19. from labelme import utils
  20. def main():
  21. parser = argparse.ArgumentParser()
  22. parser.add_argument('json_file') # 标注文件json所在的文件夹
  23. parser.add_argument('-o', '--out', default=None)
  24. args = parser.parse_args()
  25. json_file = args.json_file
  26. list = os.listdir(json_file) # 获取json文件列表
  27. for i in range(0, len(list)):
  28. path = os.path.join(json_file, list[i]) # 获取每个json文件的绝对路径
  29. filename = list[i][:-5] # 提取出.json前的字符作为文件名,以便后续保存Label图片的时候使用
  30. extension = list[i][-4:]
  31. if extension == 'json':
  32. if os.path.isfile(path):
  33. data = json.load(open(path))
  34. img = utils.image.img_b64_to_arr(data['imageData']) # 根据'imageData'字段的字符可以得到原图像
  35. # lbl为label图片(标注的地方用类别名对应的数字来标,其他为0)lbl_names为label名和数字的对应关系字典
  36. lbl, lbl_names = utils.shape.labelme_shapes_to_label(img.shape, data['shapes']) # data['shapes']是json文件中记录着标注的位置及label等信息的字段
  37. #captions = ['%d: %s' % (l, name) for l, name in enumerate(lbl_names)]
  38. #lbl_viz = utils.draw.draw_label(lbl, img, captions)
  39. out_dir = osp.basename(list[i])[:-5]+'_json'
  40. out_dir = osp.join(osp.dirname(list[i]), out_dir)
  41. if not osp.exists(out_dir):
  42. os.mkdir(out_dir)
  43. PIL.Image.fromarray(img).save(osp.join(out_dir, '{}_source.png'.format(filename)))
  44. PIL.Image.fromarray(lbl).save(osp.join(out_dir, '{}_mask.png'.format(filename)))
  45. #PIL.Image.fromarray(lbl_viz).save(osp.join(out_dir, '{}_viz.jpg'.format(filename)))
  46. with open(osp.join(out_dir, 'label_names.txt'), 'w') as f:
  47. for lbl_name in lbl_names:
  48. f.write(lbl_name + '\n')
  49. warnings.warn('info.yaml is being replaced by label_names.txt')
  50. info = dict(label_names=lbl_names)
  51. with open(osp.join(out_dir, 'info.yaml'), 'w') as f:
  52. yaml.safe_dump(info, f, default_flow_style=False)
  53. print('Saved to: %s' % out_dir)
  54. if __name__ == '__main__':
  55. main()