dataset.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  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 ppdet.core.workspace import register, serializable
  21. from ppdet.utils.download import get_dataset_path
  22. @serializable
  23. class DataSet(object):
  24. """
  25. Dataset, e.g., coco, pascal voc
  26. Args:
  27. annotation (str): annotation file path
  28. image_dir (str): directory where image files are stored
  29. shuffle (bool): shuffle samples
  30. """
  31. def __init__(self,
  32. dataset_dir=None,
  33. image_dir=None,
  34. anno_path=None,
  35. sample_num=-1,
  36. with_background=True,
  37. use_default_label=False,
  38. **kwargs):
  39. super(DataSet, self).__init__()
  40. self.anno_path = anno_path
  41. self.image_dir = image_dir if image_dir is not None else ''
  42. self.dataset_dir = dataset_dir if dataset_dir is not None else ''
  43. self.sample_num = sample_num
  44. self.with_background = with_background
  45. self.use_default_label = use_default_label
  46. self.cname2cid = None
  47. self._imid2path = None
  48. def load_roidb_and_cname2cid(self):
  49. """load dataset"""
  50. raise NotImplementedError('%s.load_roidb_and_cname2cid not available' %
  51. (self.__class__.__name__))
  52. def get_roidb(self):
  53. if not self.roidbs:
  54. data_dir = get_dataset_path(self.dataset_dir, self.anno_path,
  55. self.image_dir)
  56. if data_dir:
  57. self.dataset_dir = data_dir
  58. self.load_roidb_and_cname2cid()
  59. return self.roidbs
  60. def get_cname2cid(self):
  61. if not self.cname2cid:
  62. self.load_roidb_and_cname2cid()
  63. return self.cname2cid
  64. def get_anno(self):
  65. if self.anno_path is None:
  66. return
  67. return os.path.join(self.dataset_dir, self.anno_path)
  68. def get_imid2path(self):
  69. return self._imid2path
  70. def _is_valid_file(f, extensions=('.jpg', '.jpeg', '.png', '.bmp')):
  71. return f.lower().endswith(extensions)
  72. def _make_dataset(data_dir):
  73. data_dir = os.path.expanduser(data_dir)
  74. if not os.path.isdir(data_dir):
  75. raise ('{} should be a dir'.format(data_dir))
  76. images = []
  77. for root, _, fnames in sorted(os.walk(data_dir, followlinks=True)):
  78. for fname in sorted(fnames):
  79. file_path = os.path.join(root, fname)
  80. if _is_valid_file(file_path):
  81. images.append(file_path)
  82. return images
  83. @register
  84. @serializable
  85. class ImageFolder(DataSet):
  86. """
  87. Args:
  88. dataset_dir (str): root directory for dataset.
  89. image_dir(list|str): list of image folders or list of image files
  90. anno_path (str): annotation file path.
  91. samples (int): number of samples to load, -1 means all
  92. """
  93. def __init__(self,
  94. dataset_dir=None,
  95. image_dir=None,
  96. anno_path=None,
  97. sample_num=-1,
  98. with_background=True,
  99. use_default_label=False,
  100. **kwargs):
  101. super(ImageFolder, self).__init__(dataset_dir, image_dir, anno_path,
  102. sample_num, with_background,
  103. use_default_label)
  104. self.roidbs = None
  105. self._imid2path = {}
  106. def get_roidb(self):
  107. if not self.roidbs:
  108. self.roidbs = self._load_images()
  109. return self.roidbs
  110. def set_images(self, images):
  111. self.image_dir = images
  112. self.roidbs = self._load_images()
  113. def _parse(self):
  114. image_dir = self.image_dir
  115. if not isinstance(image_dir, Sequence):
  116. image_dir = [image_dir]
  117. images = []
  118. for im_dir in image_dir:
  119. if os.path.isdir(im_dir):
  120. im_dir = os.path.join(self.dataset_dir, im_dir)
  121. images.extend(_make_dataset(im_dir))
  122. elif os.path.isfile(im_dir) and _is_valid_file(im_dir):
  123. images.append(im_dir)
  124. return images
  125. def _load_images(self):
  126. images = self._parse()
  127. ct = 0
  128. records = []
  129. for image in images:
  130. assert image != '' and os.path.isfile(image), \
  131. "Image {} not found".format(image)
  132. if self.sample_num > 0 and ct >= self.sample_num:
  133. break
  134. rec = {'im_id': np.array([ct]), 'im_file': image}
  135. self._imid2path[ct] = image
  136. ct += 1
  137. records.append(rec)
  138. assert len(records) > 0, "No image file found"
  139. return records