imagenet.py 4.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. # copyright (c) 2020 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. from __future__ import absolute_import
  15. import os.path as osp
  16. import random
  17. import copy
  18. import paddlex.utils.logging as logging
  19. from paddlex.utils import path_normalization
  20. from .dataset import Dataset
  21. from .dataset import is_pic
  22. from .dataset import get_encoding
  23. class ImageNet(Dataset):
  24. """读取ImageNet格式的分类数据集,并对样本进行相应的处理。
  25. Args:
  26. data_dir (str): 数据集所在的目录路径。
  27. file_list (str): 描述数据集图片文件和类别id的文件路径(文本内每行路径为相对data_dir的相对路)。
  28. label_list (str): 描述数据集包含的类别信息文件路径。
  29. transforms (paddlex.cls.transforms): 数据集中每个样本的预处理/增强算子。
  30. num_workers (int|str): 数据集中样本在预处理过程中的线程或进程数。默认为'auto'。当设为'auto'时,根据
  31. 系统的实际CPU核数设置`num_workers`: 如果CPU核数的一半大于8,则`num_workers`为8,否则为CPU核
  32. 数的一半。
  33. buffer_size (int): 数据集中样本在预处理过程中队列的缓存长度,以样本数为单位。默认为8。
  34. parallel_method (str): 数据集中样本在预处理过程中并行处理的方式,支持'thread'
  35. 线程和'process'进程两种方式。默认为'process'(Windows和Mac下会强制使用thread,该参数无效)。
  36. shuffle (bool): 是否需要对数据集中样本打乱顺序。默认为False。
  37. """
  38. def __init__(self,
  39. data_dir,
  40. file_list,
  41. label_list,
  42. transforms=None,
  43. num_workers='auto',
  44. buffer_size=8,
  45. parallel_method='process',
  46. shuffle=False):
  47. super(ImageNet, self).__init__(
  48. transforms=transforms,
  49. num_workers=num_workers,
  50. buffer_size=buffer_size,
  51. parallel_method=parallel_method,
  52. shuffle=shuffle)
  53. self.file_list = list()
  54. self.labels = list()
  55. self._epoch = 0
  56. with open(label_list, encoding=get_encoding(label_list)) as f:
  57. for line in f:
  58. item = line.strip()
  59. self.labels.append(item)
  60. logging.info("Starting to read file list from dataset...")
  61. with open(file_list, encoding=get_encoding(file_list)) as f:
  62. for line in f:
  63. items = line.strip().split()
  64. if len(items) > 2:
  65. raise Exception(
  66. "A space is defined as the separator, but it exists in image or label name {}."
  67. .format(line))
  68. items[0] = path_normalization(items[0])
  69. if not is_pic(items[0]):
  70. continue
  71. full_path = osp.join(data_dir, items[0])
  72. if not osp.exists(full_path):
  73. raise IOError('The image file {} is not exist!'.format(
  74. full_path))
  75. self.file_list.append([full_path, int(items[1])])
  76. self.num_samples = len(self.file_list)
  77. logging.info("{} samples in file {}".format(
  78. len(self.file_list), file_list))
  79. def iterator(self):
  80. self._epoch += 1
  81. self._pos = 0
  82. files = copy.deepcopy(self.file_list)
  83. if self.shuffle:
  84. random.shuffle(files)
  85. files = files[:self.num_samples]
  86. self.num_samples = len(files)
  87. for f in files:
  88. records = f[1]
  89. sample = [f[0], records]
  90. yield sample