Label_Studio2Labelme.py 3.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import copy
  2. import json
  3. import argparse
  4. import numpy
  5. import glob
  6. import os
  7. from tqdm import tqdm
  8. def Label_Studio2Labelme(label_Studio_json_dirs, labelme_json_dir):
  9. labelme_json = {}
  10. shape_dic = {}
  11. jsons_path = []
  12. for labelme_dir in label_Studio_json_dirs:
  13. list_path = glob.glob(labelme_dir + "/*.json")
  14. jsons_path.extend(list_path)
  15. for Label_Studio_json in jsons_path:
  16. with open(Label_Studio_json, 'r', encoding='utf-8') as f:
  17. info = json.load(f)
  18. for json_dic in info:
  19. if not json_dic['annotations'][0]['result']:
  20. continue
  21. shapes_list = []
  22. labelme_json['version'] = '5.0.1'
  23. labelme_json['flags'] = {}
  24. for result_dic in tqdm(json_dic['annotations'][0]['result']):
  25. # print(len(result_dic))
  26. points_list = []
  27. # 进行标签改动
  28. if result_dic['value']['rectanglelabels'][0] == 'Pseudocode':
  29. shape_dic['label'] = 'Code'
  30. else:
  31. shape_dic['label'] = copy.deepcopy(result_dic['value']['rectanglelabels'][0])
  32. x1, y1 = result_dic['value']['x'] * result_dic['original_width'] / 100, \
  33. result_dic['value']['y'] * result_dic['original_height'] / 100
  34. points_list.append([x1, y1])
  35. x2, y2 = x1 + result_dic['value']['width'] * result_dic['original_width'] / 100, \
  36. y1 + result_dic['value']['height'] * result_dic['original_height'] / 100
  37. points_list.append([x2, y2])
  38. shape_dic['points'] = points_list
  39. shape_dic['group_id'] = None
  40. shape_dic['shape_type'] = result_dic['type'][:9]
  41. shape_dic['flags'] = {}
  42. shapes_list.append(copy.deepcopy(shape_dic))
  43. labelme_json['shapes'] = shapes_list
  44. labelme_json['imagePath'] = os.path.basename(json_dic['data']['image'])
  45. labelme_json['imageData'] = None
  46. labelme_json['imageHeight'] = json_dic['annotations'][0]['result'][0]['original_height']
  47. labelme_json['imageWidth'] = json_dic['annotations'][0]['result'][0]['original_width']
  48. labelme_json['updated_by'] = json_dic['updated_by']
  49. json.dump(labelme_json,
  50. open(labelme_json_dir + '/' +
  51. str(os.path.splitext(os.path.basename(json_dic['data']['image']))[0]) + '.json',
  52. 'w', encoding='utf-8'),
  53. ensure_ascii=False, indent=2)
  54. f.close()
  55. if __name__ == '__main__':
  56. parser = argparse.ArgumentParser()
  57. parser.add_argument('--Label_Studio_json_dirs', type=str,
  58. nargs="+", default=[])
  59. parser.add_argument('--Labelme_json_dir', type=str, default='')
  60. args = parser.parse_args()
  61. Label_Studio2Labelme(args.Label_Studio_json_dirs, args.Labelme_json_dir)