split_dataset.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. # Copyright (c) 2024 PaddlePaddle Authors. All Rights Reserved.
  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 (
  29. sum_rate == 100
  30. ), f"The sum of train_rate({train_rate}), val_rate({val_rate}) should equal 100!"
  31. assert (
  32. train_rate > 0 and val_rate > 0
  33. ), f"The train_rate({train_rate}) and val_rate({val_rate}) should be greater than 0!"
  34. tags = ["train", "val"]
  35. valid_path = False
  36. image_files = []
  37. for tag in tags:
  38. split_image_list = os.path.abspath(os.path.join(root_dir, f"{tag}.txt"))
  39. rename_image_list = os.path.abspath(os.path.join(root_dir, f"{tag}.txt.bak"))
  40. if os.path.exists(split_image_list):
  41. with custom_open(split_image_list, "r") as f:
  42. lines = f.readlines()
  43. image_files = image_files + lines
  44. valid_path = True
  45. if not os.path.exists(rename_image_list):
  46. os.rename(split_image_list, rename_image_list)
  47. assert (
  48. valid_path
  49. ), f"The files to be divided{tags[0]}.txt, {tags[1]}.txt, do not exist in the dataset directory."
  50. shuffle(image_files)
  51. start = 0
  52. image_num = len(image_files)
  53. rate_list = [train_rate, val_rate]
  54. for i, tag in enumerate(tags):
  55. rate = rate_list[i]
  56. if rate == 0:
  57. continue
  58. end = start + round(image_num * rate / 100)
  59. if sum(rate_list[i + 1 :]) == 0:
  60. end = image_num
  61. txt_file = os.path.abspath(os.path.join(root_dir, tag + ".txt"))
  62. with custom_open(txt_file, "w") as f:
  63. m = 0
  64. for id in range(start, end):
  65. m += 1
  66. f.write(image_files[id])
  67. start = end
  68. return root_dir