json_Split.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  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数据集划分,可以通过val_split_rate、val_split_num控制划分比例或个数, keep_val_inTrain可以设定是否在train中保留val相关信息
  17. python ./coco_tools/json_Split.py \
  18. --json_all_path=./annotations/instances_val2017.json \
  19. --json_train_path=./instances_val2017_train.json \
  20. --json_val_path=./instances_val2017_val.json
  21. """
  22. import json
  23. import argparse
  24. import pandas as pd
  25. def get_annno(df_img_split, df_anno):
  26. df_merge = pd.merge(df_img_split, df_anno, on="image_id")
  27. df_anno_split = df_merge[df_anno.columns.to_list()]
  28. df_anno_split = df_anno_split.sort_values(by='id')
  29. return df_anno_split
  30. def js_split(js_all_path, js_train_path, js_val_path, val_split_rate,
  31. val_split_num, keep_val_inTrain, image_keyname, anno_keyname):
  32. print('Split'.center(100, '-'))
  33. print()
  34. print('json read...\n')
  35. with open(js_all_path, 'r') as load_f:
  36. data = json.load(load_f)
  37. df_anno = pd.DataFrame(data[anno_keyname])
  38. df_img = pd.DataFrame(data[image_keyname])
  39. df_img = df_img.rename(columns={"id": "image_id"})
  40. df_img = df_img.sample(frac=1, random_state=0)
  41. if val_split_num is None:
  42. val_split_num = int(val_split_rate * len(df_img))
  43. if keep_val_inTrain:
  44. df_img_train = df_img
  45. df_img_val = df_img[:val_split_num]
  46. df_anno_train = df_anno
  47. df_anno_val = get_annno(df_img_val, df_anno)
  48. else:
  49. df_img_train = df_img[val_split_num:]
  50. df_img_val = df_img[:val_split_num]
  51. df_anno_train = get_annno(df_img_train, df_anno)
  52. df_anno_val = get_annno(df_img_val, df_anno)
  53. df_img_train = df_img_train.rename(columns={"image_id": "id"}).sort_values(
  54. by='id')
  55. df_img_val = df_img_val.rename(columns={"image_id": "id"}).sort_values(
  56. by='id')
  57. data[image_keyname] = json.loads(df_img_train.to_json(orient='records'))
  58. data[anno_keyname] = json.loads(df_anno_train.to_json(orient='records'))
  59. str_json = json.dumps(data, ensure_ascii=False)
  60. with open(js_train_path, 'w', encoding='utf-8') as file_obj:
  61. file_obj.write(str_json)
  62. data[image_keyname] = json.loads(df_img_val.to_json(orient='records'))
  63. data[anno_keyname] = json.loads(df_anno_val.to_json(orient='records'))
  64. str_json = json.dumps(data, ensure_ascii=False)
  65. with open(js_val_path, 'w', encoding='utf-8') as file_obj:
  66. file_obj.write(str_json)
  67. print('image total %d, train %d, val %d' %
  68. (len(df_img), len(df_img_train), len(df_img_val)))
  69. print('anno total %d, train %d, val %d' %
  70. (len(df_anno), len(df_anno_train), len(df_anno_val)))
  71. return df_img
  72. def get_args():
  73. parser = argparse.ArgumentParser(description='Json Merge')
  74. # Parameters
  75. parser.add_argument('--json_all_path', type=str, help='json path to split')
  76. parser.add_argument(
  77. '--json_train_path',
  78. type=str,
  79. help='json path to save the split result -- train part')
  80. parser.add_argument(
  81. '--json_val_path',
  82. type=str,
  83. help='json path to save the split result -- val part')
  84. parser.add_argument(
  85. '--val_split_rate',
  86. type=float,
  87. default=0.1,
  88. help='val image number rate in total image, default is 0.1; if val_split_num is set, val_split_rate will not work'
  89. )
  90. parser.add_argument(
  91. '--val_split_num',
  92. type=int,
  93. default=None,
  94. help='val image number in total image, default is None; if val_split_num is set, val_split_rate will not work'
  95. )
  96. parser.add_argument(
  97. '--keep_val_inTrain',
  98. type=bool,
  99. default=False,
  100. help='if true, val part will be in train as well; which means that the content of json_train_path is the same as the content of json_all_path'
  101. )
  102. parser.add_argument(
  103. '--image_keyname',
  104. type=str,
  105. default='images',
  106. help='image key name in json, default images')
  107. parser.add_argument(
  108. '--anno_keyname',
  109. type=str,
  110. default='annotations',
  111. help='annotation key name in json, default annotations')
  112. parser.add_argument(
  113. '-Args_show',
  114. '--Args_show',
  115. type=bool,
  116. default=True,
  117. help='Args_show(default: True), if True, show args info')
  118. args = parser.parse_args()
  119. if args.Args_show:
  120. print('Args'.center(100, '-'))
  121. for k, v in vars(args).items():
  122. print('%s = %s' % (k, v))
  123. print()
  124. return args
  125. if __name__ == '__main__':
  126. args = get_args()
  127. js_split(args.json_all_path, args.json_train_path, args.json_val_path,
  128. args.val_split_rate, args.val_split_num, args.keep_val_inTrain,
  129. args.image_keyname, args.anno_keyname)