abinet_aug.py 18 KB

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