json_Split.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  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, val_split_num, keep_val_inTrain,
  31. 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(by='id')
  54. df_img_val =df_img_val.rename(columns={"image_id": "id"}).sort_values(by='id')
  55. data[image_keyname] = json.loads(df_img_train.to_json(orient='records'))
  56. data[anno_keyname] = json.loads(df_anno_train.to_json(orient='records'))
  57. str_json = json.dumps(data, ensure_ascii=False)
  58. with open(js_train_path, 'w', encoding='utf-8') as file_obj:
  59. file_obj.write(str_json)
  60. data[image_keyname] = json.loads(df_img_val.to_json(orient='records'))
  61. data[anno_keyname] = json.loads(df_anno_val.to_json(orient='records'))
  62. str_json = json.dumps(data, ensure_ascii=False)
  63. with open(js_val_path, 'w', encoding='utf-8') as file_obj:
  64. file_obj.write(str_json)
  65. print('image total %d, train %d, val %d'%(len(df_img), len(df_img_train), len(df_img_val)))
  66. print('anno total %d, train %d, val %d'%(len(df_anno), len(df_anno_train), len(df_anno_val)))
  67. return df_img
  68. def get_args():
  69. parser = argparse.ArgumentParser(description='Json Merge')
  70. # parameters
  71. parser.add_argument('--json_all_path', type=str,
  72. help='json path to split')
  73. parser.add_argument('--json_train_path', type=str,
  74. help='json path to save the split result -- train part')
  75. parser.add_argument('--json_val_path', type=str,
  76. help='json path to save the split result -- val part')
  77. parser.add_argument('--val_split_rate', type=float, default=0.1,
  78. help='val image number rate in total image, default is 0.1; if val_split_num is set, val_split_rate will not work')
  79. parser.add_argument('--val_split_num', type=int, default=None,
  80. help='val image number in total image, default is None; if val_split_num is set, val_split_rate will not work')
  81. parser.add_argument('--keep_val_inTrain', type=bool, default=False,
  82. 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')
  83. parser.add_argument('--image_keyname', type=str, default='images',
  84. help='image key name in json, default images')
  85. parser.add_argument('--anno_keyname', type=str, default='annotations',
  86. help='annotation key name in json, default annotations')
  87. parser.add_argument('-Args_show', '--Args_show', type=bool, default=True,
  88. help='Args_show(default: True), if True, show args info')
  89. args = parser.parse_args()
  90. if args.Args_show:
  91. print('Args'.center(100,'-'))
  92. for k, v in vars(args).items():
  93. print('%s = %s' % (k, v))
  94. print()
  95. return args
  96. if __name__ == '__main__':
  97. args = get_args()
  98. js_split(args.json_all_path,args.json_train_path,args.json_val_path, args.val_split_rate, args.val_split_num,
  99. args.keep_val_inTrain, args.image_keyname, args.anno_keyname)