pgnet_dataset.py 4.1 KB

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