split_dataset.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. import shutil
  16. from random import shuffle
  17. from .....utils.file_interface import custom_open
  18. def split_dataset(dataset_root, train_rate, val_rate):
  19. """
  20. 将图像数据集按照比例分成训练集、验证集和测试集,并生成对应的.txt文件。
  21. Args:
  22. dataset_root (str): 数据集根目录路径。
  23. train_rate (int): 训练集占总数据集的比例(%)。
  24. val_rate (int): 验证集占总数据集的比例(%)。
  25. Returns:
  26. str: 数据划分结果信息。
  27. """
  28. sum_rate = train_rate + val_rate
  29. if sum_rate != 100:
  30. return "训练集、验证集比例之和需要等于100,请修改后重试"
  31. tags = ["train", "val"]
  32. valid_path = False
  33. image_files = []
  34. for tag in tags:
  35. split_image_list = os.path.abspath(
  36. os.path.join(dataset_root, f'{tag}.txt'))
  37. rename_image_list = os.path.abspath(
  38. os.path.join(dataset_root, 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. if not valid_path:
  47. return f"数据集目录下保存待划分文件{tags[0]}.txt或{tags[1]}.txt不存在,请检查后重试"
  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. if rate > 100 or rate < 0:
  57. return f"{tag} 数据集的比例应该在0~100之间."
  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(dataset_root, 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 dataset_root