simple_dataset.py 3.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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 numpy as np
  15. import os
  16. import random
  17. from paddle.io import Dataset
  18. from .imaug import transform, create_operators
  19. class SimpleDataSet(Dataset):
  20. def __init__(self, config, mode, logger, seed=None):
  21. super(SimpleDataSet, self).__init__()
  22. self.logger = logger
  23. global_config = config['Global']
  24. dataset_config = config[mode]['dataset']
  25. loader_config = config[mode]['loader']
  26. self.delimiter = dataset_config.get('delimiter', '\t')
  27. label_file_list = dataset_config.pop('label_file_list')
  28. data_source_num = len(label_file_list)
  29. ratio_list = dataset_config.get("ratio_list", [1.0])
  30. if isinstance(ratio_list, (float, int)):
  31. ratio_list = [float(ratio_list)] * int(data_source_num)
  32. assert len(
  33. ratio_list
  34. ) == data_source_num, "The length of ratio_list should be the same as the file_list."
  35. self.data_dir = dataset_config['data_dir']
  36. self.do_shuffle = loader_config['shuffle']
  37. self.seed = seed
  38. logger.info("Initialize indexs of datasets:%s" % label_file_list)
  39. self.data_lines = self.get_image_info_list(label_file_list, ratio_list)
  40. self.data_idx_order_list = list(range(len(self.data_lines)))
  41. if mode.lower() == "train":
  42. self.shuffle_data_random()
  43. self.ops = create_operators(dataset_config['transforms'], global_config)
  44. def get_image_info_list(self, file_list, ratio_list):
  45. if isinstance(file_list, str):
  46. file_list = [file_list]
  47. data_lines = []
  48. for idx, file in enumerate(file_list):
  49. with open(file, "rb") as f:
  50. lines = f.readlines()
  51. random.seed(self.seed)
  52. lines = random.sample(lines,
  53. round(len(lines) * ratio_list[idx]))
  54. data_lines.extend(lines)
  55. return data_lines
  56. def shuffle_data_random(self):
  57. if self.do_shuffle:
  58. random.seed(self.seed)
  59. random.shuffle(self.data_lines)
  60. return
  61. def __getitem__(self, idx):
  62. file_idx = self.data_idx_order_list[idx]
  63. data_line = self.data_lines[file_idx]
  64. try:
  65. data_line = data_line.decode('utf-8')
  66. substr = data_line.strip("\n").split(self.delimiter)
  67. file_name = substr[0]
  68. label = substr[1]
  69. img_path = os.path.join(self.data_dir, file_name)
  70. data = {'img_path': img_path, 'label': label}
  71. if not os.path.exists(img_path):
  72. raise Exception("{} does not exist!".format(img_path))
  73. with open(data['img_path'], 'rb') as f:
  74. img = f.read()
  75. data['image'] = img
  76. outs = transform(data, self.ops)
  77. except Exception as e:
  78. self.logger.error(
  79. "When parsing line {}, error happened with msg: {}".format(
  80. data_line, e))
  81. outs = None
  82. if outs is None:
  83. return self.__getitem__(np.random.randint(self.__len__()))
  84. return outs
  85. def __len__(self):
  86. return len(self.data_idx_order_list)