split_dataset.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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(dataset_root, train_rate, val_rate):
  18. """
  19. 将图像数据集按照比例分成训练集、验证集和测试集,并生成对应的.txt文件。
  20. Args:
  21. dataset_root (str): 数据集根目录路径。
  22. train_rate (int): 训练集占总数据集的比例(%)。
  23. val_rate (int): 验证集占总数据集的比例(%)。
  24. Returns:
  25. str: 数据划分结果信息。
  26. """
  27. sum_rate = train_rate + val_rate
  28. if sum_rate != 100:
  29. return "训练集、验证集比例之和需要等于100,请修改后重试"
  30. tags = ["train", "val"]
  31. valid_path = False
  32. image_files = []
  33. for tag in tags:
  34. split_image_list = os.path.abspath(os.path.join(dataset_root, f"{tag}.txt"))
  35. rename_image_list = os.path.abspath(
  36. os.path.join(dataset_root, f"{tag}.txt.bak")
  37. )
  38. if os.path.exists(split_image_list):
  39. with custom_open(split_image_list, "r") as f:
  40. lines = f.readlines()
  41. image_files = image_files + lines
  42. valid_path = True
  43. if not os.path.exists(rename_image_list):
  44. os.rename(split_image_list, rename_image_list)
  45. if not valid_path:
  46. return f"数据集目录下保存待划分文件{tags[0]}.txt或{tags[1]}.txt不存在,请检查后重试"
  47. shuffle(image_files)
  48. start = 0
  49. image_num = len(image_files)
  50. rate_list = [train_rate, val_rate]
  51. for i, tag in enumerate(tags):
  52. rate = rate_list[i]
  53. if rate == 0:
  54. continue
  55. if rate > 100 or rate < 0:
  56. return f"{tag} 数据集的比例应该在0~100之间."
  57. end = start + round(image_num * rate / 100)
  58. if sum(rate_list[i + 1 :]) == 0:
  59. end = image_num
  60. txt_file = os.path.abspath(os.path.join(dataset_root, tag + ".txt"))
  61. with custom_open(txt_file, "w") as f:
  62. m = 0
  63. for id in range(start, end):
  64. m += 1
  65. f.write(image_files[id])
  66. start = end
  67. return dataset_root