dataset.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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 copy
  16. import numpy as np
  17. try:
  18. from collections.abc import Sequence
  19. except Exception:
  20. from collections import Sequence
  21. from paddle.io import Dataset
  22. from ppdet.core.workspace import register, serializable
  23. from ppdet.utils.download import get_dataset_path
  24. from ppdet.data import source
  25. from ppdet.utils.logger import setup_logger
  26. logger = setup_logger(__name__)
  27. @serializable
  28. class DetDataset(Dataset):
  29. """
  30. Load detection dataset.
  31. Args:
  32. dataset_dir (str): root directory for dataset.
  33. image_dir (str): directory for images.
  34. anno_path (str): annotation file path.
  35. data_fields (list): key name of data dictionary, at least have 'image'.
  36. sample_num (int): number of samples to load, -1 means all.
  37. use_default_label (bool): whether to load default label list.
  38. repeat (int): repeat times for dataset, use in benchmark.
  39. """
  40. def __init__(self,
  41. dataset_dir=None,
  42. image_dir=None,
  43. anno_path=None,
  44. data_fields=['image'],
  45. sample_num=-1,
  46. use_default_label=None,
  47. repeat=1,
  48. **kwargs):
  49. super(DetDataset, self).__init__()
  50. self.dataset_dir = dataset_dir if dataset_dir is not None else ''
  51. self.anno_path = anno_path
  52. self.image_dir = image_dir if image_dir is not None else ''
  53. self.data_fields = data_fields
  54. self.sample_num = sample_num
  55. self.use_default_label = use_default_label
  56. self.repeat = repeat
  57. self._epoch = 0
  58. self._curr_iter = 0
  59. def __len__(self, ):
  60. return len(self.roidbs) * self.repeat
  61. def __call__(self, *args, **kwargs):
  62. return self
  63. def __getitem__(self, idx):
  64. n = len(self.roidbs)
  65. if self.repeat > 1:
  66. idx %= n
  67. # data batch
  68. roidb = copy.deepcopy(self.roidbs[idx])
  69. if self.mixup_epoch == 0 or self._epoch < self.mixup_epoch:
  70. idx = np.random.randint(n)
  71. roidb = [roidb, copy.deepcopy(self.roidbs[idx])]
  72. elif self.cutmix_epoch == 0 or self._epoch < self.cutmix_epoch:
  73. idx = np.random.randint(n)
  74. roidb = [roidb, copy.deepcopy(self.roidbs[idx])]
  75. elif self.mosaic_epoch == 0 or self._epoch < self.mosaic_epoch:
  76. roidb = [roidb, ] + [
  77. copy.deepcopy(self.roidbs[np.random.randint(n)])
  78. for _ in range(4)
  79. ]
  80. elif self.pre_img_epoch == 0 or self._epoch < self.pre_img_epoch:
  81. # Add previous image as input, only used in CenterTrack
  82. idx_pre_img = idx - 1
  83. if idx_pre_img < 0:
  84. idx_pre_img = idx + 1
  85. roidb = [roidb, ] + [copy.deepcopy(self.roidbs[idx_pre_img])]
  86. if isinstance(roidb, Sequence):
  87. for r in roidb:
  88. r['curr_iter'] = self._curr_iter
  89. else:
  90. roidb['curr_iter'] = self._curr_iter
  91. self._curr_iter += 1
  92. return self.transform(roidb)
  93. def check_or_download_dataset(self):
  94. self.dataset_dir = get_dataset_path(self.dataset_dir, self.anno_path,
  95. self.image_dir)
  96. def set_kwargs(self, **kwargs):
  97. self.mixup_epoch = kwargs.get('mixup_epoch', -1)
  98. self.cutmix_epoch = kwargs.get('cutmix_epoch', -1)
  99. self.mosaic_epoch = kwargs.get('mosaic_epoch', -1)
  100. self.pre_img_epoch = kwargs.get('pre_img_epoch', -1)
  101. def set_transform(self, transform):
  102. self.transform = transform
  103. def set_epoch(self, epoch_id):
  104. self._epoch = epoch_id
  105. def parse_dataset(self, ):
  106. raise NotImplementedError(
  107. "Need to implement parse_dataset method of Dataset")
  108. def get_anno(self):
  109. if self.anno_path is None:
  110. return
  111. return os.path.join(self.dataset_dir, self.anno_path)
  112. def _is_valid_file(f, extensions=('.jpg', '.jpeg', '.png', '.bmp')):
  113. return f.lower().endswith(extensions)
  114. def _make_dataset(dir):
  115. dir = os.path.expanduser(dir)
  116. if not os.path.isdir(dir):
  117. raise ('{} should be a dir'.format(dir))
  118. images = []
  119. for root, _, fnames in sorted(os.walk(dir, followlinks=True)):
  120. for fname in sorted(fnames):
  121. path = os.path.join(root, fname)
  122. if _is_valid_file(path):
  123. images.append(path)
  124. return images
  125. @register
  126. @serializable
  127. class ImageFolder(DetDataset):
  128. def __init__(self,
  129. dataset_dir=None,
  130. image_dir=None,
  131. anno_path=None,
  132. sample_num=-1,
  133. use_default_label=None,
  134. **kwargs):
  135. super(ImageFolder, self).__init__(
  136. dataset_dir,
  137. image_dir,
  138. anno_path,
  139. sample_num=sample_num,
  140. use_default_label=use_default_label)
  141. self._imid2path = {}
  142. self.roidbs = None
  143. self.sample_num = sample_num
  144. def check_or_download_dataset(self):
  145. return
  146. def get_anno(self):
  147. if self.anno_path is None:
  148. return
  149. if self.dataset_dir:
  150. return os.path.join(self.dataset_dir, self.anno_path)
  151. else:
  152. return self.anno_path
  153. def parse_dataset(self, ):
  154. if not self.roidbs:
  155. self.roidbs = self._load_images()
  156. def _parse(self):
  157. image_dir = self.image_dir
  158. if not isinstance(image_dir, Sequence):
  159. image_dir = [image_dir]
  160. images = []
  161. for im_dir in image_dir:
  162. if os.path.isdir(im_dir):
  163. im_dir = os.path.join(self.dataset_dir, im_dir)
  164. images.extend(_make_dataset(im_dir))
  165. elif os.path.isfile(im_dir) and _is_valid_file(im_dir):
  166. images.append(im_dir)
  167. return images
  168. def _load_images(self):
  169. images = self._parse()
  170. ct = 0
  171. records = []
  172. for image in images:
  173. assert image != '' and os.path.isfile(image), \
  174. "Image {} not found".format(image)
  175. if self.sample_num > 0 and ct >= self.sample_num:
  176. break
  177. rec = {'im_id': np.array([ct]), 'im_file': image}
  178. self._imid2path[ct] = image
  179. ct += 1
  180. records.append(rec)
  181. assert len(records) > 0, "No image file found"
  182. return records
  183. def get_imid2path(self):
  184. return self._imid2path
  185. def set_images(self, images):
  186. self.image_dir = images
  187. self.roidbs = self._load_images()
  188. def set_slice_images(self,
  189. images,
  190. slice_size=[640, 640],
  191. overlap_ratio=[0.25, 0.25]):
  192. self.image_dir = images
  193. ori_records = self._load_images()
  194. try:
  195. import sahi
  196. from sahi.slicing import slice_image
  197. except Exception as e:
  198. logger.error(
  199. 'sahi not found, plaese install sahi. '
  200. 'for example: `pip install sahi`, see https://github.com/obss/sahi.'
  201. )
  202. raise e
  203. sub_img_ids = 0
  204. ct = 0
  205. ct_sub = 0
  206. records = []
  207. for i, ori_rec in enumerate(ori_records):
  208. im_path = ori_rec['im_file']
  209. slice_image_result = sahi.slicing.slice_image(
  210. image=im_path,
  211. slice_height=slice_size[0],
  212. slice_width=slice_size[1],
  213. overlap_height_ratio=overlap_ratio[0],
  214. overlap_width_ratio=overlap_ratio[1])
  215. sub_img_num = len(slice_image_result)
  216. for _ind in range(sub_img_num):
  217. im = slice_image_result.images[_ind]
  218. rec = {
  219. 'image': im,
  220. 'im_id': np.array([sub_img_ids + _ind]),
  221. 'h': im.shape[0],
  222. 'w': im.shape[1],
  223. 'ori_im_id': np.array([ori_rec['im_id'][0]]),
  224. 'st_pix': np.array(
  225. slice_image_result.starting_pixels[_ind],
  226. dtype=np.float32),
  227. 'is_last': 1 if _ind == sub_img_num - 1 else 0,
  228. } if 'image' in self.data_fields else {}
  229. records.append(rec)
  230. ct_sub += sub_img_num
  231. ct += 1
  232. logger.info('{} samples and slice to {} sub_samples.'.format(ct,
  233. ct_sub))
  234. self.roidbs = records
  235. def get_label_list(self):
  236. # Only VOC dataset needs label list in ImageFold
  237. return self.anno_path
  238. @register
  239. class CommonDataset(object):
  240. def __init__(self, **dataset_args):
  241. super(CommonDataset, self).__init__()
  242. dataset_args = copy.deepcopy(dataset_args)
  243. type = dataset_args.pop("name")
  244. self.dataset = getattr(source, type)(**dataset_args)
  245. def __call__(self):
  246. return self.dataset
  247. @register
  248. class TrainDataset(CommonDataset):
  249. pass
  250. @register
  251. class EvalMOTDataset(CommonDataset):
  252. pass
  253. @register
  254. class TestMOTDataset(CommonDataset):
  255. pass
  256. @register
  257. class EvalDataset(CommonDataset):
  258. pass
  259. @register
  260. class TestDataset(CommonDataset):
  261. pass