readers.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. #copyright (c) 2020 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 os
  15. import sys
  16. import cv2
  17. import numpy as np
  18. import six
  19. import glob
  20. from .data_path_utils import _find_classes
  21. from PIL import Image
  22. def resize_short(img, target_size, interpolation=None):
  23. """resize image
  24. Args:
  25. img: image data
  26. target_size: resize short target size
  27. interpolation: interpolation mode
  28. Returns:
  29. resized image data
  30. """
  31. percent = float(target_size) / min(img.shape[0], img.shape[1])
  32. resized_width = int(round(img.shape[1] * percent))
  33. resized_height = int(round(img.shape[0] * percent))
  34. if interpolation:
  35. resized = cv2.resize(
  36. img, (resized_width, resized_height), interpolation=interpolation)
  37. else:
  38. resized = cv2.resize(img, (resized_width, resized_height))
  39. return resized
  40. def crop_image(img, target_size, center=True):
  41. """crop image
  42. Args:
  43. img: images data
  44. target_size: crop target size
  45. center: crop mode
  46. Returns:
  47. img: cropped image data
  48. """
  49. height, width = img.shape[:2]
  50. size = target_size
  51. if center:
  52. w_start = (width - size) // 2
  53. h_start = (height - size) // 2
  54. else:
  55. w_start = np.random.randint(0, width - size + 1)
  56. h_start = np.random.randint(0, height - size + 1)
  57. w_end = w_start + size
  58. h_end = h_start + size
  59. img = img[h_start:h_end, w_start:w_end, :]
  60. return img
  61. def preprocess_image(img, random_mirror=False):
  62. """
  63. centered, scaled by 1/255.
  64. :param img: np.array: shape: [ns, h, w, 3], color order: rgb.
  65. :return: np.array: shape: [ns, h, w, 3]
  66. """
  67. mean = [0.485, 0.456, 0.406]
  68. std = [0.229, 0.224, 0.225]
  69. # transpose to [ns, 3, h, w]
  70. img = img.astype('float32').transpose((0, 3, 1, 2)) / 255
  71. img_mean = np.array(mean).reshape((3, 1, 1))
  72. img_std = np.array(std).reshape((3, 1, 1))
  73. img -= img_mean
  74. img /= img_std
  75. if random_mirror:
  76. mirror = int(np.random.uniform(0, 2))
  77. if mirror == 1:
  78. img = img[:, :, ::-1, :]
  79. return img
  80. def read_image(img_path, target_size=256, crop_size=224):
  81. """
  82. resize_short to 256, then center crop to 224.
  83. :param img_path: one image path
  84. :return: np.array: shape: [1, h, w, 3], color order: rgb.
  85. """
  86. if isinstance(img_path, str):
  87. with open(img_path, 'rb') as f:
  88. img = Image.open(f)
  89. img = img.convert('RGB')
  90. img = np.array(img)
  91. # img = cv2.imread(img_path)
  92. img = resize_short(img, target_size, interpolation=None)
  93. img = crop_image(img, target_size=crop_size, center=True)
  94. # img = img[:, :, ::-1]
  95. img = np.expand_dims(img, axis=0)
  96. return img
  97. elif isinstance(img_path, np.ndarray):
  98. assert len(img_path.shape) == 4
  99. return img_path
  100. else:
  101. ValueError(f"Not recognized data type {type(img_path)}.")
  102. class ReaderConfig(object):
  103. """
  104. A generic data loader where the images are arranged in this way:
  105. root/train/dog/xxy.jpg
  106. root/train/dog/xxz.jpg
  107. ...
  108. root/train/cat/nsdf3.jpg
  109. root/train/cat/asd932_.jpg
  110. ...
  111. root/test/dog/xxx.jpg
  112. ...
  113. root/test/cat/123.jpg
  114. ...
  115. """
  116. def __init__(self, dataset_dir, is_test):
  117. image_paths, labels, self.num_classes = self.get_dataset_info(dataset_dir, is_test)
  118. random_per = np.random.permutation(range(len(image_paths)))
  119. self.image_paths = image_paths[random_per]
  120. self.labels = labels[random_per]
  121. self.is_test = is_test
  122. def get_reader(self):
  123. def reader():
  124. IMG_EXTENSIONS = ('.jpg', '.jpeg', '.png', '.ppm', '.bmp', '.pgm', '.tif', '.tiff', '.webp')
  125. target_size = 256
  126. crop_size = 224
  127. for i, img_path in enumerate(self.image_paths):
  128. if not img_path.lower().endswith(IMG_EXTENSIONS):
  129. continue
  130. img = cv2.imread(img_path)
  131. if img is None:
  132. print(img_path)
  133. continue
  134. img = resize_short(img, target_size, interpolation=None)
  135. img = crop_image(img, crop_size, center=self.is_test)
  136. img = img[:, :, ::-1]
  137. img = np.expand_dims(img, axis=0)
  138. img = preprocess_image(img, not self.is_test)
  139. yield img, self.labels[i]
  140. return reader
  141. def get_dataset_info(self, dataset_dir, is_test=False):
  142. IMG_EXTENSIONS = ('.jpg', '.jpeg', '.png', '.ppm', '.bmp', '.pgm', '.tif', '.tiff', '.webp')
  143. # read
  144. if is_test:
  145. datasubset_dir = os.path.join(dataset_dir, 'test')
  146. else:
  147. datasubset_dir = os.path.join(dataset_dir, 'train')
  148. class_names, class_to_idx = _find_classes(datasubset_dir)
  149. # num_classes = len(class_names)
  150. image_paths = []
  151. labels = []
  152. for class_name in class_names:
  153. classes_dir = os.path.join(datasubset_dir, class_name)
  154. for img_path in glob.glob(os.path.join(classes_dir, '*')):
  155. if not img_path.lower().endswith(IMG_EXTENSIONS):
  156. continue
  157. image_paths.append(img_path)
  158. labels.append(class_to_idx[class_name])
  159. image_paths = np.array(image_paths)
  160. labels = np.array(labels)
  161. return image_paths, labels, len(class_names)
  162. def create_reader(list_image_path, list_label=None, is_test=False):
  163. def reader():
  164. IMG_EXTENSIONS = ('.jpg', '.jpeg', '.png', '.ppm', '.bmp', '.pgm', '.tif', '.tiff', '.webp')
  165. target_size = 256
  166. crop_size = 224
  167. for i, img_path in enumerate(list_image_path):
  168. if not img_path.lower().endswith(IMG_EXTENSIONS):
  169. continue
  170. img = cv2.imread(img_path)
  171. if img is None:
  172. print(img_path)
  173. continue
  174. img = resize_short(img, target_size, interpolation=None)
  175. img = crop_image(img, crop_size, center=is_test)
  176. img = img[:, :, ::-1]
  177. img_show = np.expand_dims(img, axis=0)
  178. img = preprocess_image(img_show, not is_test)
  179. label = 0 if list_label is None else list_label[i]
  180. yield img_show, img, label
  181. return reader