json_image2json.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. import os
  15. import json
  16. import argparse
  17. import cv2
  18. from tqdm import tqdm
  19. def json_image2json(image_dir, json_train_path, json_test_path, img_keyname,
  20. cat_keyname):
  21. print("Image to Json".center(100, "-"))
  22. print("json read...\n")
  23. data = {}
  24. with open(json_train_path, "r") as load_f:
  25. data_train = json.load(load_f)
  26. file_list = os.listdir(image_dir)
  27. print("test image read...")
  28. with tqdm(file_list) as pbar:
  29. images = []
  30. for index, image_name in enumerate(pbar):
  31. image_path = os.path.join(image_dir, image_name)
  32. image = cv2.imread(image_path)
  33. tmp = {}
  34. tmp["id"] = index
  35. tmp["width"] = image.shape[1]
  36. tmp["height"] = image.shape[0]
  37. tmp["file_name"] = image_name
  38. images.append(tmp)
  39. print("\n total test image:", len(file_list))
  40. data[img_keyname] = images
  41. data[cat_keyname] = data_train[cat_keyname]
  42. with open(json_test_path, "w") as f:
  43. json.dump(data, f)
  44. if __name__ == "__main__":
  45. parser = argparse.ArgumentParser(
  46. description="Generate JSON file from image directory")
  47. parser.add_argument("--image_dir", type=str, required=True, \
  48. help="Directory that contains the test set images.")
  49. parser.add_argument("--json_train_path", type=str, required=True, \
  50. help="JSON file path of the training set. Used as reference.")
  51. parser.add_argument("--result_path", type=str, required=True, \
  52. help="Path to the generated test set JSON file.")
  53. parser.add_argument("--img_keyname", type=str, default="images", \
  54. help="Image key in the JSON file.")
  55. parser.add_argument("--cat_keyname", type=str, default="categories", \
  56. help="Category key in the JSON file.")
  57. args = parser.parse_args()
  58. json_image2json(args.image_dir, args.json_train_path, args.result_path,
  59. args.img_keyname, args.cat_keyname)