collect_imgs.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #!/usr/bin/env python
  2. import argparse
  3. import os
  4. import os.path as osp
  5. import shutil
  6. from glob import glob
  7. from tqdm import tqdm
  8. def get_subdir_name(src_path):
  9. basename = osp.basename(src_path)
  10. subdir_name, _ = osp.splitext(basename)
  11. return subdir_name
  12. def parse_args():
  13. parser = argparse.ArgumentParser()
  14. parser.add_argument(
  15. "--mode",
  16. default='copy',
  17. type=str,
  18. choices=['copy', 'link'],
  19. help="Copy or link images.")
  20. parser.add_argument(
  21. "--globs",
  22. nargs='+',
  23. type=str,
  24. help="Glob patterns used to find the images to be copied.")
  25. parser.add_argument(
  26. "--tags", nargs='+', type=str, help="Tags of each source directory.")
  27. parser.add_argument(
  28. "--save_dir",
  29. default='./',
  30. type=str,
  31. help="Path of directory to save collected results.")
  32. return parser.parse_args()
  33. if __name__ == '__main__':
  34. args = parse_args()
  35. if len(args.globs) != len(args.tags):
  36. raise ValueError(
  37. "The number of globs does not match the number of tags!")
  38. for pat, tag in zip(args.globs, args.tags):
  39. im_paths = glob(pat)
  40. print(f"Glob: {pat}\tTag: {tag}")
  41. for p in tqdm(im_paths):
  42. subdir_name = get_subdir_name(p)
  43. ext = osp.splitext(p)[1]
  44. subdir_path = osp.join(args.save_dir, subdir_name)
  45. subdir_path = osp.abspath(osp.normpath(subdir_path))
  46. if not osp.exists(subdir_path):
  47. os.makedirs(subdir_path)
  48. if args.mode == 'copy':
  49. shutil.copyfile(p, osp.join(subdir_path, tag + ext))
  50. elif args.mode == 'link':
  51. os.symlink(p, osp.join(subdir_path, tag + ext))