easydata_seg.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  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 json
  19. import cv2
  20. import numpy as np
  21. import paddlex.utils.logging as logging
  22. from paddlex.utils import path_normalization
  23. from .dataset import Dataset
  24. from .dataset import get_encoding
  25. from .dataset import is_pic
  26. class EasyDataSeg(Dataset):
  27. """读取EasyDataSeg语义分割任务数据集,并对样本进行相应的处理。
  28. Args:
  29. data_dir (str): 数据集所在的目录路径。
  30. file_list (str): 描述数据集图片文件和对应标注文件的文件路径(文本内每行路径为相对data_dir的相对路)。
  31. label_list (str): 描述数据集包含的类别信息文件路径。
  32. transforms (list): 数据集中每个样本的预处理/增强算子。
  33. num_workers (int): 数据集中样本在预处理过程中的线程或进程数。默认为4。
  34. buffer_size (int): 数据集中样本在预处理过程中队列的缓存长度,以样本数为单位。默认为100。
  35. parallel_method (str): 数据集中样本在预处理过程中并行处理的方式,支持'thread'
  36. 线程和'process'进程两种方式。默认为'process'(Windows和Mac下会强制使用thread,该参数无效)。
  37. shuffle (bool): 是否需要对数据集中样本打乱顺序。默认为False。
  38. """
  39. def __init__(self,
  40. data_dir,
  41. file_list,
  42. label_list,
  43. transforms=None,
  44. num_workers='auto',
  45. buffer_size=100,
  46. parallel_method='process',
  47. shuffle=False):
  48. super(EasyDataSeg, self).__init__(
  49. transforms=transforms,
  50. num_workers=num_workers,
  51. buffer_size=buffer_size,
  52. parallel_method=parallel_method,
  53. shuffle=shuffle)
  54. self.file_list = list()
  55. self.labels = list()
  56. self._epoch = 0
  57. from pycocotools.mask import decode
  58. cname2cid = {}
  59. label_id = 0
  60. with open(label_list, encoding=get_encoding(label_list)) as fr:
  61. for line in fr.readlines():
  62. cname2cid[line.strip()] = label_id
  63. label_id += 1
  64. self.labels.append(line.strip())
  65. with open(file_list, encoding=get_encoding(file_list)) as f:
  66. for line in f:
  67. img_file, json_file = [osp.join(data_dir, x) \
  68. for x in line.strip().split()[:2]]
  69. img_file = path_normalization(img_file)
  70. json_file = path_normalization(json_file)
  71. if not is_pic(img_file):
  72. continue
  73. if not osp.isfile(json_file):
  74. continue
  75. if not osp.exists(img_file):
  76. raise IOError('The image file {} is not exist!'.format(
  77. img_file))
  78. with open(json_file, mode='r', \
  79. encoding=get_encoding(json_file)) as j:
  80. json_info = json.load(j)
  81. im = cv2.imread(img_file)
  82. im_w = im.shape[1]
  83. im_h = im.shape[0]
  84. objs = json_info['labels']
  85. lable_npy = np.zeros([im_h, im_w]).astype('uint8')
  86. for i, obj in enumerate(objs):
  87. cname = obj['name']
  88. cid = cname2cid[cname]
  89. mask_dict = {}
  90. mask_dict['size'] = [im_h, im_w]
  91. mask_dict['counts'] = obj['mask'].encode()
  92. mask = decode(mask_dict)
  93. mask *= cid
  94. conflict_index = np.where(((lable_npy > 0) &
  95. (mask == cid)) == True)
  96. mask[conflict_index] = 0
  97. lable_npy += mask
  98. self.file_list.append([img_file, lable_npy])
  99. self.num_samples = len(self.file_list)
  100. logging.info("{} samples in file {}".format(
  101. len(self.file_list), file_list))
  102. def iterator(self):
  103. self._epoch += 1
  104. self._pos = 0
  105. files = copy.deepcopy(self.file_list)
  106. if self.shuffle:
  107. random.shuffle(files)
  108. files = files[:self.num_samples]
  109. self.num_samples = len(files)
  110. for f in files:
  111. lable_npy = f[1]
  112. sample = [f[0], None, lable_npy]
  113. yield sample