make_txt.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435
  1. import os
  2. import argparse
  3. # -------------------------------------------------------------------------------------------------------------------- #
  4. # 设置
  5. parser = argparse.ArgumentParser(description='将文件夹中的图片和类别号按比例添加到train.txt和val.txt中')
  6. parser.add_argument('--image_path', default=r'D:\dataset\classification\mask\image\mask', type=str, help='|图片所在目录|')
  7. parser.add_argument('--add', default=' 0', type=str, help='|标签内容为[图片绝对路径+add]|')
  8. parser.add_argument('--divide', default='9,1', type=str, help='|图片划分到train.txt和val.txt的比例|')
  9. args = parser.parse_args()
  10. # -------------------------------------------------------------------------------------------------------------------- #
  11. # 程序
  12. if __name__ == '__main__':
  13. if not os.path.exists('train.txt'):
  14. with open('train.txt', 'w')as f:
  15. pass
  16. if not os.path.exists('val.txt'):
  17. with open('val.txt', 'w')as f:
  18. pass
  19. image_dir = sorted(os.listdir(args.image_path))
  20. args.divide = list(map(int, args.divide.split(',')))
  21. boundary = int(len(image_dir) * args.divide[0] / (args.divide[0] + args.divide[1]))
  22. with open('train.txt', 'a')as f:
  23. write_line = []
  24. for i in range(boundary):
  25. label = args.image_path + '/' + image_dir[i] + args.add
  26. write_line.append(label + '\n')
  27. f.writelines(write_line)
  28. with open('val.txt', 'a')as f:
  29. write_line = []
  30. for i in range(boundary, len(image_dir)):
  31. label = args.image_path + '/' + image_dir[i] + args.add
  32. write_line.append(label + '\n')
  33. f.writelines(write_line)