json_Img2Json.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. # -*- coding: utf-8 -*-
  2. # @File : json_getTest.py
  3. # @Author : zhaoHL
  4. # @Contact : huilin16@qq.com
  5. # @Time Create First: 2021/8/1 10:25
  6. # @Contributor : zhaoHL
  7. # @Time Modify Last : 2021/8/1 10:25
  8. '''
  9. @File Description:
  10. # 根据test影像文件夹生成test.json
  11. python ./coco_tools/json_Img2Json.py \
  12. --test_image_path=./test2017 \
  13. --json_train_path=./annotations/instances_val2017.json \
  14. --json_test_path=./test.json
  15. '''
  16. import os, cv2
  17. import json
  18. import argparse
  19. from tqdm import tqdm
  20. def js_test(test_image_path, js_train_path, js_test_path, image_keyname, cat_keyname):
  21. print('Get Test'.center(100, '-'))
  22. print()
  23. print('json read...\n')
  24. data = {}
  25. with open(js_train_path, 'r') as load_f:
  26. data_train = json.load(load_f)
  27. file_list = os.listdir(test_image_path)
  28. # sort method
  29. # file_list.sort(key=lambda x: int(x.split('.')[0]))
  30. # file_list.sort()
  31. print('test image read...')
  32. with tqdm(file_list) as pbar:
  33. images = []
  34. for index, img_name in enumerate(pbar):
  35. img_path = os.path.join(test_image_path, img_name)
  36. img = cv2.imread(img_path)
  37. tmp = {}
  38. tmp['id'] = index
  39. tmp['width'] = img.shape[1]
  40. tmp['height'] = img.shape[0]
  41. tmp['file_name'] = img_name
  42. images.append(tmp)
  43. print('\n total test image:', len(file_list))
  44. data[image_keyname] = images
  45. data[cat_keyname] = data_train[cat_keyname]
  46. with open(js_test_path, 'w') as f:
  47. json.dump(data, f)
  48. def get_args():
  49. parser = argparse.ArgumentParser(description='Get Test Json')
  50. # parameters
  51. parser.add_argument('--test_image_path', type=str,
  52. help='test image path')
  53. parser.add_argument('--json_train_path', type=str,
  54. help='train json path, provide categories information')
  55. parser.add_argument('--json_test_path', type=str,
  56. help='test json path to save')
  57. parser.add_argument('--image_keyname', type=str, default='images',
  58. help='image key name in json, default images')
  59. parser.add_argument('--cat_keyname', type=str, default='categories',
  60. help='categories key name in json, default categories')
  61. parser.add_argument('-Args_show', '--Args_show', type=bool, default=True,
  62. help='Args_show(default: True), if True, show args info')
  63. args = parser.parse_args()
  64. if args.Args_show:
  65. print('Args'.center(100, '-'))
  66. for k, v in vars(args).items():
  67. print('%s = %s' % (k, v))
  68. print()
  69. return args
  70. if __name__ == '__main__':
  71. args = get_args()
  72. js_test(args.test_image_path, args.json_train_path, args.json_test_path, args.image_keyname, args.cat_keyname)