auto_augment.py 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000
  1. """ AutoAugment, RandAugment, AugMix, and 3-Augment for PyTorch
  2. This code implements the searched ImageNet policies with various tweaks and improvements and
  3. does not include any of the search code.
  4. AA and RA Implementation adapted from:
  5. https://github.com/tensorflow/tpu/blob/master/models/official/efficientnet/autoaugment.py
  6. AugMix adapted from:
  7. https://github.com/google-research/augmix
  8. 3-Augment based on: https://github.com/facebookresearch/deit/blob/main/README_revenge.md
  9. Papers:
  10. AutoAugment: Learning Augmentation Policies from Data - https://arxiv.org/abs/1805.09501
  11. Learning Data Augmentation Strategies for Object Detection - https://arxiv.org/abs/1906.11172
  12. RandAugment: Practical automated data augmentation... - https://arxiv.org/abs/1909.13719
  13. AugMix: A Simple Data Processing Method to Improve Robustness and Uncertainty - https://arxiv.org/abs/1912.02781
  14. 3-Augment: DeiT III: Revenge of the ViT - https://arxiv.org/abs/2204.07118
  15. Hacked together by / Copyright 2019, Ross Wightman
  16. """
  17. import random
  18. import math
  19. import re
  20. from functools import partial
  21. from typing import Dict, List, Optional, Union
  22. from PIL import Image, ImageOps, ImageEnhance, ImageChops, ImageFilter
  23. import PIL
  24. import numpy as np
  25. _PIL_VER = tuple([int(x) for x in PIL.__version__.split('.')[:2]])
  26. _FILL = (128, 128, 128)
  27. _LEVEL_DENOM = 10. # denominator for conversion from 'Mx' magnitude scale to fractional aug level for op arguments
  28. _HPARAMS_DEFAULT = dict(
  29. translate_const=250,
  30. img_mean=_FILL,
  31. )
  32. if hasattr(Image, "Resampling"):
  33. _RANDOM_INTERPOLATION = (Image.Resampling.BILINEAR, Image.Resampling.BICUBIC)
  34. _DEFAULT_INTERPOLATION = Image.Resampling.BICUBIC
  35. else:
  36. _RANDOM_INTERPOLATION = (Image.BILINEAR, Image.BICUBIC)
  37. _DEFAULT_INTERPOLATION = Image.BICUBIC
  38. def _interpolation(kwargs):
  39. interpolation = kwargs.pop('resample', _DEFAULT_INTERPOLATION)
  40. if isinstance(interpolation, (list, tuple)):
  41. return random.choice(interpolation)
  42. return interpolation
  43. def _check_args_tf(kwargs):
  44. if 'fillcolor' in kwargs and _PIL_VER < (5, 0):
  45. kwargs.pop('fillcolor')
  46. kwargs['resample'] = _interpolation(kwargs)
  47. def shear_x(img, factor, **kwargs):
  48. _check_args_tf(kwargs)
  49. return img.transform(img.size, Image.AFFINE, (1, factor, 0, 0, 1, 0), **kwargs)
  50. def shear_y(img, factor, **kwargs):
  51. _check_args_tf(kwargs)
  52. return img.transform(img.size, Image.AFFINE, (1, 0, 0, factor, 1, 0), **kwargs)
  53. def translate_x_rel(img, pct, **kwargs):
  54. pixels = pct * img.size[0]
  55. _check_args_tf(kwargs)
  56. return img.transform(img.size, Image.AFFINE, (1, 0, pixels, 0, 1, 0), **kwargs)
  57. def translate_y_rel(img, pct, **kwargs):
  58. pixels = pct * img.size[1]
  59. _check_args_tf(kwargs)
  60. return img.transform(img.size, Image.AFFINE, (1, 0, 0, 0, 1, pixels), **kwargs)
  61. def translate_x_abs(img, pixels, **kwargs):
  62. _check_args_tf(kwargs)
  63. return img.transform(img.size, Image.AFFINE, (1, 0, pixels, 0, 1, 0), **kwargs)
  64. def translate_y_abs(img, pixels, **kwargs):
  65. _check_args_tf(kwargs)
  66. return img.transform(img.size, Image.AFFINE, (1, 0, 0, 0, 1, pixels), **kwargs)
  67. def rotate(img, degrees, **kwargs):
  68. _check_args_tf(kwargs)
  69. if _PIL_VER >= (5, 2):
  70. return img.rotate(degrees, **kwargs)
  71. if _PIL_VER >= (5, 0):
  72. w, h = img.size
  73. post_trans = (0, 0)
  74. rotn_center = (w / 2.0, h / 2.0)
  75. angle = -math.radians(degrees)
  76. matrix = [
  77. round(math.cos(angle), 15),
  78. round(math.sin(angle), 15),
  79. 0.0,
  80. round(-math.sin(angle), 15),
  81. round(math.cos(angle), 15),
  82. 0.0,
  83. ]
  84. def transform(x, y, matrix):
  85. (a, b, c, d, e, f) = matrix
  86. return a * x + b * y + c, d * x + e * y + f
  87. matrix[2], matrix[5] = transform(
  88. -rotn_center[0] - post_trans[0], -rotn_center[1] - post_trans[1], matrix
  89. )
  90. matrix[2] += rotn_center[0]
  91. matrix[5] += rotn_center[1]
  92. return img.transform(img.size, Image.AFFINE, matrix, **kwargs)
  93. return img.rotate(degrees, resample=kwargs['resample'])
  94. def auto_contrast(img, **__):
  95. return ImageOps.autocontrast(img)
  96. def invert(img, **__):
  97. return ImageOps.invert(img)
  98. def equalize(img, **__):
  99. return ImageOps.equalize(img)
  100. def solarize(img, thresh, **__):
  101. return ImageOps.solarize(img, thresh)
  102. def solarize_add(img, add, thresh=128, **__):
  103. lut = []
  104. for i in range(256):
  105. if i < thresh:
  106. lut.append(min(255, i + add))
  107. else:
  108. lut.append(i)
  109. if img.mode in ("L", "RGB"):
  110. if img.mode == "RGB" and len(lut) == 256:
  111. lut = lut + lut + lut
  112. return img.point(lut)
  113. return img
  114. def posterize(img, bits_to_keep, **__):
  115. if bits_to_keep >= 8:
  116. return img
  117. return ImageOps.posterize(img, bits_to_keep)
  118. def contrast(img, factor, **__):
  119. return ImageEnhance.Contrast(img).enhance(factor)
  120. def color(img, factor, **__):
  121. return ImageEnhance.Color(img).enhance(factor)
  122. def brightness(img, factor, **__):
  123. return ImageEnhance.Brightness(img).enhance(factor)
  124. def sharpness(img, factor, **__):
  125. return ImageEnhance.Sharpness(img).enhance(factor)
  126. def gaussian_blur(img, factor, **__):
  127. img = img.filter(ImageFilter.GaussianBlur(radius=factor))
  128. return img
  129. def gaussian_blur_rand(img, factor, **__):
  130. radius_min = 0.1
  131. radius_max = 2.0
  132. img = img.filter(ImageFilter.GaussianBlur(radius=random.uniform(radius_min, radius_max * factor)))
  133. return img
  134. def desaturate(img, factor, **_):
  135. factor = min(1., max(0., 1. - factor))
  136. # enhance factor 0 = grayscale, 1.0 = no-change
  137. return ImageEnhance.Color(img).enhance(factor)
  138. def _randomly_negate(v):
  139. """With 50% prob, negate the value"""
  140. return -v if random.random() > 0.5 else v
  141. def _rotate_level_to_arg(level, _hparams):
  142. # range [-30, 30]
  143. level = (level / _LEVEL_DENOM) * 30.
  144. level = _randomly_negate(level)
  145. return level,
  146. def _enhance_level_to_arg(level, _hparams):
  147. # range [0.1, 1.9]
  148. return (level / _LEVEL_DENOM) * 1.8 + 0.1,
  149. def _enhance_increasing_level_to_arg(level, _hparams):
  150. # the 'no change' level is 1.0, moving away from that towards 0. or 2.0 increases the enhancement blend
  151. # range [0.1, 1.9] if level <= _LEVEL_DENOM
  152. level = (level / _LEVEL_DENOM) * .9
  153. level = max(0.1, 1.0 + _randomly_negate(level)) # keep it >= 0.1
  154. return level,
  155. def _minmax_level_to_arg(level, _hparams, min_val=0., max_val=1.0, clamp=True):
  156. level = (level / _LEVEL_DENOM)
  157. level = min_val + (max_val - min_val) * level
  158. if clamp:
  159. level = max(min_val, min(max_val, level))
  160. return level,
  161. def _shear_level_to_arg(level, _hparams):
  162. # range [-0.3, 0.3]
  163. level = (level / _LEVEL_DENOM) * 0.3
  164. level = _randomly_negate(level)
  165. return level,
  166. def _translate_abs_level_to_arg(level, hparams):
  167. translate_const = hparams['translate_const']
  168. level = (level / _LEVEL_DENOM) * float(translate_const)
  169. level = _randomly_negate(level)
  170. return level,
  171. def _translate_rel_level_to_arg(level, hparams):
  172. # default range [-0.45, 0.45]
  173. translate_pct = hparams.get('translate_pct', 0.45)
  174. level = (level / _LEVEL_DENOM) * translate_pct
  175. level = _randomly_negate(level)
  176. return level,
  177. def _posterize_level_to_arg(level, _hparams):
  178. # As per Tensorflow TPU EfficientNet impl
  179. # range [0, 4], 'keep 0 up to 4 MSB of original image'
  180. # intensity/severity of augmentation decreases with level
  181. return int((level / _LEVEL_DENOM) * 4),
  182. def _posterize_increasing_level_to_arg(level, hparams):
  183. # As per Tensorflow models research and UDA impl
  184. # range [4, 0], 'keep 4 down to 0 MSB of original image',
  185. # intensity/severity of augmentation increases with level
  186. return 4 - _posterize_level_to_arg(level, hparams)[0],
  187. def _posterize_original_level_to_arg(level, _hparams):
  188. # As per original AutoAugment paper description
  189. # range [4, 8], 'keep 4 up to 8 MSB of image'
  190. # intensity/severity of augmentation decreases with level
  191. return int((level / _LEVEL_DENOM) * 4) + 4,
  192. def _solarize_level_to_arg(level, _hparams):
  193. # range [0, 256]
  194. # intensity/severity of augmentation decreases with level
  195. return min(256, int((level / _LEVEL_DENOM) * 256)),
  196. def _solarize_increasing_level_to_arg(level, _hparams):
  197. # range [0, 256]
  198. # intensity/severity of augmentation increases with level
  199. return 256 - _solarize_level_to_arg(level, _hparams)[0],
  200. def _solarize_add_level_to_arg(level, _hparams):
  201. # range [0, 110]
  202. return min(128, int((level / _LEVEL_DENOM) * 110)),
  203. LEVEL_TO_ARG = {
  204. 'AutoContrast': None,
  205. 'Equalize': None,
  206. 'Invert': None,
  207. 'Rotate': _rotate_level_to_arg,
  208. # There are several variations of the posterize level scaling in various Tensorflow/Google repositories/papers
  209. 'Posterize': _posterize_level_to_arg,
  210. 'PosterizeIncreasing': _posterize_increasing_level_to_arg,
  211. 'PosterizeOriginal': _posterize_original_level_to_arg,
  212. 'Solarize': _solarize_level_to_arg,
  213. 'SolarizeIncreasing': _solarize_increasing_level_to_arg,
  214. 'SolarizeAdd': _solarize_add_level_to_arg,
  215. 'Color': _enhance_level_to_arg,
  216. 'ColorIncreasing': _enhance_increasing_level_to_arg,
  217. 'Contrast': _enhance_level_to_arg,
  218. 'ContrastIncreasing': _enhance_increasing_level_to_arg,
  219. 'Brightness': _enhance_level_to_arg,
  220. 'BrightnessIncreasing': _enhance_increasing_level_to_arg,
  221. 'Sharpness': _enhance_level_to_arg,
  222. 'SharpnessIncreasing': _enhance_increasing_level_to_arg,
  223. 'ShearX': _shear_level_to_arg,
  224. 'ShearY': _shear_level_to_arg,
  225. 'TranslateX': _translate_abs_level_to_arg,
  226. 'TranslateY': _translate_abs_level_to_arg,
  227. 'TranslateXRel': _translate_rel_level_to_arg,
  228. 'TranslateYRel': _translate_rel_level_to_arg,
  229. 'Desaturate': partial(_minmax_level_to_arg, min_val=0.5, max_val=1.0),
  230. 'GaussianBlur': partial(_minmax_level_to_arg, min_val=0.1, max_val=2.0),
  231. 'GaussianBlurRand': _minmax_level_to_arg,
  232. }
  233. NAME_TO_OP = {
  234. 'AutoContrast': auto_contrast,
  235. 'Equalize': equalize,
  236. 'Invert': invert,
  237. 'Rotate': rotate,
  238. 'Posterize': posterize,
  239. 'PosterizeIncreasing': posterize,
  240. 'PosterizeOriginal': posterize,
  241. 'Solarize': solarize,
  242. 'SolarizeIncreasing': solarize,
  243. 'SolarizeAdd': solarize_add,
  244. 'Color': color,
  245. 'ColorIncreasing': color,
  246. 'Contrast': contrast,
  247. 'ContrastIncreasing': contrast,
  248. 'Brightness': brightness,
  249. 'BrightnessIncreasing': brightness,
  250. 'Sharpness': sharpness,
  251. 'SharpnessIncreasing': sharpness,
  252. 'ShearX': shear_x,
  253. 'ShearY': shear_y,
  254. 'TranslateX': translate_x_abs,
  255. 'TranslateY': translate_y_abs,
  256. 'TranslateXRel': translate_x_rel,
  257. 'TranslateYRel': translate_y_rel,
  258. 'Desaturate': desaturate,
  259. 'GaussianBlur': gaussian_blur,
  260. 'GaussianBlurRand': gaussian_blur_rand,
  261. }
  262. class AugmentOp:
  263. def __init__(self, name, prob=0.5, magnitude=10, hparams=None):
  264. hparams = hparams or _HPARAMS_DEFAULT
  265. self.name = name
  266. self.aug_fn = NAME_TO_OP[name]
  267. self.level_fn = LEVEL_TO_ARG[name]
  268. self.prob = prob
  269. self.magnitude = magnitude
  270. self.hparams = hparams.copy()
  271. self.kwargs = dict(
  272. fillcolor=hparams['img_mean'] if 'img_mean' in hparams else _FILL,
  273. resample=hparams['interpolation'] if 'interpolation' in hparams else _RANDOM_INTERPOLATION,
  274. )
  275. # If magnitude_std is > 0, we introduce some randomness
  276. # in the usually fixed policy and sample magnitude from a normal distribution
  277. # with mean `magnitude` and std-dev of `magnitude_std`.
  278. # NOTE This is my own hack, being tested, not in papers or reference impls.
  279. # If magnitude_std is inf, we sample magnitude from a uniform distribution
  280. self.magnitude_std = self.hparams.get('magnitude_std', 0)
  281. self.magnitude_max = self.hparams.get('magnitude_max', None)
  282. def __call__(self, img):
  283. if self.prob < 1.0 and random.random() > self.prob:
  284. return img
  285. magnitude = self.magnitude
  286. if self.magnitude_std > 0:
  287. # magnitude randomization enabled
  288. if self.magnitude_std == float('inf'):
  289. # inf == uniform sampling
  290. magnitude = random.uniform(0, magnitude)
  291. elif self.magnitude_std > 0:
  292. magnitude = random.gauss(magnitude, self.magnitude_std)
  293. # default upper_bound for the timm RA impl is _LEVEL_DENOM (10)
  294. # setting magnitude_max overrides this to allow M > 10 (behaviour closer to Google TF RA impl)
  295. upper_bound = self.magnitude_max or _LEVEL_DENOM
  296. magnitude = max(0., min(magnitude, upper_bound))
  297. level_args = self.level_fn(magnitude, self.hparams) if self.level_fn is not None else tuple()
  298. return self.aug_fn(img, *level_args, **self.kwargs)
  299. def __repr__(self):
  300. fs = self.__class__.__name__ + f'(name={self.name}, p={self.prob}'
  301. fs += f', m={self.magnitude}, mstd={self.magnitude_std}'
  302. if self.magnitude_max is not None:
  303. fs += f', mmax={self.magnitude_max}'
  304. fs += ')'
  305. return fs
  306. def auto_augment_policy_v0(hparams):
  307. # ImageNet v0 policy from TPU EfficientNet impl, cannot find a paper reference.
  308. policy = [
  309. [('Equalize', 0.8, 1), ('ShearY', 0.8, 4)],
  310. [('Color', 0.4, 9), ('Equalize', 0.6, 3)],
  311. [('Color', 0.4, 1), ('Rotate', 0.6, 8)],
  312. [('Solarize', 0.8, 3), ('Equalize', 0.4, 7)],
  313. [('Solarize', 0.4, 2), ('Solarize', 0.6, 2)],
  314. [('Color', 0.2, 0), ('Equalize', 0.8, 8)],
  315. [('Equalize', 0.4, 8), ('SolarizeAdd', 0.8, 3)],
  316. [('ShearX', 0.2, 9), ('Rotate', 0.6, 8)],
  317. [('Color', 0.6, 1), ('Equalize', 1.0, 2)],
  318. [('Invert', 0.4, 9), ('Rotate', 0.6, 0)],
  319. [('Equalize', 1.0, 9), ('ShearY', 0.6, 3)],
  320. [('Color', 0.4, 7), ('Equalize', 0.6, 0)],
  321. [('Posterize', 0.4, 6), ('AutoContrast', 0.4, 7)],
  322. [('Solarize', 0.6, 8), ('Color', 0.6, 9)],
  323. [('Solarize', 0.2, 4), ('Rotate', 0.8, 9)],
  324. [('Rotate', 1.0, 7), ('TranslateYRel', 0.8, 9)],
  325. [('ShearX', 0.0, 0), ('Solarize', 0.8, 4)],
  326. [('ShearY', 0.8, 0), ('Color', 0.6, 4)],
  327. [('Color', 1.0, 0), ('Rotate', 0.6, 2)],
  328. [('Equalize', 0.8, 4), ('Equalize', 0.0, 8)],
  329. [('Equalize', 1.0, 4), ('AutoContrast', 0.6, 2)],
  330. [('ShearY', 0.4, 7), ('SolarizeAdd', 0.6, 7)],
  331. [('Posterize', 0.8, 2), ('Solarize', 0.6, 10)], # This results in black image with Tpu posterize
  332. [('Solarize', 0.6, 8), ('Equalize', 0.6, 1)],
  333. [('Color', 0.8, 6), ('Rotate', 0.4, 5)],
  334. ]
  335. pc = [[AugmentOp(*a, hparams=hparams) for a in sp] for sp in policy]
  336. return pc
  337. def auto_augment_policy_v0r(hparams):
  338. # ImageNet v0 policy from TPU EfficientNet impl, with variation of Posterize used
  339. # in Google research implementation (number of bits discarded increases with magnitude)
  340. policy = [
  341. [('Equalize', 0.8, 1), ('ShearY', 0.8, 4)],
  342. [('Color', 0.4, 9), ('Equalize', 0.6, 3)],
  343. [('Color', 0.4, 1), ('Rotate', 0.6, 8)],
  344. [('Solarize', 0.8, 3), ('Equalize', 0.4, 7)],
  345. [('Solarize', 0.4, 2), ('Solarize', 0.6, 2)],
  346. [('Color', 0.2, 0), ('Equalize', 0.8, 8)],
  347. [('Equalize', 0.4, 8), ('SolarizeAdd', 0.8, 3)],
  348. [('ShearX', 0.2, 9), ('Rotate', 0.6, 8)],
  349. [('Color', 0.6, 1), ('Equalize', 1.0, 2)],
  350. [('Invert', 0.4, 9), ('Rotate', 0.6, 0)],
  351. [('Equalize', 1.0, 9), ('ShearY', 0.6, 3)],
  352. [('Color', 0.4, 7), ('Equalize', 0.6, 0)],
  353. [('PosterizeIncreasing', 0.4, 6), ('AutoContrast', 0.4, 7)],
  354. [('Solarize', 0.6, 8), ('Color', 0.6, 9)],
  355. [('Solarize', 0.2, 4), ('Rotate', 0.8, 9)],
  356. [('Rotate', 1.0, 7), ('TranslateYRel', 0.8, 9)],
  357. [('ShearX', 0.0, 0), ('Solarize', 0.8, 4)],
  358. [('ShearY', 0.8, 0), ('Color', 0.6, 4)],
  359. [('Color', 1.0, 0), ('Rotate', 0.6, 2)],
  360. [('Equalize', 0.8, 4), ('Equalize', 0.0, 8)],
  361. [('Equalize', 1.0, 4), ('AutoContrast', 0.6, 2)],
  362. [('ShearY', 0.4, 7), ('SolarizeAdd', 0.6, 7)],
  363. [('PosterizeIncreasing', 0.8, 2), ('Solarize', 0.6, 10)],
  364. [('Solarize', 0.6, 8), ('Equalize', 0.6, 1)],
  365. [('Color', 0.8, 6), ('Rotate', 0.4, 5)],
  366. ]
  367. pc = [[AugmentOp(*a, hparams=hparams) for a in sp] for sp in policy]
  368. return pc
  369. def auto_augment_policy_original(hparams):
  370. # ImageNet policy from https://arxiv.org/abs/1805.09501
  371. policy = [
  372. [('PosterizeOriginal', 0.4, 8), ('Rotate', 0.6, 9)],
  373. [('Solarize', 0.6, 5), ('AutoContrast', 0.6, 5)],
  374. [('Equalize', 0.8, 8), ('Equalize', 0.6, 3)],
  375. [('PosterizeOriginal', 0.6, 7), ('PosterizeOriginal', 0.6, 6)],
  376. [('Equalize', 0.4, 7), ('Solarize', 0.2, 4)],
  377. [('Equalize', 0.4, 4), ('Rotate', 0.8, 8)],
  378. [('Solarize', 0.6, 3), ('Equalize', 0.6, 7)],
  379. [('PosterizeOriginal', 0.8, 5), ('Equalize', 1.0, 2)],
  380. [('Rotate', 0.2, 3), ('Solarize', 0.6, 8)],
  381. [('Equalize', 0.6, 8), ('PosterizeOriginal', 0.4, 6)],
  382. [('Rotate', 0.8, 8), ('Color', 0.4, 0)],
  383. [('Rotate', 0.4, 9), ('Equalize', 0.6, 2)],
  384. [('Equalize', 0.0, 7), ('Equalize', 0.8, 8)],
  385. [('Invert', 0.6, 4), ('Equalize', 1.0, 8)],
  386. [('Color', 0.6, 4), ('Contrast', 1.0, 8)],
  387. [('Rotate', 0.8, 8), ('Color', 1.0, 2)],
  388. [('Color', 0.8, 8), ('Solarize', 0.8, 7)],
  389. [('Sharpness', 0.4, 7), ('Invert', 0.6, 8)],
  390. [('ShearX', 0.6, 5), ('Equalize', 1.0, 9)],
  391. [('Color', 0.4, 0), ('Equalize', 0.6, 3)],
  392. [('Equalize', 0.4, 7), ('Solarize', 0.2, 4)],
  393. [('Solarize', 0.6, 5), ('AutoContrast', 0.6, 5)],
  394. [('Invert', 0.6, 4), ('Equalize', 1.0, 8)],
  395. [('Color', 0.6, 4), ('Contrast', 1.0, 8)],
  396. [('Equalize', 0.8, 8), ('Equalize', 0.6, 3)],
  397. ]
  398. pc = [[AugmentOp(*a, hparams=hparams) for a in sp] for sp in policy]
  399. return pc
  400. def auto_augment_policy_originalr(hparams):
  401. # ImageNet policy from https://arxiv.org/abs/1805.09501 with research posterize variation
  402. policy = [
  403. [('PosterizeIncreasing', 0.4, 8), ('Rotate', 0.6, 9)],
  404. [('Solarize', 0.6, 5), ('AutoContrast', 0.6, 5)],
  405. [('Equalize', 0.8, 8), ('Equalize', 0.6, 3)],
  406. [('PosterizeIncreasing', 0.6, 7), ('PosterizeIncreasing', 0.6, 6)],
  407. [('Equalize', 0.4, 7), ('Solarize', 0.2, 4)],
  408. [('Equalize', 0.4, 4), ('Rotate', 0.8, 8)],
  409. [('Solarize', 0.6, 3), ('Equalize', 0.6, 7)],
  410. [('PosterizeIncreasing', 0.8, 5), ('Equalize', 1.0, 2)],
  411. [('Rotate', 0.2, 3), ('Solarize', 0.6, 8)],
  412. [('Equalize', 0.6, 8), ('PosterizeIncreasing', 0.4, 6)],
  413. [('Rotate', 0.8, 8), ('Color', 0.4, 0)],
  414. [('Rotate', 0.4, 9), ('Equalize', 0.6, 2)],
  415. [('Equalize', 0.0, 7), ('Equalize', 0.8, 8)],
  416. [('Invert', 0.6, 4), ('Equalize', 1.0, 8)],
  417. [('Color', 0.6, 4), ('Contrast', 1.0, 8)],
  418. [('Rotate', 0.8, 8), ('Color', 1.0, 2)],
  419. [('Color', 0.8, 8), ('Solarize', 0.8, 7)],
  420. [('Sharpness', 0.4, 7), ('Invert', 0.6, 8)],
  421. [('ShearX', 0.6, 5), ('Equalize', 1.0, 9)],
  422. [('Color', 0.4, 0), ('Equalize', 0.6, 3)],
  423. [('Equalize', 0.4, 7), ('Solarize', 0.2, 4)],
  424. [('Solarize', 0.6, 5), ('AutoContrast', 0.6, 5)],
  425. [('Invert', 0.6, 4), ('Equalize', 1.0, 8)],
  426. [('Color', 0.6, 4), ('Contrast', 1.0, 8)],
  427. [('Equalize', 0.8, 8), ('Equalize', 0.6, 3)],
  428. ]
  429. pc = [[AugmentOp(*a, hparams=hparams) for a in sp] for sp in policy]
  430. return pc
  431. def auto_augment_policy_3a(hparams):
  432. policy = [
  433. [('Solarize', 1.0, 5)], # 128 solarize threshold @ 5 magnitude
  434. [('Desaturate', 1.0, 10)], # grayscale at 10 magnitude
  435. [('GaussianBlurRand', 1.0, 10)],
  436. ]
  437. pc = [[AugmentOp(*a, hparams=hparams) for a in sp] for sp in policy]
  438. return pc
  439. def auto_augment_policy(name='v0', hparams=None):
  440. hparams = hparams or _HPARAMS_DEFAULT
  441. if name == 'original':
  442. return auto_augment_policy_original(hparams)
  443. if name == 'originalr':
  444. return auto_augment_policy_originalr(hparams)
  445. if name == 'v0':
  446. return auto_augment_policy_v0(hparams)
  447. if name == 'v0r':
  448. return auto_augment_policy_v0r(hparams)
  449. if name == '3a':
  450. return auto_augment_policy_3a(hparams)
  451. assert False, f'Unknown AA policy {name}'
  452. class AutoAugment:
  453. def __init__(self, policy):
  454. self.policy = policy
  455. def __call__(self, img):
  456. sub_policy = random.choice(self.policy)
  457. for op in sub_policy:
  458. img = op(img)
  459. return img
  460. def __repr__(self):
  461. fs = self.__class__.__name__ + '(policy='
  462. for p in self.policy:
  463. fs += '\n\t['
  464. fs += ', '.join([str(op) for op in p])
  465. fs += ']'
  466. fs += ')'
  467. return fs
  468. def auto_augment_transform(config_str: str, hparams: Optional[Dict] = None):
  469. """ Create a AutoAugment transform
  470. Args:
  471. config_str: String defining configuration of auto augmentation. Consists of multiple sections separated by
  472. dashes ('-').
  473. The first section defines the AutoAugment policy (one of 'v0', 'v0r', 'original', 'originalr').
  474. While the remaining sections define other arguments
  475. * 'mstd' - float std deviation of magnitude noise applied
  476. hparams: Other hparams (kwargs) for the AutoAugmentation scheme
  477. Returns:
  478. A PyTorch compatible Transform
  479. Examples::
  480. 'original-mstd0.5' results in AutoAugment with original policy, magnitude_std 0.5
  481. """
  482. config = config_str.split('-')
  483. policy_name = config[0]
  484. config = config[1:]
  485. for c in config:
  486. cs = re.split(r'(\d.*)', c)
  487. if len(cs) < 2:
  488. continue
  489. key, val = cs[:2]
  490. if key == 'mstd':
  491. # noise param injected via hparams for now
  492. hparams.setdefault('magnitude_std', float(val))
  493. else:
  494. assert False, 'Unknown AutoAugment config section'
  495. aa_policy = auto_augment_policy(policy_name, hparams=hparams)
  496. return AutoAugment(aa_policy)
  497. _RAND_TRANSFORMS = [
  498. 'AutoContrast',
  499. 'Equalize',
  500. 'Invert',
  501. 'Rotate',
  502. 'Posterize',
  503. 'Solarize',
  504. 'SolarizeAdd',
  505. 'Color',
  506. 'Contrast',
  507. 'Brightness',
  508. 'Sharpness',
  509. 'ShearX',
  510. 'ShearY',
  511. 'TranslateXRel',
  512. 'TranslateYRel',
  513. # 'Cutout' # NOTE I've implement this as random erasing separately
  514. ]
  515. _RAND_INCREASING_TRANSFORMS = [
  516. 'AutoContrast',
  517. 'Equalize',
  518. 'Invert',
  519. 'Rotate',
  520. 'PosterizeIncreasing',
  521. 'SolarizeIncreasing',
  522. 'SolarizeAdd',
  523. 'ColorIncreasing',
  524. 'ContrastIncreasing',
  525. 'BrightnessIncreasing',
  526. 'SharpnessIncreasing',
  527. 'ShearX',
  528. 'ShearY',
  529. 'TranslateXRel',
  530. 'TranslateYRel',
  531. # 'Cutout' # NOTE I've implement this as random erasing separately
  532. ]
  533. _RAND_3A = [
  534. 'SolarizeIncreasing',
  535. 'Desaturate',
  536. 'GaussianBlur',
  537. ]
  538. _RAND_WEIGHTED_3A = {
  539. 'SolarizeIncreasing': 6,
  540. 'Desaturate': 6,
  541. 'GaussianBlur': 6,
  542. 'Rotate': 3,
  543. 'ShearX': 2,
  544. 'ShearY': 2,
  545. 'PosterizeIncreasing': 1,
  546. 'AutoContrast': 1,
  547. 'ColorIncreasing': 1,
  548. 'SharpnessIncreasing': 1,
  549. 'ContrastIncreasing': 1,
  550. 'BrightnessIncreasing': 1,
  551. 'Equalize': 1,
  552. 'Invert': 1,
  553. }
  554. # These experimental weights are based loosely on the relative improvements mentioned in paper.
  555. # They may not result in increased performance, but could likely be tuned to so.
  556. _RAND_WEIGHTED_0 = {
  557. 'Rotate': 3,
  558. 'ShearX': 2,
  559. 'ShearY': 2,
  560. 'TranslateXRel': 1,
  561. 'TranslateYRel': 1,
  562. 'ColorIncreasing': .25,
  563. 'SharpnessIncreasing': 0.25,
  564. 'AutoContrast': 0.25,
  565. 'SolarizeIncreasing': .05,
  566. 'SolarizeAdd': .05,
  567. 'ContrastIncreasing': .05,
  568. 'BrightnessIncreasing': .05,
  569. 'Equalize': .05,
  570. 'PosterizeIncreasing': 0.05,
  571. 'Invert': 0.05,
  572. }
  573. def _get_weighted_transforms(transforms: Dict):
  574. transforms, probs = list(zip(*transforms.items()))
  575. probs = np.array(probs)
  576. probs = probs / np.sum(probs)
  577. return transforms, probs
  578. def rand_augment_choices(name: str, increasing=True):
  579. if name == 'weights':
  580. return _RAND_WEIGHTED_0
  581. if name == '3aw':
  582. return _RAND_WEIGHTED_3A
  583. if name == '3a':
  584. return _RAND_3A
  585. return _RAND_INCREASING_TRANSFORMS if increasing else _RAND_TRANSFORMS
  586. def rand_augment_ops(
  587. magnitude: Union[int, float] = 10,
  588. prob: float = 0.5,
  589. hparams: Optional[Dict] = None,
  590. transforms: Optional[Union[Dict, List]] = None,
  591. ):
  592. hparams = hparams or _HPARAMS_DEFAULT
  593. transforms = transforms or _RAND_TRANSFORMS
  594. return [AugmentOp(
  595. name, prob=prob, magnitude=magnitude, hparams=hparams) for name in transforms]
  596. class RandAugment:
  597. def __init__(self, ops, num_layers=2, choice_weights=None):
  598. self.ops = ops
  599. self.num_layers = num_layers
  600. self.choice_weights = choice_weights
  601. def __call__(self, img):
  602. # no replacement when using weighted choice
  603. ops = np.random.choice(
  604. self.ops,
  605. self.num_layers,
  606. replace=self.choice_weights is None,
  607. p=self.choice_weights,
  608. )
  609. for op in ops:
  610. img = op(img)
  611. return img
  612. def __repr__(self):
  613. fs = self.__class__.__name__ + f'(n={self.num_layers}, ops='
  614. for op in self.ops:
  615. fs += f'\n\t{op}'
  616. fs += ')'
  617. return fs
  618. def rand_augment_transform(
  619. config_str: str,
  620. hparams: Optional[Dict] = None,
  621. transforms: Optional[Union[str, Dict, List]] = None,
  622. ):
  623. """ Create a RandAugment transform
  624. Args:
  625. config_str (str): String defining configuration of random augmentation. Consists of multiple sections separated
  626. by dashes ('-'). The first section defines the specific variant of rand augment (currently only 'rand').
  627. The remaining sections, not order specific determine
  628. * 'm' - integer magnitude of rand augment
  629. * 'n' - integer num layers (number of transform ops selected per image)
  630. * 'p' - float probability of applying each layer (default 0.5)
  631. * 'mstd' - float std deviation of magnitude noise applied, or uniform sampling if infinity (or > 100)
  632. * 'mmax' - set upper bound for magnitude to something other than default of _LEVEL_DENOM (10)
  633. * 'inc' - integer (bool), use augmentations that increase in severity with magnitude (default: 0)
  634. * 't' - str name of transform set to use
  635. hparams (dict): Other hparams (kwargs) for the RandAugmentation scheme
  636. Returns:
  637. A PyTorch compatible Transform
  638. Examples::
  639. 'rand-m9-n3-mstd0.5' results in RandAugment with magnitude 9, num_layers 3, magnitude_std 0.5
  640. 'rand-mstd1-tweights' results in mag std 1.0, weighted transforms, default mag of 10 and num_layers 2
  641. """
  642. magnitude = _LEVEL_DENOM # default to _LEVEL_DENOM for magnitude (currently 10)
  643. num_layers = 2 # default to 2 ops per image
  644. increasing = False
  645. prob = 0.5
  646. config = config_str.split('-')
  647. assert config[0] == 'rand'
  648. config = config[1:]
  649. for c in config:
  650. if c.startswith('t'):
  651. # NOTE old 'w' key was removed, 'w0' is not equivalent to 'tweights'
  652. val = str(c[1:])
  653. if transforms is None:
  654. transforms = val
  655. else:
  656. # numeric options
  657. cs = re.split(r'(\d.*)', c)
  658. if len(cs) < 2:
  659. continue
  660. key, val = cs[:2]
  661. if key == 'mstd':
  662. # noise param / randomization of magnitude values
  663. mstd = float(val)
  664. if mstd > 100:
  665. # use uniform sampling in 0 to magnitude if mstd is > 100
  666. mstd = float('inf')
  667. hparams.setdefault('magnitude_std', mstd)
  668. elif key == 'mmax':
  669. # clip magnitude between [0, mmax] instead of default [0, _LEVEL_DENOM]
  670. hparams.setdefault('magnitude_max', int(val))
  671. elif key == 'inc':
  672. if bool(val):
  673. increasing = True
  674. elif key == 'm':
  675. magnitude = int(val)
  676. elif key == 'n':
  677. num_layers = int(val)
  678. elif key == 'p':
  679. prob = float(val)
  680. else:
  681. assert False, 'Unknown RandAugment config section'
  682. if isinstance(transforms, str):
  683. transforms = rand_augment_choices(transforms, increasing=increasing)
  684. elif transforms is None:
  685. transforms = _RAND_INCREASING_TRANSFORMS if increasing else _RAND_TRANSFORMS
  686. choice_weights = None
  687. if isinstance(transforms, Dict):
  688. transforms, choice_weights = _get_weighted_transforms(transforms)
  689. ra_ops = rand_augment_ops(magnitude=magnitude, prob=prob, hparams=hparams, transforms=transforms)
  690. return RandAugment(ra_ops, num_layers, choice_weights=choice_weights)
  691. _AUGMIX_TRANSFORMS = [
  692. 'AutoContrast',
  693. 'ColorIncreasing', # not in paper
  694. 'ContrastIncreasing', # not in paper
  695. 'BrightnessIncreasing', # not in paper
  696. 'SharpnessIncreasing', # not in paper
  697. 'Equalize',
  698. 'Rotate',
  699. 'PosterizeIncreasing',
  700. 'SolarizeIncreasing',
  701. 'ShearX',
  702. 'ShearY',
  703. 'TranslateXRel',
  704. 'TranslateYRel',
  705. ]
  706. def augmix_ops(
  707. magnitude: Union[int, float] = 10,
  708. hparams: Optional[Dict] = None,
  709. transforms: Optional[Union[str, Dict, List]] = None,
  710. ):
  711. hparams = hparams or _HPARAMS_DEFAULT
  712. transforms = transforms or _AUGMIX_TRANSFORMS
  713. return [AugmentOp(
  714. name,
  715. prob=1.0,
  716. magnitude=magnitude,
  717. hparams=hparams
  718. ) for name in transforms]
  719. class AugMixAugment:
  720. """ AugMix Transform
  721. Adapted and improved from impl here: https://github.com/google-research/augmix/blob/master/imagenet.py
  722. From paper: 'AugMix: A Simple Data Processing Method to Improve Robustness and Uncertainty -
  723. https://arxiv.org/abs/1912.02781
  724. """
  725. def __init__(self, ops, alpha=1., width=3, depth=-1, blended=False):
  726. self.ops = ops
  727. self.alpha = alpha
  728. self.width = width
  729. self.depth = depth
  730. self.blended = blended # blended mode is faster but not well tested
  731. def _calc_blended_weights(self, ws, m):
  732. ws = ws * m
  733. cump = 1.
  734. rws = []
  735. for w in ws[::-1]:
  736. alpha = w / cump
  737. cump *= (1 - alpha)
  738. rws.append(alpha)
  739. return np.array(rws[::-1], dtype=np.float32)
  740. def _apply_blended(self, img, mixing_weights, m):
  741. # This is my first crack and implementing a slightly faster mixed augmentation. Instead
  742. # of accumulating the mix for each chain in a Numpy array and then blending with original,
  743. # it recomputes the blending coefficients and applies one PIL image blend per chain.
  744. # TODO the results appear in the right ballpark but they differ by more than rounding.
  745. img_orig = img.copy()
  746. ws = self._calc_blended_weights(mixing_weights, m)
  747. for w in ws:
  748. depth = self.depth if self.depth > 0 else np.random.randint(1, 4)
  749. ops = np.random.choice(self.ops, depth, replace=True)
  750. img_aug = img_orig # no ops are in-place, deep copy not necessary
  751. for op in ops:
  752. img_aug = op(img_aug)
  753. img = Image.blend(img, img_aug, w)
  754. return img
  755. def _apply_basic(self, img, mixing_weights, m):
  756. # This is a literal adaptation of the paper/official implementation without normalizations and
  757. # PIL <-> Numpy conversions between every op. It is still quite CPU compute heavy compared to the
  758. # typical augmentation transforms, could use a GPU / Kornia implementation.
  759. img_shape = img.size[0], img.size[1], len(img.getbands())
  760. mixed = np.zeros(img_shape, dtype=np.float32)
  761. for mw in mixing_weights:
  762. depth = self.depth if self.depth > 0 else np.random.randint(1, 4)
  763. ops = np.random.choice(self.ops, depth, replace=True)
  764. img_aug = img # no ops are in-place, deep copy not necessary
  765. for op in ops:
  766. img_aug = op(img_aug)
  767. mixed += mw * np.asarray(img_aug, dtype=np.float32)
  768. np.clip(mixed, 0, 255., out=mixed)
  769. mixed = Image.fromarray(mixed.astype(np.uint8))
  770. return Image.blend(img, mixed, m)
  771. def __call__(self, img):
  772. mixing_weights = np.float32(np.random.dirichlet([self.alpha] * self.width))
  773. m = np.float32(np.random.beta(self.alpha, self.alpha))
  774. if self.blended:
  775. mixed = self._apply_blended(img, mixing_weights, m)
  776. else:
  777. mixed = self._apply_basic(img, mixing_weights, m)
  778. return mixed
  779. def __repr__(self):
  780. fs = self.__class__.__name__ + f'(alpha={self.alpha}, width={self.width}, depth={self.depth}, ops='
  781. for op in self.ops:
  782. fs += f'\n\t{op}'
  783. fs += ')'
  784. return fs
  785. def augment_and_mix_transform(config_str: str, hparams: Optional[Dict] = None):
  786. """ Create AugMix PyTorch transform
  787. Args:
  788. config_str (str): String defining configuration of random augmentation. Consists of multiple sections separated
  789. by dashes ('-'). The first section defines the specific variant of rand augment (currently only 'rand').
  790. The remaining sections, not order specific determine
  791. 'm' - integer magnitude (severity) of augmentation mix (default: 3)
  792. 'w' - integer width of augmentation chain (default: 3)
  793. 'd' - integer depth of augmentation chain (-1 is random [1, 3], default: -1)
  794. 'b' - integer (bool), blend each branch of chain into end result without a final blend, less CPU (default: 0)
  795. 'mstd' - float std deviation of magnitude noise applied (default: 0)
  796. Ex 'augmix-m5-w4-d2' results in AugMix with severity 5, chain width 4, chain depth 2
  797. hparams: Other hparams (kwargs) for the Augmentation transforms
  798. Returns:
  799. A PyTorch compatible Transform
  800. """
  801. magnitude = 3
  802. width = 3
  803. depth = -1
  804. alpha = 1.
  805. blended = False
  806. config = config_str.split('-')
  807. assert config[0] == 'augmix'
  808. config = config[1:]
  809. for c in config:
  810. cs = re.split(r'(\d.*)', c)
  811. if len(cs) < 2:
  812. continue
  813. key, val = cs[:2]
  814. if key == 'mstd':
  815. # noise param injected via hparams for now
  816. hparams.setdefault('magnitude_std', float(val))
  817. elif key == 'm':
  818. magnitude = int(val)
  819. elif key == 'w':
  820. width = int(val)
  821. elif key == 'd':
  822. depth = int(val)
  823. elif key == 'a':
  824. alpha = float(val)
  825. elif key == 'b':
  826. blended = bool(val)
  827. else:
  828. assert False, 'Unknown AugMix config section'
  829. hparams.setdefault('magnitude_std', float('inf')) # default to uniform sampling (if not set via mstd arg)
  830. ops = augmix_ops(magnitude=magnitude, hparams=hparams)
  831. return AugMixAugment(ops, alpha=alpha, width=width, depth=depth, blended=blended)