imagenet.py 3.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. # Copyright (c) 2021 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.path as osp
  15. import copy
  16. import numpy as np
  17. from paddle.io import Dataset
  18. from paddlex.utils import logging, get_num_workers, get_encoding, path_normalization, is_pic
  19. class ImageNet(Dataset):
  20. """读取ImageNet格式的分类数据集,并对样本进行相应的处理。
  21. Args:
  22. data_dir (str): 数据集所在的目录路径。
  23. file_list (str): 描述数据集图片文件和类别id的文件路径(文本内每行路径为相对data_dir的相对路)。
  24. label_list (str): 描述数据集包含的类别信息文件路径。
  25. transforms (paddlex.transforms): 数据集中每个样本的预处理/增强算子。
  26. num_workers (int|str): 数据集中样本在预处理过程中的线程或进程数。默认为'auto'。当设为'auto'时,根据
  27. 系统的实际CPU核数设置`num_workers`: 如果CPU核数的一半大于8,则`num_workers`为8,否则为CPU核
  28. 数的一半。
  29. shuffle (bool): 是否需要对数据集中样本打乱顺序。默认为False。
  30. """
  31. def __init__(self,
  32. data_dir,
  33. file_list,
  34. label_list,
  35. transforms=None,
  36. num_workers='auto',
  37. shuffle=False):
  38. super(ImageNet, self).__init__()
  39. self.transforms = copy.deepcopy(transforms)
  40. # TODO batch padding
  41. self.batch_transforms = None
  42. self.num_workers = get_num_workers(num_workers)
  43. self.shuffle = shuffle
  44. self.file_list = list()
  45. self.labels = list()
  46. with open(label_list, encoding=get_encoding(label_list)) as f:
  47. for line in f:
  48. item = line.strip()
  49. self.labels.append(item)
  50. logging.info("Starting to read file list from dataset...")
  51. with open(file_list, encoding=get_encoding(file_list)) as f:
  52. for line in f:
  53. items = line.strip().split()
  54. if len(items) > 2:
  55. raise Exception(
  56. "A space is defined as the delimiter to separate the image and label path, " \
  57. "so the space cannot be in the image or label path, but the line[{}] of " \
  58. " file_list[{}] has a space in the image or label path.".format(line, file_list))
  59. items[0] = path_normalization(items[0])
  60. if not is_pic(items[0]):
  61. continue
  62. full_path = osp.join(data_dir, items[0])
  63. if not osp.exists(full_path):
  64. raise IOError('The image file {} does not exist!'.format(
  65. full_path))
  66. self.file_list.append({
  67. 'image': full_path,
  68. 'label': np.asarray(
  69. items[1], dtype=np.int64)
  70. })
  71. self.num_samples = len(self.file_list)
  72. logging.info("{} samples in file {}".format(
  73. len(self.file_list), file_list))
  74. def __getitem__(self, idx):
  75. sample = copy.deepcopy(self.file_list[idx])
  76. outputs = self.transforms(sample)
  77. return outputs
  78. def __len__(self):
  79. return len(self.file_list)