randaugment.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. import cv2
  2. import numpy as np
  3. ## aug functions
  4. def identity_func(img):
  5. return img
  6. def autocontrast_func(img, cutoff=0):
  7. '''
  8. same output as PIL.ImageOps.autocontrast
  9. '''
  10. n_bins = 256
  11. def tune_channel(ch):
  12. n = ch.size
  13. cut = cutoff * n // 100
  14. if cut == 0:
  15. high, low = ch.max(), ch.min()
  16. else:
  17. hist = cv2.calcHist([ch], [0], None, [n_bins], [0, n_bins])
  18. low = np.argwhere(np.cumsum(hist) > cut)
  19. low = 0 if low.shape[0] == 0 else low[0]
  20. high = np.argwhere(np.cumsum(hist[::-1]) > cut)
  21. high = n_bins - 1 if high.shape[0] == 0 else n_bins - 1 - high[0]
  22. if high <= low:
  23. table = np.arange(n_bins)
  24. else:
  25. scale = (n_bins - 1) / (high - low)
  26. offset = -low * scale
  27. table = np.arange(n_bins) * scale + offset
  28. table[table < 0] = 0
  29. table[table > n_bins - 1] = n_bins - 1
  30. table = table.clip(0, 255).astype(np.uint8)
  31. return table[ch]
  32. channels = [tune_channel(ch) for ch in cv2.split(img)]
  33. out = cv2.merge(channels)
  34. return out
  35. def equalize_func(img):
  36. '''
  37. same output as PIL.ImageOps.equalize
  38. PIL's implementation is different from cv2.equalize
  39. '''
  40. n_bins = 256
  41. def tune_channel(ch):
  42. hist = cv2.calcHist([ch], [0], None, [n_bins], [0, n_bins])
  43. non_zero_hist = hist[hist != 0].reshape(-1)
  44. step = np.sum(non_zero_hist[:-1]) // (n_bins - 1)
  45. if step == 0: return ch
  46. n = np.empty_like(hist)
  47. n[0] = step // 2
  48. n[1:] = hist[:-1]
  49. table = (np.cumsum(n) // step).clip(0, 255).astype(np.uint8)
  50. return table[ch]
  51. channels = [tune_channel(ch) for ch in cv2.split(img)]
  52. out = cv2.merge(channels)
  53. return out
  54. def rotate_func(img, degree, fill=(0, 0, 0)):
  55. '''
  56. like PIL, rotate by degree, not radians
  57. '''
  58. H, W = img.shape[0], img.shape[1]
  59. center = W / 2, H / 2
  60. M = cv2.getRotationMatrix2D(center, degree, 1)
  61. out = cv2.warpAffine(img, M, (W, H), borderValue=fill)
  62. return out
  63. def solarize_func(img, thresh=128):
  64. '''
  65. same output as PIL.ImageOps.posterize
  66. '''
  67. table = np.array([el if el < thresh else 255 - el for el in range(256)])
  68. table = table.clip(0, 255).astype(np.uint8)
  69. out = table[img]
  70. return out
  71. def color_func(img, factor):
  72. '''
  73. same output as PIL.ImageEnhance.Color
  74. '''
  75. ## implementation according to PIL definition, quite slow
  76. # degenerate = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)[:, :, np.newaxis]
  77. # out = blend(degenerate, img, factor)
  78. # M = (
  79. # np.eye(3) * factor
  80. # + np.float32([0.114, 0.587, 0.299]).reshape(3, 1) * (1. - factor)
  81. # )[np.newaxis, np.newaxis, :]
  82. M = (
  83. np.float32([
  84. [0.886, -0.114, -0.114],
  85. [-0.587, 0.413, -0.587],
  86. [-0.299, -0.299, 0.701]]) * factor
  87. + np.float32([[0.114], [0.587], [0.299]])
  88. )
  89. out = np.matmul(img, M).clip(0, 255).astype(np.uint8)
  90. return out
  91. def contrast_func(img, factor):
  92. """
  93. same output as PIL.ImageEnhance.Contrast
  94. """
  95. mean = np.sum(np.mean(img, axis=(0, 1)) * np.array([0.114, 0.587, 0.299]))
  96. table = np.array([(
  97. el - mean) * factor + mean
  98. for el in range(256)
  99. ]).clip(0, 255).astype(np.uint8)
  100. out = table[img]
  101. return out
  102. def brightness_func(img, factor):
  103. '''
  104. same output as PIL.ImageEnhance.Contrast
  105. '''
  106. table = (np.arange(256, dtype=np.float32) * factor).clip(0, 255).astype(np.uint8)
  107. out = table[img]
  108. return out
  109. def sharpness_func(img, factor):
  110. '''
  111. The differences the this result and PIL are all on the 4 boundaries, the center
  112. areas are same
  113. '''
  114. kernel = np.ones((3, 3), dtype=np.float32)
  115. kernel[1][1] = 5
  116. kernel /= 13
  117. degenerate = cv2.filter2D(img, -1, kernel)
  118. if factor == 0.0:
  119. out = degenerate
  120. elif factor == 1.0:
  121. out = img
  122. else:
  123. out = img.astype(np.float32)
  124. degenerate = degenerate.astype(np.float32)[1:-1, 1:-1, :]
  125. out[1:-1, 1:-1, :] = degenerate + factor * (out[1:-1, 1:-1, :] - degenerate)
  126. out = out.astype(np.uint8)
  127. return out
  128. def shear_x_func(img, factor, fill=(0, 0, 0)):
  129. H, W = img.shape[0], img.shape[1]
  130. M = np.float32([[1, factor, 0], [0, 1, 0]])
  131. out = cv2.warpAffine(img, M, (W, H), borderValue=fill, flags=cv2.INTER_LINEAR).astype(np.uint8)
  132. return out
  133. def translate_x_func(img, offset, fill=(0, 0, 0)):
  134. '''
  135. same output as PIL.Image.transform
  136. '''
  137. H, W = img.shape[0], img.shape[1]
  138. M = np.float32([[1, 0, -offset], [0, 1, 0]])
  139. out = cv2.warpAffine(img, M, (W, H), borderValue=fill, flags=cv2.INTER_LINEAR).astype(np.uint8)
  140. return out
  141. def translate_y_func(img, offset, fill=(0, 0, 0)):
  142. '''
  143. same output as PIL.Image.transform
  144. '''
  145. H, W = img.shape[0], img.shape[1]
  146. M = np.float32([[1, 0, 0], [0, 1, -offset]])
  147. out = cv2.warpAffine(img, M, (W, H), borderValue=fill, flags=cv2.INTER_LINEAR).astype(np.uint8)
  148. return out
  149. def posterize_func(img, bits):
  150. '''
  151. same output as PIL.ImageOps.posterize
  152. '''
  153. out = np.bitwise_and(img, np.uint8(255 << (8 - bits)))
  154. return out
  155. def shear_y_func(img, factor, fill=(0, 0, 0)):
  156. H, W = img.shape[0], img.shape[1]
  157. M = np.float32([[1, 0, 0], [factor, 1, 0]])
  158. out = cv2.warpAffine(img, M, (W, H), borderValue=fill, flags=cv2.INTER_LINEAR).astype(np.uint8)
  159. return out
  160. def cutout_func(img, pad_size, replace=(0, 0, 0)):
  161. replace = np.array(replace, dtype=np.uint8)
  162. H, W = img.shape[0], img.shape[1]
  163. rh, rw = np.random.random(2)
  164. pad_size = pad_size // 2
  165. ch, cw = int(rh * H), int(rw * W)
  166. x1, x2 = max(ch - pad_size, 0), min(ch + pad_size, H)
  167. y1, y2 = max(cw - pad_size, 0), min(cw + pad_size, W)
  168. out = img.copy()
  169. out[x1:x2, y1:y2, :] = replace
  170. return out
  171. ### level to args
  172. def enhance_level_to_args(MAX_LEVEL):
  173. def level_to_args(level):
  174. return ((level / MAX_LEVEL) * 1.8 + 0.1,)
  175. return level_to_args
  176. def shear_level_to_args(MAX_LEVEL, replace_value):
  177. def level_to_args(level):
  178. level = (level / MAX_LEVEL) * 0.3
  179. if np.random.random() > 0.5: level = -level
  180. return (level, replace_value)
  181. return level_to_args
  182. def translate_level_to_args(translate_const, MAX_LEVEL, replace_value):
  183. def level_to_args(level):
  184. level = (level / MAX_LEVEL) * float(translate_const)
  185. if np.random.random() > 0.5: level = -level
  186. return (level, replace_value)
  187. return level_to_args
  188. def cutout_level_to_args(cutout_const, MAX_LEVEL, replace_value):
  189. def level_to_args(level):
  190. level = int((level / MAX_LEVEL) * cutout_const)
  191. return (level, replace_value)
  192. return level_to_args
  193. def solarize_level_to_args(MAX_LEVEL):
  194. def level_to_args(level):
  195. level = int((level / MAX_LEVEL) * 256)
  196. return (level, )
  197. return level_to_args
  198. def none_level_to_args(level):
  199. return ()
  200. def posterize_level_to_args(MAX_LEVEL):
  201. def level_to_args(level):
  202. level = int((level / MAX_LEVEL) * 4)
  203. return (level, )
  204. return level_to_args
  205. def rotate_level_to_args(MAX_LEVEL, replace_value):
  206. def level_to_args(level):
  207. level = (level / MAX_LEVEL) * 30
  208. if np.random.random() < 0.5:
  209. level = -level
  210. return (level, replace_value)
  211. return level_to_args
  212. func_dict = {
  213. 'Identity': identity_func,
  214. 'AutoContrast': autocontrast_func,
  215. 'Equalize': equalize_func,
  216. 'Rotate': rotate_func,
  217. 'Solarize': solarize_func,
  218. 'Color': color_func,
  219. 'Contrast': contrast_func,
  220. 'Brightness': brightness_func,
  221. 'Sharpness': sharpness_func,
  222. 'ShearX': shear_x_func,
  223. 'TranslateX': translate_x_func,
  224. 'TranslateY': translate_y_func,
  225. 'Posterize': posterize_func,
  226. 'ShearY': shear_y_func,
  227. }
  228. translate_const = 10
  229. MAX_LEVEL = 10
  230. replace_value = (128, 128, 128)
  231. arg_dict = {
  232. 'Identity': none_level_to_args,
  233. 'AutoContrast': none_level_to_args,
  234. 'Equalize': none_level_to_args,
  235. 'Rotate': rotate_level_to_args(MAX_LEVEL, replace_value),
  236. 'Solarize': solarize_level_to_args(MAX_LEVEL),
  237. 'Color': enhance_level_to_args(MAX_LEVEL),
  238. 'Contrast': enhance_level_to_args(MAX_LEVEL),
  239. 'Brightness': enhance_level_to_args(MAX_LEVEL),
  240. 'Sharpness': enhance_level_to_args(MAX_LEVEL),
  241. 'ShearX': shear_level_to_args(MAX_LEVEL, replace_value),
  242. 'TranslateX': translate_level_to_args(
  243. translate_const, MAX_LEVEL, replace_value
  244. ),
  245. 'TranslateY': translate_level_to_args(
  246. translate_const, MAX_LEVEL, replace_value
  247. ),
  248. 'Posterize': posterize_level_to_args(MAX_LEVEL),
  249. 'ShearY': shear_level_to_args(MAX_LEVEL, replace_value),
  250. }
  251. class RandomAugment(object):
  252. def __init__(self, N=2, M=10, isPIL=False, augs=[]):
  253. self.N = N
  254. self.M = M
  255. self.isPIL = isPIL
  256. if augs:
  257. self.augs = augs
  258. else:
  259. self.augs = list(arg_dict.keys())
  260. def get_random_ops(self):
  261. sampled_ops = np.random.choice(self.augs, self.N)
  262. return [(op, 0.5, self.M) for op in sampled_ops]
  263. def __call__(self, img):
  264. if self.isPIL:
  265. img = np.array(img)
  266. ops = self.get_random_ops()
  267. for name, prob, level in ops:
  268. if np.random.random() > prob:
  269. continue
  270. args = arg_dict[name](level)
  271. img = func_dict[name](img, *args)
  272. return img
  273. if __name__ == '__main__':
  274. a = RandomAugment()
  275. img = np.random.randn(32, 32, 3)
  276. a(img)