split_dataset.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. # !/usr/bin/env python3
  2. # -*- coding: UTF-8 -*-
  3. ################################################################################
  4. #
  5. # Copyright (c) 2024 Baidu.com, Inc. All Rights Reserved
  6. #
  7. ################################################################################
  8. """
  9. Author: PaddlePaddle Authors
  10. """
  11. import os
  12. from random import shuffle
  13. from .....utils.file_interface import custom_open
  14. def split_dataset(root_dir, train_rate, val_rate):
  15. """
  16. 将图像数据集按照比例分成训练集、验证集和测试集,并生成对应的.txt文件。
  17. Args:
  18. root_dir (str): 数据集根目录路径。
  19. train_rate (int): 训练集占总数据集的比例(%)。
  20. val_rate (int): 验证集占总数据集的比例(%)。
  21. Returns:
  22. str: 数据划分结果信息。
  23. """
  24. sum_rate = train_rate + val_rate
  25. assert sum_rate == 100, \
  26. f"The sum of train_rate({train_rate}), val_rate({val_rate}) should equal 100!"
  27. assert train_rate > 0 and val_rate > 0, \
  28. f"The train_rate({train_rate}) and val_rate({val_rate}) should be greater than 0!"
  29. tags = ["train", "val"]
  30. valid_path = False
  31. image_files = []
  32. for tag in tags:
  33. split_image_list = os.path.abspath(os.path.join(root_dir, f'{tag}.txt'))
  34. rename_image_list = os.path.abspath(
  35. os.path.join(root_dir, f'{tag}.txt.bak'))
  36. if os.path.exists(split_image_list):
  37. with custom_open(split_image_list, 'r') as f:
  38. lines = f.readlines()
  39. image_files = image_files + lines
  40. valid_path = True
  41. if not os.path.exists(rename_image_list):
  42. os.rename(split_image_list, rename_image_list)
  43. assert valid_path, \
  44. f"The files to be divided{tags[0]}.txt, {tags[1]}.txt, do not exist in the dataset directory."
  45. shuffle(image_files)
  46. start = 0
  47. image_num = len(image_files)
  48. rate_list = [train_rate, val_rate]
  49. for i, tag in enumerate(tags):
  50. rate = rate_list[i]
  51. if rate == 0:
  52. continue
  53. end = start + round(image_num * rate / 100)
  54. if sum(rate_list[i + 1:]) == 0:
  55. end = image_num
  56. txt_file = os.path.abspath(os.path.join(root_dir, tag + '.txt'))
  57. with custom_open(txt_file, 'w') as f:
  58. m = 0
  59. for id in range(start, end):
  60. m += 1
  61. f.write(image_files[id])
  62. start = end
  63. return root_dir