dataset.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. # Copyright (c) 2019 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 numpy as np
  16. try:
  17. from collections.abc import Sequence
  18. except Exception:
  19. from collections import Sequence
  20. from paddle.io import Dataset
  21. from ppdet.core.workspace import register, serializable
  22. from ppdet.utils.download import get_dataset_path
  23. import copy
  24. from ppdet.data import source
  25. @serializable
  26. class DetDataset(Dataset):
  27. """
  28. Load detection dataset.
  29. Args:
  30. dataset_dir (str): root directory for dataset.
  31. image_dir (str): directory for images.
  32. anno_path (str): annotation file path.
  33. data_fields (list): key name of data dictionary, at least have 'image'.
  34. sample_num (int): number of samples to load, -1 means all.
  35. use_default_label (bool): whether to load default label list.
  36. """
  37. def __init__(self,
  38. dataset_dir=None,
  39. image_dir=None,
  40. anno_path=None,
  41. data_fields=['image'],
  42. sample_num=-1,
  43. use_default_label=None,
  44. **kwargs):
  45. super(DetDataset, self).__init__()
  46. self.dataset_dir = dataset_dir if dataset_dir is not None else ''
  47. self.anno_path = anno_path
  48. self.image_dir = image_dir if image_dir is not None else ''
  49. self.data_fields = data_fields
  50. self.sample_num = sample_num
  51. self.use_default_label = use_default_label
  52. self._epoch = 0
  53. self._curr_iter = 0
  54. def __len__(self, ):
  55. return len(self.roidbs)
  56. def __call__(self, *args, **kwargs):
  57. return self
  58. def __getitem__(self, idx):
  59. # data batch
  60. roidb = copy.deepcopy(self.roidbs[idx])
  61. if self.mixup_epoch == 0 or self._epoch < self.mixup_epoch:
  62. n = len(self.roidbs)
  63. idx = np.random.randint(n)
  64. roidb = [roidb, copy.deepcopy(self.roidbs[idx])]
  65. elif self.cutmix_epoch == 0 or self._epoch < self.cutmix_epoch:
  66. n = len(self.roidbs)
  67. idx = np.random.randint(n)
  68. roidb = [roidb, copy.deepcopy(self.roidbs[idx])]
  69. elif self.mosaic_epoch == 0 or self._epoch < self.mosaic_epoch:
  70. n = len(self.roidbs)
  71. roidb = [roidb, ] + [
  72. copy.deepcopy(self.roidbs[np.random.randint(n)])
  73. for _ in range(4)
  74. ]
  75. if isinstance(roidb, Sequence):
  76. for r in roidb:
  77. r['curr_iter'] = self._curr_iter
  78. else:
  79. roidb['curr_iter'] = self._curr_iter
  80. self._curr_iter += 1
  81. return self.transform(roidb)
  82. def check_or_download_dataset(self):
  83. self.dataset_dir = get_dataset_path(self.dataset_dir, self.anno_path,
  84. self.image_dir)
  85. def set_kwargs(self, **kwargs):
  86. self.mixup_epoch = kwargs.get('mixup_epoch', -1)
  87. self.cutmix_epoch = kwargs.get('cutmix_epoch', -1)
  88. self.mosaic_epoch = kwargs.get('mosaic_epoch', -1)
  89. def set_transform(self, transform):
  90. self.transform = transform
  91. def set_epoch(self, epoch_id):
  92. self._epoch = epoch_id
  93. def parse_dataset(self, ):
  94. raise NotImplementedError(
  95. "Need to implement parse_dataset method of Dataset")
  96. def get_anno(self):
  97. if self.anno_path is None:
  98. return
  99. return os.path.join(self.dataset_dir, self.anno_path)
  100. def _is_valid_file(f, extensions=('.jpg', '.jpeg', '.png', '.bmp')):
  101. return f.lower().endswith(extensions)
  102. def _make_dataset(dir):
  103. dir = os.path.expanduser(dir)
  104. if not os.path.isdir(dir):
  105. raise ('{} should be a dir'.format(dir))
  106. images = []
  107. for root, _, fnames in sorted(os.walk(dir, followlinks=True)):
  108. for fname in sorted(fnames):
  109. path = os.path.join(root, fname)
  110. if _is_valid_file(path):
  111. images.append(path)
  112. return images
  113. @register
  114. @serializable
  115. class ImageFolder(DetDataset):
  116. def __init__(self,
  117. dataset_dir=None,
  118. image_dir=None,
  119. anno_path=None,
  120. sample_num=-1,
  121. use_default_label=None,
  122. **kwargs):
  123. super(ImageFolder, self).__init__(
  124. dataset_dir,
  125. image_dir,
  126. anno_path,
  127. sample_num=sample_num,
  128. use_default_label=use_default_label)
  129. self._imid2path = {}
  130. self.roidbs = None
  131. self.sample_num = sample_num
  132. def check_or_download_dataset(self):
  133. return
  134. def get_anno(self):
  135. if self.anno_path is None:
  136. return
  137. if self.dataset_dir:
  138. return os.path.join(self.dataset_dir, self.anno_path)
  139. else:
  140. return self.anno_path
  141. def parse_dataset(self, ):
  142. if not self.roidbs:
  143. self.roidbs = self._load_images()
  144. def _parse(self):
  145. image_dir = self.image_dir
  146. if not isinstance(image_dir, Sequence):
  147. image_dir = [image_dir]
  148. images = []
  149. for im_dir in image_dir:
  150. if os.path.isdir(im_dir):
  151. im_dir = os.path.join(self.dataset_dir, im_dir)
  152. images.extend(_make_dataset(im_dir))
  153. elif os.path.isfile(im_dir) and _is_valid_file(im_dir):
  154. images.append(im_dir)
  155. return images
  156. def _load_images(self):
  157. images = self._parse()
  158. ct = 0
  159. records = []
  160. for image in images:
  161. assert image != '' and os.path.isfile(image), \
  162. "Image {} not found".format(image)
  163. if self.sample_num > 0 and ct >= self.sample_num:
  164. break
  165. rec = {'im_id': np.array([ct]), 'im_file': image}
  166. self._imid2path[ct] = image
  167. ct += 1
  168. records.append(rec)
  169. assert len(records) > 0, "No image file found"
  170. return records
  171. def get_imid2path(self):
  172. return self._imid2path
  173. def set_images(self, images):
  174. self.image_dir = images
  175. self.roidbs = self._load_images()
  176. @register
  177. class CommonDataset(object):
  178. def __init__(self, **dataset_args):
  179. super(CommonDataset, self).__init__()
  180. dataset_args = copy.deepcopy(dataset_args)
  181. type = dataset_args.pop("name")
  182. self.dataset = getattr(source, type)(**dataset_args)
  183. def __call__(self):
  184. return self.dataset
  185. @register
  186. class TrainDataset(CommonDataset):
  187. pass
  188. @register
  189. class EvalMOTDataset(CommonDataset):
  190. pass
  191. @register
  192. class TestMOTDataset(CommonDataset):
  193. pass
  194. @register
  195. class EvalDataset(CommonDataset):
  196. pass
  197. @register
  198. class TestDataset(CommonDataset):
  199. pass