abinet_aug.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  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. """
  15. This code is refer from:
  16. https://github.com/FangShancheng/ABINet/blob/main/transforms.py
  17. """
  18. import math
  19. import numbers
  20. import random
  21. import cv2
  22. import numpy as np
  23. from paddle.vision.transforms import Compose, ColorJitter
  24. def sample_asym(magnitude, size=None):
  25. return np.random.beta(1, 4, size) * magnitude
  26. def sample_sym(magnitude, size=None):
  27. return (np.random.beta(4, 4, size=size) - 0.5) * 2 * magnitude
  28. def sample_uniform(low, high, size=None):
  29. return np.random.uniform(low, high, size=size)
  30. def get_interpolation(type='random'):
  31. if type == 'random':
  32. choice = [
  33. cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA
  34. ]
  35. interpolation = choice[random.randint(0, len(choice) - 1)]
  36. elif type == 'nearest':
  37. interpolation = cv2.INTER_NEAREST
  38. elif type == 'linear':
  39. interpolation = cv2.INTER_LINEAR
  40. elif type == 'cubic':
  41. interpolation = cv2.INTER_CUBIC
  42. elif type == 'area':
  43. interpolation = cv2.INTER_AREA
  44. else:
  45. raise TypeError(
  46. 'Interpolation types only nearest, linear, cubic, area are supported!'
  47. )
  48. return interpolation
  49. class CVRandomRotation(object):
  50. def __init__(self, degrees=15):
  51. assert isinstance(degrees,
  52. numbers.Number), "degree should be a single number."
  53. assert degrees >= 0, "degree must be positive."
  54. self.degrees = degrees
  55. @staticmethod
  56. def get_params(degrees):
  57. return sample_sym(degrees)
  58. def __call__(self, img):
  59. angle = self.get_params(self.degrees)
  60. src_h, src_w = img.shape[:2]
  61. M = cv2.getRotationMatrix2D(
  62. center=(src_w / 2, src_h / 2), angle=angle, scale=1.0)
  63. abs_cos, abs_sin = abs(M[0, 0]), abs(M[0, 1])
  64. dst_w = int(src_h * abs_sin + src_w * abs_cos)
  65. dst_h = int(src_h * abs_cos + src_w * abs_sin)
  66. M[0, 2] += (dst_w - src_w) / 2
  67. M[1, 2] += (dst_h - src_h) / 2
  68. flags = get_interpolation()
  69. return cv2.warpAffine(
  70. img,
  71. M, (dst_w, dst_h),
  72. flags=flags,
  73. borderMode=cv2.BORDER_REPLICATE)
  74. class CVRandomAffine(object):
  75. def __init__(self, degrees, translate=None, scale=None, shear=None):
  76. assert isinstance(degrees,
  77. numbers.Number), "degree should be a single number."
  78. assert degrees >= 0, "degree must be positive."
  79. self.degrees = degrees
  80. if translate is not None:
  81. assert isinstance(translate, (tuple, list)) and len(translate) == 2, \
  82. "translate should be a list or tuple and it must be of length 2."
  83. for t in translate:
  84. if not (0.0 <= t <= 1.0):
  85. raise ValueError(
  86. "translation values should be between 0 and 1")
  87. self.translate = translate
  88. if scale is not None:
  89. assert isinstance(scale, (tuple, list)) and len(scale) == 2, \
  90. "scale should be a list or tuple and it must be of length 2."
  91. for s in scale:
  92. if s <= 0:
  93. raise ValueError("scale values should be positive")
  94. self.scale = scale
  95. if shear is not None:
  96. if isinstance(shear, numbers.Number):
  97. if shear < 0:
  98. raise ValueError(
  99. "If shear is a single number, it must be positive.")
  100. self.shear = [shear]
  101. else:
  102. assert isinstance(shear, (tuple, list)) and (len(shear) == 2), \
  103. "shear should be a list or tuple and it must be of length 2."
  104. self.shear = shear
  105. else:
  106. self.shear = shear
  107. def _get_inverse_affine_matrix(self, center, angle, translate, scale,
  108. shear):
  109. # https://github.com/pytorch/vision/blob/v0.4.0/torchvision/transforms/functional.py#L717
  110. from numpy import sin, cos, tan
  111. if isinstance(shear, numbers.Number):
  112. shear = [shear, 0]
  113. if not isinstance(shear, (tuple, list)) and len(shear) == 2:
  114. raise ValueError(
  115. "Shear should be a single value or a tuple/list containing " +
  116. "two values. Got {}".format(shear))
  117. rot = math.radians(angle)
  118. sx, sy = [math.radians(s) for s in shear]
  119. cx, cy = center
  120. tx, ty = translate
  121. # RSS without scaling
  122. a = cos(rot - sy) / cos(sy)
  123. b = -cos(rot - sy) * tan(sx) / cos(sy) - sin(rot)
  124. c = sin(rot - sy) / cos(sy)
  125. d = -sin(rot - sy) * tan(sx) / cos(sy) + cos(rot)
  126. # Inverted rotation matrix with scale and shear
  127. # det([[a, b], [c, d]]) == 1, since det(rotation) = 1 and det(shear) = 1
  128. M = [d, -b, 0, -c, a, 0]
  129. M = [x / scale for x in M]
  130. # Apply inverse of translation and of center translation: RSS^-1 * C^-1 * T^-1
  131. M[2] += M[0] * (-cx - tx) + M[1] * (-cy - ty)
  132. M[5] += M[3] * (-cx - tx) + M[4] * (-cy - ty)
  133. # Apply center translation: C * RSS^-1 * C^-1 * T^-1
  134. M[2] += cx
  135. M[5] += cy
  136. return M
  137. @staticmethod
  138. def get_params(degrees, translate, scale_ranges, shears, height):
  139. angle = sample_sym(degrees)
  140. if translate is not None:
  141. max_dx = translate[0] * height
  142. max_dy = translate[1] * height
  143. translations = (np.round(sample_sym(max_dx)),
  144. np.round(sample_sym(max_dy)))
  145. else:
  146. translations = (0, 0)
  147. if scale_ranges is not None:
  148. scale = sample_uniform(scale_ranges[0], scale_ranges[1])
  149. else:
  150. scale = 1.0
  151. if shears is not None:
  152. if len(shears) == 1:
  153. shear = [sample_sym(shears[0]), 0.]
  154. elif len(shears) == 2:
  155. shear = [sample_sym(shears[0]), sample_sym(shears[1])]
  156. else:
  157. shear = 0.0
  158. return angle, translations, scale, shear
  159. def __call__(self, img):
  160. src_h, src_w = img.shape[:2]
  161. angle, translate, scale, shear = self.get_params(
  162. self.degrees, self.translate, self.scale, self.shear, src_h)
  163. M = self._get_inverse_affine_matrix((src_w / 2, src_h / 2), angle,
  164. (0, 0), scale, shear)
  165. M = np.array(M).reshape(2, 3)
  166. startpoints = [(0, 0), (src_w - 1, 0), (src_w - 1, src_h - 1),
  167. (0, src_h - 1)]
  168. project = lambda x, y, a, b, c: int(a * x + b * y + c)
  169. endpoints = [(project(x, y, *M[0]), project(x, y, *M[1]))
  170. for x, y in startpoints]
  171. rect = cv2.minAreaRect(np.array(endpoints))
  172. bbox = cv2.boxPoints(rect).astype(dtype=np.int)
  173. max_x, max_y = bbox[:, 0].max(), bbox[:, 1].max()
  174. min_x, min_y = bbox[:, 0].min(), bbox[:, 1].min()
  175. dst_w = int(max_x - min_x)
  176. dst_h = int(max_y - min_y)
  177. M[0, 2] += (dst_w - src_w) / 2
  178. M[1, 2] += (dst_h - src_h) / 2
  179. # add translate
  180. dst_w += int(abs(translate[0]))
  181. dst_h += int(abs(translate[1]))
  182. if translate[0] < 0: M[0, 2] += abs(translate[0])
  183. if translate[1] < 0: M[1, 2] += abs(translate[1])
  184. flags = get_interpolation()
  185. return cv2.warpAffine(
  186. img,
  187. M, (dst_w, dst_h),
  188. flags=flags,
  189. borderMode=cv2.BORDER_REPLICATE)
  190. class CVRandomPerspective(object):
  191. def __init__(self, distortion=0.5):
  192. self.distortion = distortion
  193. def get_params(self, width, height, distortion):
  194. offset_h = sample_asym(
  195. distortion * height / 2, size=4).astype(dtype=np.int)
  196. offset_w = sample_asym(
  197. distortion * width / 2, size=4).astype(dtype=np.int)
  198. topleft = (offset_w[0], offset_h[0])
  199. topright = (width - 1 - offset_w[1], offset_h[1])
  200. botright = (width - 1 - offset_w[2], height - 1 - offset_h[2])
  201. botleft = (offset_w[3], height - 1 - offset_h[3])
  202. startpoints = [(0, 0), (width - 1, 0), (width - 1, height - 1),
  203. (0, height - 1)]
  204. endpoints = [topleft, topright, botright, botleft]
  205. return np.array(
  206. startpoints, dtype=np.float32), np.array(
  207. endpoints, dtype=np.float32)
  208. def __call__(self, img):
  209. height, width = img.shape[:2]
  210. startpoints, endpoints = self.get_params(width, height, self.distortion)
  211. M = cv2.getPerspectiveTransform(startpoints, endpoints)
  212. # TODO: more robust way to crop image
  213. rect = cv2.minAreaRect(endpoints)
  214. bbox = cv2.boxPoints(rect).astype(dtype=np.int)
  215. max_x, max_y = bbox[:, 0].max(), bbox[:, 1].max()
  216. min_x, min_y = bbox[:, 0].min(), bbox[:, 1].min()
  217. min_x, min_y = max(min_x, 0), max(min_y, 0)
  218. flags = get_interpolation()
  219. img = cv2.warpPerspective(
  220. img,
  221. M, (max_x, max_y),
  222. flags=flags,
  223. borderMode=cv2.BORDER_REPLICATE)
  224. img = img[min_y:, min_x:]
  225. return img
  226. class CVRescale(object):
  227. def __init__(self, factor=4, base_size=(128, 512)):
  228. """ Define image scales using gaussian pyramid and rescale image to target scale.
  229. Args:
  230. factor: the decayed factor from base size, factor=4 keeps target scale by default.
  231. base_size: base size the build the bottom layer of pyramid
  232. """
  233. if isinstance(factor, numbers.Number):
  234. self.factor = round(sample_uniform(0, factor))
  235. elif isinstance(factor, (tuple, list)) and len(factor) == 2:
  236. self.factor = round(sample_uniform(factor[0], factor[1]))
  237. else:
  238. raise Exception('factor must be number or list with length 2')
  239. # assert factor is valid
  240. self.base_h, self.base_w = base_size[:2]
  241. def __call__(self, img):
  242. if self.factor == 0: return img
  243. src_h, src_w = img.shape[:2]
  244. cur_w, cur_h = self.base_w, self.base_h
  245. scale_img = cv2.resize(
  246. img, (cur_w, cur_h), interpolation=get_interpolation())
  247. for _ in range(self.factor):
  248. scale_img = cv2.pyrDown(scale_img)
  249. scale_img = cv2.resize(
  250. scale_img, (src_w, src_h), interpolation=get_interpolation())
  251. return scale_img
  252. class CVGaussianNoise(object):
  253. def __init__(self, mean=0, var=20):
  254. self.mean = mean
  255. if isinstance(var, numbers.Number):
  256. self.var = max(int(sample_asym(var)), 1)
  257. elif isinstance(var, (tuple, list)) and len(var) == 2:
  258. self.var = int(sample_uniform(var[0], var[1]))
  259. else:
  260. raise Exception('degree must be number or list with length 2')
  261. def __call__(self, img):
  262. noise = np.random.normal(self.mean, self.var**0.5, img.shape)
  263. img = np.clip(img + noise, 0, 255).astype(np.uint8)
  264. return img
  265. class CVMotionBlur(object):
  266. def __init__(self, degrees=12, angle=90):
  267. if isinstance(degrees, numbers.Number):
  268. self.degree = max(int(sample_asym(degrees)), 1)
  269. elif isinstance(degrees, (tuple, list)) and len(degrees) == 2:
  270. self.degree = int(sample_uniform(degrees[0], degrees[1]))
  271. else:
  272. raise Exception('degree must be number or list with length 2')
  273. self.angle = sample_uniform(-angle, angle)
  274. def __call__(self, img):
  275. M = cv2.getRotationMatrix2D((self.degree // 2, self.degree // 2),
  276. self.angle, 1)
  277. motion_blur_kernel = np.zeros((self.degree, self.degree))
  278. motion_blur_kernel[self.degree // 2, :] = 1
  279. motion_blur_kernel = cv2.warpAffine(motion_blur_kernel, M,
  280. (self.degree, self.degree))
  281. motion_blur_kernel = motion_blur_kernel / self.degree
  282. img = cv2.filter2D(img, -1, motion_blur_kernel)
  283. img = np.clip(img, 0, 255).astype(np.uint8)
  284. return img
  285. class CVGeometry(object):
  286. def __init__(self,
  287. degrees=15,
  288. translate=(0.3, 0.3),
  289. scale=(0.5, 2.),
  290. shear=(45, 15),
  291. distortion=0.5,
  292. p=0.5):
  293. self.p = p
  294. type_p = random.random()
  295. if type_p < 0.33:
  296. self.transforms = CVRandomRotation(degrees=degrees)
  297. elif type_p < 0.66:
  298. self.transforms = CVRandomAffine(
  299. degrees=degrees, translate=translate, scale=scale, shear=shear)
  300. else:
  301. self.transforms = CVRandomPerspective(distortion=distortion)
  302. def __call__(self, img):
  303. if random.random() < self.p:
  304. return self.transforms(img)
  305. else:
  306. return img
  307. class CVDeterioration(object):
  308. def __init__(self, var, degrees, factor, p=0.5):
  309. self.p = p
  310. transforms = []
  311. if var is not None:
  312. transforms.append(CVGaussianNoise(var=var))
  313. if degrees is not None:
  314. transforms.append(CVMotionBlur(degrees=degrees))
  315. if factor is not None:
  316. transforms.append(CVRescale(factor=factor))
  317. random.shuffle(transforms)
  318. transforms = Compose(transforms)
  319. self.transforms = transforms
  320. def __call__(self, img):
  321. if random.random() < self.p:
  322. return self.transforms(img)
  323. else:
  324. return img
  325. class CVColorJitter(object):
  326. def __init__(self,
  327. brightness=0.5,
  328. contrast=0.5,
  329. saturation=0.5,
  330. hue=0.1,
  331. p=0.5):
  332. self.p = p
  333. self.transforms = ColorJitter(
  334. brightness=brightness,
  335. contrast=contrast,
  336. saturation=saturation,
  337. hue=hue)
  338. def __call__(self, img):
  339. if random.random() < self.p: return self.transforms(img)
  340. else: return img
  341. class SVTRDeterioration(object):
  342. def __init__(self, var, degrees, factor, p=0.5):
  343. self.p = p
  344. transforms = []
  345. if var is not None:
  346. transforms.append(CVGaussianNoise(var=var))
  347. if degrees is not None:
  348. transforms.append(CVMotionBlur(degrees=degrees))
  349. if factor is not None:
  350. transforms.append(CVRescale(factor=factor))
  351. self.transforms = transforms
  352. def __call__(self, img):
  353. if random.random() < self.p:
  354. random.shuffle(self.transforms)
  355. transforms = Compose(self.transforms)
  356. return transforms(img)
  357. else:
  358. return img
  359. class SVTRGeometry(object):
  360. def __init__(self,
  361. aug_type=0,
  362. degrees=15,
  363. translate=(0.3, 0.3),
  364. scale=(0.5, 2.),
  365. shear=(45, 15),
  366. distortion=0.5,
  367. p=0.5):
  368. self.aug_type = aug_type
  369. self.p = p
  370. self.transforms = []
  371. self.transforms.append(CVRandomRotation(degrees=degrees))
  372. self.transforms.append(CVRandomAffine(
  373. degrees=degrees, translate=translate, scale=scale, shear=shear))
  374. self.transforms.append(CVRandomPerspective(distortion=distortion))
  375. def __call__(self, img):
  376. if random.random() < self.p:
  377. if self.aug_type:
  378. random.shuffle(self.transforms)
  379. transforms = Compose(self.transforms[:random.randint(1, 3)])
  380. img = transforms(img)
  381. else:
  382. img = self.transforms[random.randint(0, 2)](img)
  383. return img
  384. else:
  385. return img