json_to_dataset.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import argparse
  2. import base64
  3. import json
  4. import os
  5. import os.path as osp
  6. import imgviz
  7. import PIL.Image
  8. from labelme.logger import logger
  9. from labelme import utils
  10. def main():
  11. logger.warning('This script is aimed to demonstrate how to convert the '
  12. 'JSON file to a single image dataset.')
  13. logger.warning("It won't handle multiple JSON files to generate a "
  14. "real-use dataset.")
  15. parser = argparse.ArgumentParser()
  16. parser.add_argument('json_file')
  17. parser.add_argument('-o', '--out', default=None)
  18. args = parser.parse_args()
  19. json_file = args.json_file
  20. if args.out is None:
  21. out_dir = osp.basename(json_file).replace('.', '_')
  22. out_dir = osp.join(osp.dirname(json_file), out_dir)
  23. else:
  24. out_dir = args.out
  25. if not osp.exists(out_dir):
  26. os.mkdir(out_dir)
  27. data = json.load(open(json_file))
  28. imageData = data.get('imageData')
  29. if not imageData:
  30. imagePath = os.path.join(os.path.dirname(json_file), data['imagePath'])
  31. with open(imagePath, 'rb') as f:
  32. imageData = f.read()
  33. imageData = base64.b64encode(imageData).decode('utf-8')
  34. img = utils.img_b64_to_arr(imageData)
  35. label_name_to_value = {'_background_': 0}
  36. for shape in sorted(data['shapes'], key=lambda x: x['label']):
  37. label_name = shape['label']
  38. if label_name in label_name_to_value:
  39. label_value = label_name_to_value[label_name]
  40. else:
  41. label_value = len(label_name_to_value)
  42. label_name_to_value[label_name] = label_value
  43. lbl, _ = utils.shapes_to_label(
  44. img.shape, data['shapes'], label_name_to_value
  45. )
  46. label_names = [None] * (max(label_name_to_value.values()) + 1)
  47. for name, value in label_name_to_value.items():
  48. label_names[value] = name
  49. lbl_viz = imgviz.label2rgb(
  50. label=lbl, img=imgviz.asgray(img), label_names=label_names, loc='rb'
  51. )
  52. PIL.Image.fromarray(img).save(osp.join(out_dir, 'img.png'))
  53. utils.lblsave(osp.join(out_dir, 'label.png'), lbl)
  54. PIL.Image.fromarray(lbl_viz).save(osp.join(out_dir, 'label_viz.png'))
  55. with open(osp.join(out_dir, 'label_names.txt'), 'w') as f:
  56. for lbl_name in label_names:
  57. f.write(lbl_name + '\n')
  58. logger.info('Saved to: {}'.format(out_dir))
  59. if __name__ == '__main__':
  60. main()