cls_dataset.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. # copyright (c) 2020 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.path as osp
  15. from ..utils import list_files
  16. from .utils import is_pic, get_encoding, check_list_txt
  17. from .datasetbase import DatasetBase
  18. class ClsDataset(DatasetBase):
  19. def __init__(self, dataset_id, path):
  20. super().__init__(dataset_id, path)
  21. def check_dataset(self, source_path):
  22. self.all_files = list_files(source_path)
  23. # 对分类数据集进行统计分析
  24. self.file_info = dict()
  25. self.label_info = dict()
  26. # 校验已切分的数据集
  27. if osp.exists(osp.join(source_path, 'train_list.txt')):
  28. return self.check_splited_dataset(source_path)
  29. for f in self.all_files:
  30. if not is_pic(f):
  31. continue
  32. items = osp.split(f)
  33. if len(items) == 2:
  34. if " " in items[0]:
  35. raise ValueError("类别-{}名称有误,分类数据集中类别名称不应包含空格".format(items[
  36. 0]))
  37. if items[0] not in self.label_info:
  38. self.label_info[items[0]] = list()
  39. self.label_info[items[0]].append(f)
  40. self.file_info[f] = items[0]
  41. if len(self.label_info) < 2:
  42. raise ValueError("分类数据集中至少需要包含两种图像类别")
  43. self.labels = sorted(self.label_info.keys())
  44. for label in self.labels:
  45. self.class_train_file_list[label] = list()
  46. self.class_val_file_list[label] = list()
  47. self.class_test_file_list[label] = list()
  48. # 将数据集分析信息dump到本地
  49. self.dump_statis_info()
  50. def check_splited_dataset(self, source_path):
  51. labels_txt = osp.join(source_path, "labels.txt")
  52. train_list_txt = osp.join(source_path, "train_list.txt")
  53. val_list_txt = osp.join(source_path, "val_list.txt")
  54. test_list_txt = osp.join(source_path, "test_list.txt")
  55. for txt_file in [labels_txt, train_list_txt, val_list_txt]:
  56. if not osp.exists(txt_file):
  57. raise Exception(
  58. "已切分的数据集下应该包含labels.txt, train_list.txt, val_list.txt文件")
  59. check_list_txt([train_list_txt, val_list_txt, test_list_txt])
  60. self.labels = open(
  61. labels_txt, 'r',
  62. encoding=get_encoding(labels_txt)).read().strip().split('\n')
  63. for txt_file in [train_list_txt, val_list_txt, test_list_txt]:
  64. if not osp.exists(txt_file):
  65. continue
  66. with open(txt_file, "r") as f:
  67. for line in f:
  68. items = line.strip().split()
  69. if not osp.exists(osp.join(source_path, items[0])):
  70. raise Exception("数据目录{}中不存在图片文件{}".format(
  71. osp.split(txt_file)[-1], items[0]))
  72. dir_name = osp.split(osp.split(items[0])[0])[-1]
  73. if dir_name != self.labels[int(items[1])]:
  74. raise Exception("labels.txt中label顺序不准确")
  75. img_file = osp.split(items[0])[-1]
  76. if not is_pic(img_file) or img_file.startswith('.'):
  77. raise ValueError("文件{}不是图片格式".format(img_file))
  78. self.file_info[items[0]] = self.labels[int(items[1])]
  79. if txt_file == train_list_txt:
  80. self.train_files.append(items[0])
  81. if self.labels[int(items[
  82. 1])] in self.class_train_file_list:
  83. self.class_train_file_list[self.labels[int(items[
  84. 1])]].append(items[0])
  85. else:
  86. self.class_train_file_list[self.labels[int(items[
  87. 1])]] = list()
  88. self.class_train_file_list[self.labels[int(items[
  89. 1])]].append(items[0])
  90. elif txt_file == val_list_txt:
  91. self.val_files.append(items[0])
  92. if self.labels[int(items[
  93. 1])] in self.class_val_file_list:
  94. self.class_val_file_list[self.labels[int(items[
  95. 1])]].append(items[0])
  96. else:
  97. self.class_val_file_list[self.labels[int(items[
  98. 1])]] = list()
  99. self.class_val_file_list[self.labels[int(items[
  100. 1])]].append(items[0])
  101. elif txt_file == test_list_txt:
  102. self.test_files.append(items[0])
  103. if self.labels[int(items[
  104. 1])] in self.class_test_file_list:
  105. self.class_test_file_list[self.labels[int(items[
  106. 1])]].append(items[0])
  107. else:
  108. self.class_test_file_list[self.labels[int(items[
  109. 1])]] = list()
  110. self.class_test_file_list[self.labels[int(items[
  111. 1])]].append(items[0])
  112. for img_file, label in self.file_info.items():
  113. if label not in self.label_info:
  114. self.label_info[label] = list()
  115. self.label_info[label].append(img_file)
  116. # 将数据集分析信息dump到本地
  117. self.dump_statis_info()
  118. def split(self, val_split, test_split):
  119. super().split(val_split, test_split)
  120. with open(
  121. osp.join(self.path, 'train_list.txt'), mode='w',
  122. encoding='utf-8') as f:
  123. for x in self.train_files:
  124. label = self.file_info[x]
  125. label_idx = self.labels.index(label)
  126. f.write('{} {}\n'.format(x, label_idx))
  127. with open(
  128. osp.join(self.path, 'val_list.txt'), mode='w',
  129. encoding='utf-8') as f:
  130. for x in self.val_files:
  131. label = self.file_info[x]
  132. label_idx = self.labels.index(label)
  133. f.write('{} {}\n'.format(x, label_idx))
  134. with open(
  135. osp.join(self.path, 'test_list.txt'), mode='w',
  136. encoding='utf-8') as f:
  137. for x in self.test_files:
  138. label = self.file_info[x]
  139. label_idx = self.labels.index(label)
  140. f.write('{} {}\n'.format(x, label_idx))
  141. with open(
  142. osp.join(self.path, 'labels.txt'), mode='w',
  143. encoding='utf-8') as f:
  144. for l in self.labels:
  145. f.write('{}\n'.format(l))
  146. self.dump_statis_info()