json_Merge.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """
  15. @File Description:
  16. # 合并json文件,可以通过merge_keys控制合并的字段, 默认合并'images', 'annotations'字段
  17. python ./coco_tools/json_Merge.py \
  18. --json1_path=./annotations/instances_train2017.json \
  19. --json2_path=./annotations/instances_val2017.json \
  20. --save_path=./instances_trainval2017.json
  21. """
  22. import json
  23. import argparse
  24. def js_merge(js1_path, js2_path, js_merge_path, merge_keys):
  25. print('Merge'.center(100, '-'))
  26. print()
  27. print('json read...\n')
  28. with open(js1_path, 'r') as load_f:
  29. data1 = json.load(load_f)
  30. with open(js2_path, 'r') as load_f:
  31. data2 = json.load(load_f)
  32. print('json merge...')
  33. data = {}
  34. for k, v in data1.items():
  35. if k not in merge_keys:
  36. data[k] = v
  37. print(k)
  38. else:
  39. data[k] = data1[k] + data2[k]
  40. print(k, 'merge!')
  41. print()
  42. print('json save...\n')
  43. data_str = json.dumps(data, ensure_ascii=False)
  44. with open(js_merge_path, 'w', encoding='utf-8') as save_f:
  45. save_f.write(data_str)
  46. print('finish!')
  47. def get_args():
  48. parser = argparse.ArgumentParser(description='Json Merge')
  49. # Parameters
  50. parser.add_argument('--json1_path', type=str, help='json path1 to merge')
  51. parser.add_argument('--json2_path', type=str, help='json path2 to merge')
  52. parser.add_argument(
  53. '--save_path', type=str, help='json path to save the merge result')
  54. parser.add_argument(
  55. '--merge_keys',
  56. type=list,
  57. default=['images', 'annotations'],
  58. help='json keys that need to merge')
  59. parser.add_argument(
  60. '-Args_show',
  61. '--Args_show',
  62. type=bool,
  63. default=True,
  64. help='Args_show(default: True), if True, show args info')
  65. args = parser.parse_args()
  66. if args.Args_show:
  67. print('Args'.center(100, '-'))
  68. for k, v in vars(args).items():
  69. print('%s = %s' % (k, v))
  70. print()
  71. return args
  72. if __name__ == '__main__':
  73. args = get_args()
  74. js_merge(args.json1_path, args.json2_path, args.save_path, args.merge_keys)