pgnet_dataset.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  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 (
  35. len(ratio_list) == data_source_num
  36. ), "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 indexes 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, round(len(lines) * ratio_list[idx]))
  61. data_lines.extend(lines)
  62. return data_lines
  63. def __getitem__(self, idx):
  64. file_idx = self.data_idx_order_list[idx]
  65. data_line = self.data_lines[file_idx]
  66. img_id = 0
  67. try:
  68. data_line = data_line.decode("utf-8")
  69. substr = data_line.strip("\n").split(self.delimiter)
  70. file_name = substr[0]
  71. label = substr[1]
  72. img_path = os.path.join(self.data_dir, file_name)
  73. if self.mode.lower() == "eval":
  74. try:
  75. img_id = int(data_line.split(".")[0][7:])
  76. except:
  77. img_id = 0
  78. data = {"img_path": img_path, "label": label, "img_id": img_id}
  79. if not os.path.exists(img_path):
  80. raise Exception("{} does not exist!".format(img_path))
  81. with open(data["img_path"], "rb") as f:
  82. img = f.read()
  83. data["image"] = img
  84. outs = transform(data, self.ops)
  85. except Exception as e:
  86. self.logger.error(
  87. "When parsing line {}, error happened with msg: {}".format(
  88. self.data_idx_order_list[idx], e
  89. )
  90. )
  91. outs = None
  92. if outs is None:
  93. return self.__getitem__(np.random.randint(self.__len__()))
  94. return outs
  95. def __len__(self):
  96. return len(self.data_idx_order_list)