det_dataset.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. # copyright (c) 2021 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, replace_ext, get_encoding, check_list_txt
  17. from .datasetbase import DatasetBase
  18. import xml.etree.ElementTree as ET
  19. class DetDataset(DatasetBase):
  20. def __init__(self, dataset_id, path):
  21. super().__init__(dataset_id, path)
  22. def check_dataset(self, source_path):
  23. if not osp.isdir(osp.join(source_path, 'Annotations')):
  24. raise ValueError("标注文件应该放在{}目录下".format(
  25. osp.join(source_path, 'Annotations')))
  26. if not osp.isdir(osp.join(source_path, 'JPEGImages')):
  27. raise ValueError("图片文件应该放在{}目录下".format(
  28. osp.join(source_path, 'JPEGImages')))
  29. self.all_files = list_files(source_path)
  30. # 对检测数据集进行统计分析
  31. self.file_info = dict()
  32. self.label_info = dict()
  33. if osp.exists(osp.join(source_path, 'train_list.txt')):
  34. return self.check_splited_dataset(source_path)
  35. for f in self.all_files:
  36. if not is_pic(f):
  37. continue
  38. items = osp.split(f)
  39. if len(items) == 2 and items[0] == "JPEGImages":
  40. anno_name = replace_ext(items[1], "xml")
  41. full_anno_path = osp.join(
  42. (osp.join(source_path, 'Annotations')), anno_name)
  43. if osp.exists(full_anno_path):
  44. self.file_info[f] = osp.join('Annotations', anno_name)
  45. # 解析XML文件,获取类别信息
  46. try:
  47. tree = ET.parse(full_anno_path)
  48. except:
  49. raise Exception("文件{}不是一个良构的xml文件".format(anno_name))
  50. objs = tree.findall('object')
  51. for i, obj in enumerate(objs):
  52. cname = obj.find('name').text
  53. if cname not in self.label_info:
  54. self.label_info[cname] = list()
  55. if f not in self.label_info[cname]:
  56. self.label_info[cname].append(f)
  57. self.labels = sorted(self.label_info.keys())
  58. for label in self.labels:
  59. self.class_train_file_list[label] = list()
  60. self.class_val_file_list[label] = list()
  61. self.class_test_file_list[label] = list()
  62. # 将数据集分析信息dump到本地
  63. self.dump_statis_info()
  64. def check_splited_dataset(self, source_path):
  65. labels_txt = osp.join(source_path, "labels.txt")
  66. train_list_txt = osp.join(source_path, "train_list.txt")
  67. val_list_txt = osp.join(source_path, "val_list.txt")
  68. test_list_txt = osp.join(source_path, "test_list.txt")
  69. for txt_file in [labels_txt, train_list_txt, val_list_txt]:
  70. if not osp.exists(txt_file):
  71. raise Exception(
  72. "已切分的数据集下应该包含labels.txt, train_list.txt, val_list.txt文件")
  73. check_list_txt([train_list_txt, val_list_txt, test_list_txt])
  74. self.labels = open(
  75. labels_txt, 'r',
  76. encoding=get_encoding(labels_txt)).read().strip().split('\n')
  77. for txt_file in [train_list_txt, val_list_txt, test_list_txt]:
  78. if not osp.exists(txt_file):
  79. continue
  80. with open(txt_file, "r") as f:
  81. for line in f:
  82. items = line.strip().split()
  83. img_file, xml_file = [items[0], items[1]]
  84. if not osp.isfile(osp.join(source_path, xml_file)):
  85. raise ValueError("数据目录{}中不存在标注文件{}".format(
  86. osp.split(txt_file)[-1], xml_file))
  87. if not osp.isfile(osp.join(source_path, img_file)):
  88. raise ValueError("数据目录{}中不存在图片文件{}".format(
  89. osp.split(txt_file)[-1], img_file))
  90. if not xml_file.split('.')[-1] == 'xml':
  91. raise ValueError("标注文件{}不是xml文件".format(xml_file))
  92. img_file_name = osp.split(img_file)[-1]
  93. if not is_pic(img_file_name) or img_file_name.startswith(
  94. '.'):
  95. raise ValueError("文件{}不是图片格式".format(img_file))
  96. self.file_info[img_file] = xml_file
  97. if txt_file == train_list_txt:
  98. self.train_files.append(img_file)
  99. elif txt_file == val_list_txt:
  100. self.val_files.append(img_file)
  101. elif txt_file == test_list_txt:
  102. self.test_files.append(img_file)
  103. try:
  104. tree = ET.parse(osp.join(source_path, xml_file))
  105. except:
  106. raise Exception("文件{}不是一个良构的xml文件".format(xml_file))
  107. objs = tree.findall('object')
  108. for i, obj in enumerate(objs):
  109. cname = obj.find('name').text
  110. if cname in self.labels:
  111. if cname not in self.label_info:
  112. self.label_info[cname] = list()
  113. if img_file not in self.label_info[cname]:
  114. self.label_info[cname].append(img_file)
  115. if txt_file == train_list_txt:
  116. if cname in self.class_train_file_list:
  117. self.class_train_file_list[
  118. cname].append(img_file)
  119. else:
  120. self.class_train_file_list[
  121. cname] = list()
  122. self.class_train_file_list[
  123. cname].append(img_file)
  124. elif txt_file == val_list_txt:
  125. if cname in self.class_val_file_list:
  126. self.class_val_file_list[cname].append(
  127. img_file)
  128. else:
  129. self.class_val_file_list[cname] = list(
  130. )
  131. self.class_val_file_list[cname].append(
  132. img_file)
  133. elif txt_file == test_list_txt:
  134. if cname in self.class_test_file_list:
  135. self.class_test_file_list[
  136. cname].append(img_file)
  137. else:
  138. self.class_test_file_list[
  139. cname] = list()
  140. self.class_test_file_list[
  141. cname].append(img_file)
  142. else:
  143. raise Exception("文件{}与labels.txt文件信息不对应".format(
  144. xml_file))
  145. # 将数据集分析信息dump到本地
  146. self.dump_statis_info()
  147. def split(self, val_split, test_split):
  148. super().split(val_split, test_split)
  149. with open(
  150. osp.join(self.path, 'train_list.txt'), mode='w',
  151. encoding='utf-8') as f:
  152. for x in self.train_files:
  153. label = self.file_info[x]
  154. f.write('{} {}\n'.format(x, label))
  155. with open(
  156. osp.join(self.path, 'val_list.txt'), mode='w',
  157. encoding='utf-8') as f:
  158. for x in self.val_files:
  159. label = self.file_info[x]
  160. f.write('{} {}\n'.format(x, label))
  161. with open(
  162. osp.join(self.path, 'test_list.txt'), mode='w',
  163. encoding='utf-8') as f:
  164. for x in self.test_files:
  165. label = self.file_info[x]
  166. f.write('{} {}\n'.format(x, label))
  167. with open(
  168. osp.join(self.path, 'labels.txt'), mode='w',
  169. encoding='utf-8') as f:
  170. for l in self.labels:
  171. f.write('{}\n'.format(l))
  172. self.dump_statis_info()