cls_transforms.py 10 KB

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