check_dataset.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  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 os.path as osp
  16. import random
  17. from PIL import Image, ImageOps
  18. from collections import defaultdict
  19. from .....utils.errors import DatasetFileNotFoundError, CheckFailedError
  20. from .utils.visualizer import draw_label
  21. def check(dataset_dir, output, sample_num=10):
  22. """ check dataset """
  23. dataset_dir = osp.abspath(dataset_dir)
  24. # Custom dataset
  25. if not osp.exists(dataset_dir) or not osp.isdir(dataset_dir):
  26. raise DatasetFileNotFoundError(file_path=dataset_dir)
  27. tags = ['train', 'val']
  28. delim = ' '
  29. valid_num_parts = 2
  30. sample_cnts = dict()
  31. label_map_dict = dict()
  32. sample_paths = defaultdict(list)
  33. labels = []
  34. label_file = osp.join(dataset_dir, 'label.txt')
  35. if not osp.exists(label_file):
  36. raise DatasetFileNotFoundError(
  37. file_path=label_file,
  38. solution=f"Ensure that `label.txt` exist in {dataset_dir}")
  39. with open(label_file, 'r', encoding='utf-8') as f:
  40. all_lines = f.readlines()
  41. for line in all_lines:
  42. substr = line.strip("\n").split(delim, 1)
  43. try:
  44. label_idx = int(substr[0])
  45. labels.append(label_idx)
  46. label_map_dict[label_idx] = str(substr[1])
  47. except:
  48. raise CheckFailedError(
  49. f"Ensure that the first number in each line in {label_file} should be int."
  50. )
  51. if min(labels) != 0:
  52. raise CheckFailedError(
  53. f"Ensure that the index starts from 0 in `{label_file}`.")
  54. for tag in tags:
  55. file_list = osp.join(dataset_dir, f'{tag}.txt')
  56. if not osp.exists(file_list):
  57. if tag in ('train', 'val'):
  58. # train and val file lists must exist
  59. raise DatasetFileNotFoundError(
  60. file_path=file_list,
  61. solution=f"Ensure that both `train.txt` and `val.txt` exist in {dataset_dir}"
  62. )
  63. else:
  64. # tag == 'test'
  65. continue
  66. else:
  67. with open(file_list, 'r', encoding='utf-8') as f:
  68. all_lines = f.readlines()
  69. random.seed(123)
  70. random.shuffle(all_lines)
  71. sample_cnts[tag] = len(all_lines)
  72. for line in all_lines:
  73. substr = line.strip("\n").split(delim)
  74. if len(substr) != valid_num_parts:
  75. raise CheckFailedError(
  76. f"The number of delimiter-separated items in each row in {file_list} \
  77. should be {valid_num_parts} (current delimiter is '{delim}')."
  78. )
  79. file_name = substr[0]
  80. label = substr[1]
  81. img_path = osp.join(dataset_dir, file_name)
  82. if not osp.exists(img_path):
  83. raise DatasetFileNotFoundError(file_path=img_path)
  84. vis_save_dir = osp.join(output, 'demo_img')
  85. if not osp.exists(vis_save_dir):
  86. os.makedirs(vis_save_dir)
  87. if len(sample_paths[tag]) < sample_num:
  88. img = Image.open(img_path)
  89. img = ImageOps.exif_transpose(img)
  90. vis_im = draw_label(img, label, label_map_dict)
  91. vis_path = osp.join(vis_save_dir,
  92. osp.basename(file_name))
  93. vis_im.save(vis_path)
  94. sample_path = osp.join(
  95. 'check_dataset', os.path.relpath(vis_path, output))
  96. sample_paths[tag].append(sample_path)
  97. try:
  98. label = int(label)
  99. except (ValueError, TypeError) as e:
  100. raise CheckFailedError(
  101. f"Ensure that the second number in each line in {label_file} should be int."
  102. ) from e
  103. num_classes = max(labels) + 1
  104. attrs = {}
  105. attrs['label_file'] = osp.relpath(label_file, output)
  106. attrs['num_classes'] = num_classes
  107. attrs['train_samples'] = sample_cnts['train']
  108. attrs['train_sample_paths'] = sample_paths['train']
  109. attrs['val_samples'] = sample_cnts['val']
  110. attrs['val_sample_paths'] = sample_paths['val']
  111. return attrs