check_dataset.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  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. import os.path as osp
  16. import random
  17. from PIL import Image, ImageOps
  18. from .....utils.errors import CheckFailedError, DatasetFileNotFoundError
  19. from .utils.visualizer import draw_label
  20. def check_train(dataset_dir, output, sample_num=10):
  21. """check dataset"""
  22. dataset_dir = osp.abspath(dataset_dir)
  23. # Custom dataset
  24. if not osp.exists(dataset_dir) or not osp.isdir(dataset_dir):
  25. raise DatasetFileNotFoundError(file_path=dataset_dir)
  26. delim = " "
  27. valid_num_parts = 2
  28. label_map_dict = dict()
  29. sample_paths = []
  30. labels = []
  31. label_file = osp.join(dataset_dir, "label.txt")
  32. if not osp.exists(label_file):
  33. raise DatasetFileNotFoundError(
  34. file_path=label_file,
  35. solution=f"Ensure that `label.txt` exist in {dataset_dir}",
  36. )
  37. with open(label_file, "r", encoding="utf-8") as f:
  38. all_lines = f.readlines()
  39. random.seed(123)
  40. random.shuffle(all_lines)
  41. sample_cnts = len(all_lines)
  42. for line in all_lines:
  43. substr = line.strip("\n").split(delim)
  44. if len(substr) != valid_num_parts:
  45. raise CheckFailedError(
  46. f"The number of delimiter-separated items in each row in {label_file} \
  47. should be {valid_num_parts} (current delimiter is '{delim}')."
  48. )
  49. file_name = substr[0]
  50. label = substr[1]
  51. img_path = osp.join(dataset_dir, file_name)
  52. if not osp.exists(img_path):
  53. raise DatasetFileNotFoundError(file_path=img_path)
  54. vis_save_dir = osp.join(output, "demo_img")
  55. if not osp.exists(vis_save_dir):
  56. os.makedirs(vis_save_dir)
  57. try:
  58. label = int(label)
  59. label_map_dict[label] = str(label)
  60. except (ValueError, TypeError) as e:
  61. raise CheckFailedError(
  62. f"Ensure that the second number in each line in {label_file} should be int."
  63. ) from e
  64. if len(sample_paths) < sample_num:
  65. img = Image.open(img_path)
  66. img = ImageOps.exif_transpose(img)
  67. vis_im = draw_label(img, label, label_map_dict)
  68. vis_path = osp.join(vis_save_dir, osp.basename(file_name))
  69. vis_im.save(vis_path)
  70. sample_path = osp.join(
  71. "check_dataset", os.path.relpath(vis_path, output)
  72. )
  73. sample_paths.append(sample_path)
  74. labels.append(label)
  75. if min(labels) != 0:
  76. raise CheckFailedError(
  77. f"Ensure that the index starts from 0 in `{label_file}`."
  78. )
  79. num_classes = max(labels) + 1
  80. attrs = {}
  81. attrs["train_label_file"] = osp.relpath(label_file, output)
  82. attrs["train_num_classes"] = num_classes
  83. attrs["train_samples"] = sample_cnts
  84. attrs["train_sample_paths"] = sample_paths
  85. return attrs
  86. def check_val(dataset_dir, output, sample_num=10):
  87. """check dataset"""
  88. dataset_dir = osp.abspath(dataset_dir)
  89. # Custom dataset
  90. if not osp.exists(dataset_dir) or not osp.isdir(dataset_dir):
  91. raise DatasetFileNotFoundError(file_path=dataset_dir)
  92. delim = " "
  93. valid_num_parts = 3
  94. labels = []
  95. sample_paths = []
  96. label_file = osp.join(dataset_dir, "pair_label.txt")
  97. if not osp.exists(label_file):
  98. raise DatasetFileNotFoundError(
  99. file_path=label_file,
  100. solution=f"Ensure that `label.txt` exist in {dataset_dir}",
  101. )
  102. with open(label_file, "r", encoding="utf-8") as f:
  103. all_lines = f.readlines()
  104. random.seed(123)
  105. random.shuffle(all_lines)
  106. sample_cnts = len(all_lines)
  107. for line in all_lines:
  108. substr = line.strip("\n").split(delim)
  109. if len(substr) != valid_num_parts:
  110. raise CheckFailedError(
  111. f"The number of delimiter-separated items in each row in {label_file} \
  112. should be {valid_num_parts} (current delimiter is '{delim}')."
  113. )
  114. left_file_name = substr[0]
  115. right_file_name = substr[1]
  116. label = substr[2]
  117. left_img_path = osp.join(dataset_dir, left_file_name)
  118. if not osp.exists(left_img_path):
  119. raise DatasetFileNotFoundError(file_path=left_img_path)
  120. right_img_path = osp.join(dataset_dir, right_file_name)
  121. if not osp.exists(right_img_path):
  122. raise DatasetFileNotFoundError(file_path=right_img_path)
  123. try:
  124. label = int(label)
  125. assert label in [0, 1], "Face eval dataset only support two classes"
  126. except (ValueError, TypeError) as e:
  127. raise CheckFailedError(
  128. f"Ensure that the second number in each line in {label_file} should be int."
  129. ) from e
  130. vis_save_dir = osp.join(output, "demo_img")
  131. if not osp.exists(vis_save_dir):
  132. os.makedirs(vis_save_dir)
  133. if len(sample_paths) < sample_num:
  134. img = Image.open(left_img_path)
  135. img = ImageOps.exif_transpose(img)
  136. vis_path = osp.join(vis_save_dir, osp.basename(left_file_name))
  137. img.save(vis_path)
  138. sample_path = osp.join(
  139. "check_dataset", os.path.relpath(vis_path, output)
  140. )
  141. sample_paths.append(sample_path)
  142. labels.append(label)
  143. num_classes = max(labels) + 1
  144. attrs = {}
  145. attrs["val_label_file"] = osp.relpath(label_file, output)
  146. attrs["val_num_classes"] = num_classes
  147. attrs["val_samples"] = sample_cnts
  148. attrs["val_sample_paths"] = sample_paths
  149. return attrs