collect_imgs.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #!/usr/bin/env python
  2. # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import argparse
  16. import os
  17. import os.path as osp
  18. import shutil
  19. from glob import glob
  20. from tqdm import tqdm
  21. def get_subdir_name(src_path):
  22. basename = osp.basename(src_path)
  23. subdir_name, _ = osp.splitext(basename)
  24. return subdir_name
  25. def parse_args():
  26. parser = argparse.ArgumentParser()
  27. parser.add_argument(
  28. "--mode",
  29. default='copy',
  30. type=str,
  31. choices=['copy', 'link'],
  32. help="Copy or link images.")
  33. parser.add_argument(
  34. "--globs",
  35. nargs='+',
  36. type=str,
  37. help="Glob patterns used to find the images to be copied.")
  38. parser.add_argument(
  39. "--tags", nargs='+', type=str, help="Tags of each source directory.")
  40. parser.add_argument(
  41. "--save_dir",
  42. default='./',
  43. type=str,
  44. help="Path of directory to save collected results.")
  45. return parser.parse_args()
  46. if __name__ == '__main__':
  47. args = parse_args()
  48. if len(args.globs) != len(args.tags):
  49. raise ValueError(
  50. "The number of globs does not match the number of tags!")
  51. for pat, tag in zip(args.globs, args.tags):
  52. im_paths = glob(pat)
  53. print(f"Glob: {pat}\tTag: {tag}")
  54. for p in tqdm(im_paths):
  55. subdir_name = get_subdir_name(p)
  56. ext = osp.splitext(p)[1]
  57. subdir_path = osp.join(args.save_dir, subdir_name)
  58. subdir_path = osp.abspath(osp.normpath(subdir_path))
  59. if not osp.exists(subdir_path):
  60. os.makedirs(subdir_path)
  61. if args.mode == 'copy':
  62. shutil.copyfile(p, osp.join(subdir_path, tag + ext))
  63. elif args.mode == 'link':
  64. os.symlink(p, osp.join(subdir_path, tag + ext))