cls_transforms.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  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. 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 Compose:
  20. """根据数据预处理/增强算子对输入数据进行操作。
  21. 所有操作的输入图像流形状均是[H, W, C],其中H为图像高,W为图像宽,C为图像通道数。
  22. Args:
  23. transforms (list): 数据预处理/增强算子。
  24. Raises:
  25. TypeError: 形参数据类型不满足需求。
  26. ValueError: 数据长度不匹配。
  27. """
  28. def __init__(self, transforms):
  29. if not isinstance(transforms, list):
  30. raise TypeError('The transforms must be a list!')
  31. if len(transforms) < 1:
  32. raise ValueError('The length of transforms ' + \
  33. 'must be equal or larger than 1!')
  34. self.transforms = transforms
  35. def __call__(self, im, label=None):
  36. """
  37. Args:
  38. im (str/np.ndarray): 图像路径/图像np.ndarray数据。
  39. label (int): 每张图像所对应的类别序号。
  40. Returns:
  41. tuple: 根据网络所需字段所组成的tuple;
  42. 字段由transforms中的最后一个数据预处理操作决定。
  43. """
  44. im = cv2.imread(im).astype('float32')
  45. if im is None:
  46. raise TypeError('Can\'t read The image file {}!'.format(im))
  47. im = cv2.cvtColor(im, cv2.COLOR_BGR2RGB)
  48. for op in self.transforms:
  49. outputs = op(im, label)
  50. im = outputs[0]
  51. if len(outputs) == 2:
  52. label = outputs[1]
  53. return outputs
  54. class RandomCrop:
  55. """对图像进行随机剪裁,模型训练时的数据增强操作。
  56. 1. 根据lower_scale、lower_ratio、upper_ratio计算随机剪裁的高、宽。
  57. 2. 根据随机剪裁的高、宽随机选取剪裁的起始点。
  58. 3. 剪裁图像。
  59. 4. 调整剪裁后的图像的大小到crop_size*crop_size。
  60. Args:
  61. crop_size (int): 随机裁剪后重新调整的目标边长。默认为224。
  62. lower_scale (float): 裁剪面积相对原面积比例的最小限制。默认为0.88。
  63. lower_ratio (float): 宽变换比例的最小限制。默认为3. / 4。
  64. upper_ratio (float): 宽变换比例的最大限制。默认为4. / 3。
  65. """
  66. def __init__(self,
  67. crop_size=224,
  68. lower_scale=0.88,
  69. lower_ratio=3. / 4,
  70. upper_ratio=4. / 3):
  71. self.crop_size = crop_size
  72. self.lower_scale = lower_scale
  73. self.lower_ratio = lower_ratio
  74. self.upper_ratio = upper_ratio
  75. def __call__(self, im, label=None):
  76. """
  77. Args:
  78. im (np.ndarray): 图像np.ndarray数据。
  79. label (int): 每张图像所对应的类别序号。
  80. Returns:
  81. tuple: 当label为空时,返回的tuple为(im, ),对应图像np.ndarray数据;
  82. 当label不为空时,返回的tuple为(im, label),分别对应图像np.ndarray数据、图像类别id。
  83. """
  84. im = random_crop(im, self.crop_size, self.lower_scale,
  85. self.lower_ratio, self.upper_ratio)
  86. if label is None:
  87. return (im, )
  88. else:
  89. return (im, label)
  90. class RandomHorizontalFlip:
  91. """以一定的概率对图像进行随机水平翻转,模型训练时的数据增强操作。
  92. Args:
  93. prob (float): 随机水平翻转的概率。默认为0.5。
  94. """
  95. def __init__(self, prob=0.5):
  96. self.prob = prob
  97. def __call__(self, im, label=None):
  98. """
  99. Args:
  100. im (np.ndarray): 图像np.ndarray数据。
  101. label (int): 每张图像所对应的类别序号。
  102. Returns:
  103. tuple: 当label为空时,返回的tuple为(im, ),对应图像np.ndarray数据;
  104. 当label不为空时,返回的tuple为(im, label),分别对应图像np.ndarray数据、图像类别id。
  105. """
  106. if random.random() < self.prob:
  107. im = horizontal_flip(im)
  108. if label is None:
  109. return (im, )
  110. else:
  111. return (im, label)
  112. class RandomVerticalFlip:
  113. """以一定的概率对图像进行随机垂直翻转,模型训练时的数据增强操作。
  114. Args:
  115. prob (float): 随机垂直翻转的概率。默认为0.5。
  116. """
  117. def __init__(self, prob=0.5):
  118. self.prob = prob
  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. if random.random() < self.prob:
  129. im = vertical_flip(im)
  130. if label is None:
  131. return (im, )
  132. else:
  133. return (im, label)
  134. class Normalize:
  135. """对图像进行标准化。
  136. 1. 对图像进行归一化到区间[0.0, 1.0]。
  137. 2. 对图像进行减均值除以标准差操作。
  138. Args:
  139. mean (list): 图像数据集的均值。默认为[0.485, 0.456, 0.406]。
  140. std (list): 图像数据集的标准差。默认为[0.229, 0.224, 0.225]。
  141. """
  142. def __init__(self, mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]):
  143. self.mean = mean
  144. self.std = std
  145. def __call__(self, im, label=None):
  146. """
  147. Args:
  148. im (np.ndarray): 图像np.ndarray数据。
  149. label (int): 每张图像所对应的类别序号。
  150. Returns:
  151. tuple: 当label为空时,返回的tuple为(im, ),对应图像np.ndarray数据;
  152. 当label不为空时,返回的tuple为(im, label),分别对应图像np.ndarray数据、图像类别id。
  153. """
  154. mean = np.array(self.mean)[np.newaxis, np.newaxis, :]
  155. std = np.array(self.std)[np.newaxis, np.newaxis, :]
  156. im = normalize(im, mean, std)
  157. if label is None:
  158. return (im, )
  159. else:
  160. return (im, label)
  161. class ResizeByShort:
  162. """根据图像短边对图像重新调整大小(resize)。
  163. 1. 获取图像的长边和短边长度。
  164. 2. 根据短边与short_size的比例,计算长边的目标长度,
  165. 此时高、宽的resize比例为short_size/原图短边长度。
  166. 3. 如果max_size>0,调整resize比例:
  167. 如果长边的目标长度>max_size,则高、宽的resize比例为max_size/原图长边长度;
  168. 4. 根据调整大小的比例对图像进行resize。
  169. Args:
  170. short_size (int): 调整大小后的图像目标短边长度。默认为256。
  171. max_size (int): 长边目标长度的最大限制。默认为-1。
  172. """
  173. def __init__(self, short_size=256, max_size=-1):
  174. self.short_size = short_size
  175. self.max_size = max_size
  176. def __call__(self, im, label=None):
  177. """
  178. Args:
  179. im (np.ndarray): 图像np.ndarray数据。
  180. label (int): 每张图像所对应的类别序号。
  181. Returns:
  182. tuple: 当label为空时,返回的tuple为(im, ),对应图像np.ndarray数据;
  183. 当label不为空时,返回的tuple为(im, label),分别对应图像np.ndarray数据、图像类别id。
  184. """
  185. im_short_size = min(im.shape[0], im.shape[1])
  186. im_long_size = max(im.shape[0], im.shape[1])
  187. scale = float(self.short_size) / im_short_size
  188. if self.max_size > 0 and np.round(
  189. scale * im_long_size) > self.max_size:
  190. scale = float(self.max_size) / float(im_long_size)
  191. resized_width = int(round(im.shape[1] * scale))
  192. resized_height = int(round(im.shape[0] * scale))
  193. im = cv2.resize(
  194. im, (resized_width, resized_height),
  195. interpolation=cv2.INTER_LINEAR)
  196. if label is None:
  197. return (im, )
  198. else:
  199. return (im, label)
  200. class CenterCrop:
  201. """以图像中心点扩散裁剪长宽为`crop_size`的正方形
  202. 1. 计算剪裁的起始点。
  203. 2. 剪裁图像。
  204. Args:
  205. crop_size (int): 裁剪的目标边长。默认为224。
  206. """
  207. def __init__(self, crop_size=224):
  208. self.crop_size = crop_size
  209. def __call__(self, im, label=None):
  210. """
  211. Args:
  212. im (np.ndarray): 图像np.ndarray数据。
  213. label (int): 每张图像所对应的类别序号。
  214. Returns:
  215. tuple: 当label为空时,返回的tuple为(im, ),对应图像np.ndarray数据;
  216. 当label不为空时,返回的tuple为(im, label),分别对应图像np.ndarray数据、图像类别id。
  217. """
  218. im = center_crop(im, self.crop_size)
  219. if label is None:
  220. return (im, )
  221. else:
  222. return (im, label)
  223. class RandomRotate:
  224. def __init__(self, rotate_range=30, prob=0.5):
  225. """以一定的概率对图像在[-rotate_range, rotaterange]角度范围内进行旋转,模型训练时的数据增强操作。
  226. Args:
  227. rotate_range (int): 旋转度数的范围。默认为30。
  228. prob (float): 随机旋转的概率。默认为0.5。
  229. """
  230. self.rotate_range = rotate_range
  231. self.prob = prob
  232. def __call__(self, im, label=None):
  233. """
  234. Args:
  235. im (np.ndarray): 图像np.ndarray数据。
  236. label (int): 每张图像所对应的类别序号。
  237. Returns:
  238. tuple: 当label为空时,返回的tuple为(im, ),对应图像np.ndarray数据;
  239. 当label不为空时,返回的tuple为(im, label),分别对应图像np.ndarray数据、图像类别id。
  240. """
  241. rotate_lower = -self.rotate_range
  242. rotate_upper = self.rotate_range
  243. im = im.astype('uint8')
  244. im = Image.fromarray(im)
  245. if np.random.uniform(0, 1) < self.prob:
  246. im = rotate(im, rotate_lower, rotate_upper)
  247. im = np.asarray(im).astype('float32')
  248. if label is None:
  249. return (im, )
  250. else:
  251. return (im, label)
  252. class RandomDistort:
  253. """以一定的概率对图像进行随机像素内容变换,模型训练时的数据增强操作。
  254. 1. 对变换的操作顺序进行随机化操作。
  255. 2. 按照1中的顺序以一定的概率对图像在范围[-range, range]内进行随机像素内容变换。
  256. Args:
  257. brightness_range (float): 明亮度因子的范围。默认为0.9。
  258. brightness_prob (float): 随机调整明亮度的概率。默认为0.5。
  259. contrast_range (float): 对比度因子的范围。默认为0.9。
  260. contrast_prob (float): 随机调整对比度的概率。默认为0.5。
  261. saturation_range (float): 饱和度因子的范围。默认为0.9。
  262. saturation_prob (float): 随机调整饱和度的概率。默认为0.5。
  263. hue_range (int): 色调因子的范围。默认为18。
  264. hue_prob (float): 随机调整色调的概率。默认为0.5。
  265. """
  266. def __init__(self,
  267. brightness_range=0.9,
  268. brightness_prob=0.5,
  269. contrast_range=0.9,
  270. contrast_prob=0.5,
  271. saturation_range=0.9,
  272. saturation_prob=0.5,
  273. hue_range=18,
  274. hue_prob=0.5):
  275. self.brightness_range = brightness_range
  276. self.brightness_prob = brightness_prob
  277. self.contrast_range = contrast_range
  278. self.contrast_prob = contrast_prob
  279. self.saturation_range = saturation_range
  280. self.saturation_prob = saturation_prob
  281. self.hue_range = hue_range
  282. self.hue_prob = hue_prob
  283. def __call__(self, im, label=None):
  284. """
  285. Args:
  286. im (np.ndarray): 图像np.ndarray数据。
  287. label (int): 每张图像所对应的类别序号。
  288. Returns:
  289. tuple: 当label为空时,返回的tuple为(im, ),对应图像np.ndarray数据;
  290. 当label不为空时,返回的tuple为(im, label),分别对应图像np.ndarray数据、图像类别id。
  291. """
  292. brightness_lower = 1 - self.brightness_range
  293. brightness_upper = 1 + self.brightness_range
  294. contrast_lower = 1 - self.contrast_range
  295. contrast_upper = 1 + self.contrast_range
  296. saturation_lower = 1 - self.saturation_range
  297. saturation_upper = 1 + self.saturation_range
  298. hue_lower = -self.hue_range
  299. hue_upper = self.hue_range
  300. ops = [brightness, contrast, saturation, hue]
  301. random.shuffle(ops)
  302. params_dict = {
  303. 'brightness': {
  304. 'brightness_lower': brightness_lower,
  305. 'brightness_upper': brightness_upper
  306. },
  307. 'contrast': {
  308. 'contrast_lower': contrast_lower,
  309. 'contrast_upper': contrast_upper
  310. },
  311. 'saturation': {
  312. 'saturation_lower': saturation_lower,
  313. 'saturation_upper': saturation_upper
  314. },
  315. 'hue': {
  316. 'hue_lower': hue_lower,
  317. 'hue_upper': hue_upper
  318. }
  319. }
  320. prob_dict = {
  321. 'brightness': self.brightness_prob,
  322. 'contrast': self.contrast_prob,
  323. 'saturation': self.saturation_prob,
  324. 'hue': self.hue_prob,
  325. }
  326. im = im.astype('uint8')
  327. im = Image.fromarray(im)
  328. for id in range(len(ops)):
  329. params = params_dict[ops[id].__name__]
  330. prob = prob_dict[ops[id].__name__]
  331. params['im'] = im
  332. if np.random.uniform(0, 1) < prob:
  333. im = ops[id](**params)
  334. im = np.asarray(im).astype('float32')
  335. if label is None:
  336. return (im, )
  337. else:
  338. return (im, label)
  339. class ArrangeClassifier:
  340. """获取训练/验证/预测所需信息。注意:此操作不需用户自己显示调用
  341. Args:
  342. mode (str): 指定数据用于何种用途,取值范围为['train', 'eval', 'test', 'quant']。
  343. Raises:
  344. ValueError: mode的取值不在['train', 'eval', 'test', 'quant']之内。
  345. """
  346. def __init__(self, mode=None):
  347. if mode not in ['train', 'eval', 'test', 'quant']:
  348. raise ValueError(
  349. "mode must be in ['train', 'eval', 'test', 'quant']!")
  350. self.mode = mode
  351. def __call__(self, im, label=None):
  352. """
  353. Args:
  354. im (np.ndarray): 图像np.ndarray数据。
  355. label (int): 每张图像所对应的类别序号。
  356. Returns:
  357. tuple: 当mode为'train'或'eval'时,返回(im, label),分别对应图像np.ndarray数据、
  358. 图像类别id;当mode为'test'或'quant'时,返回(im, ),对应图像np.ndarray数据。
  359. """
  360. im = permute(im, False)
  361. if self.mode == 'train' or self.mode == 'eval':
  362. outputs = (im, label)
  363. else:
  364. outputs = (im, )
  365. return outputs