split_dataset.py 2.7 KB

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