data.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. import numpy as np
  2. import paddle
  3. import os
  4. import cv2
  5. import glob
  6. def transform(data, ops=None):
  7. """ transform """
  8. if ops is None:
  9. ops = []
  10. for op in ops:
  11. data = op(data)
  12. if data is None:
  13. return None
  14. return data
  15. def create_operators(op_param_list, global_config=None):
  16. """
  17. create operators based on the config
  18. Args:
  19. params(list): a dict list, used to create some operators
  20. """
  21. assert isinstance(op_param_list, list), ('operator config should be a list')
  22. ops = []
  23. for operator in op_param_list:
  24. assert isinstance(operator,
  25. dict) and len(operator) == 1, "yaml format error"
  26. op_name = list(operator)[0]
  27. param = {} if operator[op_name] is None else operator[op_name]
  28. if global_config is not None:
  29. param.update(global_config)
  30. op = eval(op_name)(**param)
  31. ops.append(op)
  32. return ops
  33. class DecodeImage(object):
  34. """ decode image """
  35. def __init__(self, img_mode='RGB', channel_first=False, **kwargs):
  36. self.img_mode = img_mode
  37. self.channel_first = channel_first
  38. def __call__(self, data):
  39. img = data['image']
  40. if six.PY2:
  41. assert type(img) is str and len(
  42. img) > 0, "invalid input 'img' in DecodeImage"
  43. else:
  44. assert type(img) is bytes and len(
  45. img) > 0, "invalid input 'img' in DecodeImage"
  46. img = np.frombuffer(img, dtype='uint8')
  47. img = cv2.imdecode(img, 1)
  48. if img is None:
  49. return None
  50. if self.img_mode == 'GRAY':
  51. img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
  52. elif self.img_mode == 'RGB':
  53. assert img.shape[2] == 3, 'invalid shape of image[%s]' % (img.shape)
  54. img = img[:, :, ::-1]
  55. if self.channel_first:
  56. img = img.transpose((2, 0, 1))
  57. data['image'] = img
  58. data['src_image'] = img
  59. return data
  60. class NormalizeImage(object):
  61. """ normalize image such as substract mean, divide std
  62. """
  63. def __init__(self, scale=None, mean=None, std=None, order='chw', **kwargs):
  64. if isinstance(scale, str):
  65. scale = eval(scale)
  66. self.scale = np.float32(scale if scale is not None else 1.0 / 255.0)
  67. mean = mean if mean is not None else [0.485, 0.456, 0.406]
  68. std = std if std is not None else [0.229, 0.224, 0.225]
  69. shape = (3, 1, 1) if order == 'chw' else (1, 1, 3)
  70. self.mean = np.array(mean).reshape(shape).astype('float32')
  71. self.std = np.array(std).reshape(shape).astype('float32')
  72. def __call__(self, data):
  73. img = data['image']
  74. from PIL import Image
  75. if isinstance(img, Image.Image):
  76. img = np.array(img)
  77. assert isinstance(img,
  78. np.ndarray), "invalid input 'img' in NormalizeImage"
  79. data['image'] = (
  80. img.astype('float32') * self.scale - self.mean) / self.std
  81. return data
  82. class ToCHWImage(object):
  83. """ convert hwc image to chw image
  84. """
  85. def __init__(self, **kwargs):
  86. pass
  87. def __call__(self, data):
  88. img = data['image']
  89. from PIL import Image
  90. if isinstance(img, Image.Image):
  91. img = np.array(img)
  92. data['image'] = img.transpose((2, 0, 1))
  93. src_img = data['src_image']
  94. from PIL import Image
  95. if isinstance(img, Image.Image):
  96. src_img = np.array(src_img)
  97. data['src_image'] = img.transpose((2, 0, 1))
  98. return data
  99. class SimpleDataset(nn.Dataset):
  100. def __init__(self, config, mode, logger, seed=None):
  101. self.logger = logger
  102. self.mode = mode.lower()
  103. data_dir = config['Train']['data_dir']
  104. imgs_list = self.get_image_list(data_dir)
  105. self.ops = create_operators(cfg['transforms'], None)
  106. def get_image_list(self, img_dir):
  107. imgs = glob.glob(os.path.join(img_dir, "*.png"))
  108. if len(imgs) == 0:
  109. raise ValueError(f"not any images founded in {img_dir}")
  110. return imgs
  111. def __getitem__(self, idx):
  112. return None