check_dataset.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  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.file_interface import custom_open
  20. from .....utils.errors import DatasetFileNotFoundError, CheckFailedError
  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 = 5
  30. sample_cnts = dict()
  31. label_map_dict = dict()
  32. sample_paths = defaultdict(list)
  33. labels = []
  34. image_dir = osp.join(dataset_dir, "rgb-images")
  35. label_dir = osp.join(dataset_dir, "labels")
  36. if not osp.exists(image_dir):
  37. raise DatasetFileNotFoundError(file_path=image_dir)
  38. if not osp.exists(label_dir):
  39. raise DatasetFileNotFoundError(file_path=label_dir)
  40. label_map_file = osp.join(dataset_dir, "label_map.txt")
  41. if not osp.exists(label_map_file):
  42. raise DatasetFileNotFoundError(
  43. file_path=label_map_file,
  44. solution=f"Ensure that `label_map.txt` exist in {dataset_dir}",
  45. )
  46. with open(label_map_file, "r", encoding="utf-8") as f:
  47. all_lines = f.readlines()
  48. for line in all_lines:
  49. substr = line.strip("\n").split(" ", 1)
  50. try:
  51. label_idx = int(substr[1])
  52. labels.append(label_idx)
  53. label_map_dict[label_idx] = str(substr[0])
  54. except:
  55. raise CheckFailedError(
  56. f"Ensure that the second number in each line in {label_map_file} should be int."
  57. )
  58. if min(labels) != 1:
  59. raise CheckFailedError(
  60. f"Ensure that the index starts from 1 in `{label_map_file}`."
  61. )
  62. for tag in tags:
  63. file_list = osp.join(dataset_dir, f"{tag}.txt")
  64. if not osp.exists(file_list):
  65. if tag in ("train", "val"):
  66. # train and val file lists must exist
  67. raise DatasetFileNotFoundError(
  68. file_path=file_list,
  69. solution=f"Ensure that both `train.txt` and `val.txt` exist in {dataset_dir}",
  70. )
  71. else:
  72. # tag == 'test'
  73. continue
  74. else:
  75. with open(file_list, "r", encoding="utf-8") as f:
  76. all_lines = f.readlines()
  77. random.seed(123)
  78. random.shuffle(all_lines)
  79. sample_cnts[tag] = len(all_lines)
  80. for line in all_lines:
  81. substr = line.strip("\n")
  82. label_path = osp.join(dataset_dir, substr)
  83. img_path = (
  84. osp.join(dataset_dir, substr)
  85. .replace("labels", "rgb-images")
  86. .replace("txt", "jpg")
  87. )
  88. if not osp.exists(img_path):
  89. raise DatasetFileNotFoundError(file_path=img_path)
  90. if not osp.exists(label_path):
  91. raise DatasetFileNotFoundError(file_path=label_path)
  92. with custom_open(label_path, "r") as f:
  93. label_lines = f.readlines()
  94. for label_line in label_lines:
  95. label_info = label_line.strip().split(" ")
  96. try:
  97. label = int(label_info[0])
  98. except (ValueError, TypeError) as e:
  99. raise CheckFailedError(
  100. f"Ensure that the first number in each line in {label_info} should be int."
  101. ) from e
  102. if len(label_info) != valid_num_parts:
  103. raise CheckFailedError(
  104. f"Ensure that each line in {label_line} has exactly two numbers."
  105. )
  106. if len(sample_paths[tag]) < sample_num:
  107. sample_path = osp.join(
  108. "check_dataset", os.path.relpath(img_path, output)
  109. )
  110. sample_paths[tag].append(sample_path)
  111. num_classes = max(labels)
  112. attrs = {}
  113. attrs["label_file"] = osp.relpath(label_map_file, output)
  114. attrs["num_classes"] = num_classes
  115. attrs["train_samples"] = sample_cnts["train"]
  116. attrs["train_sample_paths"] = sample_paths["train"]
  117. attrs["val_samples"] = sample_cnts["val"]
  118. attrs["val_sample_paths"] = sample_paths["val"]
  119. return attrs