cls_transforms.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  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 .ops import *
  15. from .imgaug_support import execute_imgaug
  16. import random
  17. import os.path as osp
  18. import numpy as np
  19. from PIL import Image, ImageEnhance
  20. class ClsTransform:
  21. """分类Transform的基类
  22. """
  23. def __init__(self):
  24. pass
  25. class Compose(ClsTransform):
  26. """根据数据预处理/增强算子对输入数据进行操作。
  27. 所有操作的输入图像流形状均是[H, W, C],其中H为图像高,W为图像宽,C为图像通道数。
  28. Args:
  29. transforms (list): 数据预处理/增强算子。
  30. Raises:
  31. TypeError: 形参数据类型不满足需求。
  32. ValueError: 数据长度不匹配。
  33. """
  34. def __init__(self, transforms):
  35. if not isinstance(transforms, list):
  36. raise TypeError('The transforms must be a list!')
  37. if len(transforms) < 1:
  38. raise ValueError('The length of transforms ' + \
  39. 'must be equal or larger than 1!')
  40. self.transforms = transforms
  41. def __call__(self, im, label=None):
  42. """
  43. Args:
  44. im (str/np.ndarray): 图像路径/图像np.ndarray数据。
  45. label (int): 每张图像所对应的类别序号。
  46. Returns:
  47. tuple: 根据网络所需字段所组成的tuple;
  48. 字段由transforms中的最后一个数据预处理操作决定。
  49. """
  50. if isinstance(im, np.ndarray):
  51. if len(im.shape) != 3:
  52. raise Exception(
  53. "im should be 3-dimension, but now is {}-dimensions".
  54. format(len(im.shape)))
  55. else:
  56. try:
  57. im = cv2.imread(im).astype('float32')
  58. except:
  59. raise TypeError('Can\'t read The image file {}!'.format(im))
  60. im = cv2.cvtColor(im, cv2.COLOR_BGR2RGB)
  61. for op in self.transforms:
  62. outputs = op(im, label)
  63. im = outputs[0]
  64. if len(outputs) == 2:
  65. label = outputs[1]
  66. return outputs
  67. def add_augmenters(self, augmenters):
  68. if not isinstance(augmenters, list):
  69. raise Exception(
  70. "augmenters should be list type in func add_augmenters()")
  71. transform_names = [type(x).__name__ for x in self.transforms]
  72. for aug in augmenters:
  73. if type(aug).__name__ in transform_names:
  74. print("{} is already in ComposedTransforms, need to remove it from add_augmenters().".format(type(aug).__name__))
  75. self.transforms = augmenters + self.transforms
  76. class Normalize(ClsTransform):
  77. """对图像进行标准化。
  78. 1. 对图像进行归一化到区间[0.0, 1.0]。
  79. 2. 对图像进行减均值除以标准差操作。
  80. Args:
  81. mean (list): 图像数据集的均值。默认为[0.485, 0.456, 0.406]。
  82. std (list): 图像数据集的标准差。默认为[0.229, 0.224, 0.225]。
  83. """
  84. def __init__(self, mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]):
  85. self.mean = mean
  86. self.std = std
  87. def __call__(self, im, label=None):
  88. """
  89. Args:
  90. im (np.ndarray): 图像np.ndarray数据。
  91. label (int): 每张图像所对应的类别序号。
  92. Returns:
  93. tuple: 当label为空时,返回的tuple为(im, ),对应图像np.ndarray数据;
  94. 当label不为空时,返回的tuple为(im, label),分别对应图像np.ndarray数据、图像类别id。
  95. """
  96. mean = np.array(self.mean)[np.newaxis, np.newaxis, :]
  97. std = np.array(self.std)[np.newaxis, np.newaxis, :]
  98. im = normalize(im, mean, std)
  99. if label is None:
  100. return (im, )
  101. else:
  102. return (im, label)
  103. class ResizeByShort(ClsTransform):
  104. """根据图像短边对图像重新调整大小(resize)。
  105. 1. 获取图像的长边和短边长度。
  106. 2. 根据短边与short_size的比例,计算长边的目标长度,
  107. 此时高、宽的resize比例为short_size/原图短边长度。
  108. 3. 如果max_size>0,调整resize比例:
  109. 如果长边的目标长度>max_size,则高、宽的resize比例为max_size/原图长边长度;
  110. 4. 根据调整大小的比例对图像进行resize。
  111. Args:
  112. short_size (int): 调整大小后的图像目标短边长度。默认为256。
  113. max_size (int): 长边目标长度的最大限制。默认为-1。
  114. """
  115. def __init__(self, short_size=256, max_size=-1):
  116. self.short_size = short_size
  117. self.max_size = max_size
  118. def __call__(self, im, label=None):
  119. """
  120. Args:
  121. im (np.ndarray): 图像np.ndarray数据。
  122. label (int): 每张图像所对应的类别序号。
  123. Returns:
  124. tuple: 当label为空时,返回的tuple为(im, ),对应图像np.ndarray数据;
  125. 当label不为空时,返回的tuple为(im, label),分别对应图像np.ndarray数据、图像类别id。
  126. """
  127. im_short_size = min(im.shape[0], im.shape[1])
  128. im_long_size = max(im.shape[0], im.shape[1])
  129. scale = float(self.short_size) / im_short_size
  130. if self.max_size > 0 and np.round(scale *
  131. im_long_size) > self.max_size:
  132. scale = float(self.max_size) / float(im_long_size)
  133. resized_width = int(round(im.shape[1] * scale))
  134. resized_height = int(round(im.shape[0] * scale))
  135. im = cv2.resize(
  136. im, (resized_width, resized_height),
  137. interpolation=cv2.INTER_LINEAR)
  138. if label is None:
  139. return (im, )
  140. else:
  141. return (im, label)
  142. class CenterCrop(ClsTransform):
  143. """以图像中心点扩散裁剪长宽为`crop_size`的正方形
  144. 1. 计算剪裁的起始点。
  145. 2. 剪裁图像。
  146. Args:
  147. crop_size (int): 裁剪的目标边长。默认为224。
  148. """
  149. def __init__(self, crop_size=224):
  150. self.crop_size = crop_size
  151. def __call__(self, im, label=None):
  152. """
  153. Args:
  154. im (np.ndarray): 图像np.ndarray数据。
  155. label (int): 每张图像所对应的类别序号。
  156. Returns:
  157. tuple: 当label为空时,返回的tuple为(im, ),对应图像np.ndarray数据;
  158. 当label不为空时,返回的tuple为(im, label),分别对应图像np.ndarray数据、图像类别id。
  159. """
  160. im = center_crop(im, self.crop_size)
  161. if label is None:
  162. return (im, )
  163. else:
  164. return (im, label)
  165. class ArrangeClassifier(ClsTransform):
  166. """获取训练/验证/预测所需信息。注意:此操作不需用户自己显示调用
  167. Args:
  168. mode (str): 指定数据用于何种用途,取值范围为['train', 'eval', 'test', 'quant']。
  169. Raises:
  170. ValueError: mode的取值不在['train', 'eval', 'test', 'quant']之内。
  171. """
  172. def __init__(self, mode=None):
  173. if mode not in ['train', 'eval', 'test', 'quant']:
  174. raise ValueError(
  175. "mode must be in ['train', 'eval', 'test', 'quant']!")
  176. self.mode = mode
  177. def __call__(self, im, label=None):
  178. """
  179. Args:
  180. im (np.ndarray): 图像np.ndarray数据。
  181. label (int): 每张图像所对应的类别序号。
  182. Returns:
  183. tuple: 当mode为'train'或'eval'时,返回(im, label),分别对应图像np.ndarray数据、
  184. 图像类别id;当mode为'test'或'quant'时,返回(im, ),对应图像np.ndarray数据。
  185. """
  186. im = permute(im, False).astype('float32')
  187. if self.mode == 'train' or self.mode == 'eval':
  188. outputs = (im, label)
  189. else:
  190. outputs = (im, )
  191. return outputs
  192. class ComposedClsTransforms(Compose):
  193. """ 分类模型的基础Transforms流程,具体如下
  194. 训练阶段:
  195. 1. 随机从图像中crop一块子图,并resize成crop_size大小
  196. 2. 将1的输出按0.5的概率随机进行水平翻转
  197. 3. 将图像进行归一化
  198. 验证/预测阶段:
  199. 1. 将图像按比例Resize,使得最小边长度为crop_size[0] * 1.14
  200. 2. 从图像中心crop出一个大小为crop_size的图像
  201. 3. 将图像进行归一化
  202. Args:
  203. mode(str): 图像处理流程所处阶段,训练/验证/预测,分别对应'train', 'eval', 'test'
  204. crop_size(int|list): 输入模型里的图像大小
  205. mean(list): 图像均值
  206. std(list): 图像方差
  207. """
  208. def __init__(self,
  209. mode,
  210. crop_size=[224, 224],
  211. mean=[0.485, 0.456, 0.406],
  212. std=[0.229, 0.224, 0.225]):
  213. width = crop_size
  214. if isinstance(crop_size, list):
  215. if crop_size[0] != crop_size[1]:
  216. raise Exception(
  217. "In classifier model, width and height should be equal, please modify your parameter `crop_size`"
  218. )
  219. width = crop_size[0]
  220. if width % 32 != 0:
  221. raise Exception(
  222. "In classifier model, width and height should be multiple of 32, e.g 224、256、320...., please modify your parameter `crop_size`"
  223. )
  224. if mode == 'train':
  225. pass
  226. else:
  227. # 验证/预测时的transforms
  228. transforms = [
  229. ResizeByShort(short_size=int(width * 1.14)),
  230. CenterCrop(crop_size=width), Normalize(
  231. mean=mean, std=std)
  232. ]
  233. super(ComposedClsTransforms, self).__init__(transforms)