rec_img_aug.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  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. import math
  15. import cv2
  16. import numpy as np
  17. import random
  18. from .text_image_aug import tia_perspective, tia_stretch, tia_distort
  19. class RecAug(object):
  20. def __init__(self, use_tia=True, aug_prob=0.4, **kwargs):
  21. self.use_tia = use_tia
  22. self.aug_prob = aug_prob
  23. def __call__(self, data):
  24. img = data['image']
  25. img = warp(img, 10, self.use_tia, self.aug_prob)
  26. data['image'] = img
  27. return data
  28. class ClsResizeImg(object):
  29. def __init__(self, image_shape, **kwargs):
  30. self.image_shape = image_shape
  31. def __call__(self, data):
  32. img = data['image']
  33. norm_img = resize_norm_img(img, self.image_shape)
  34. data['image'] = norm_img
  35. return data
  36. class RecResizeImg(object):
  37. def __init__(self,
  38. image_shape,
  39. infer_mode=False,
  40. character_type='ch',
  41. **kwargs):
  42. self.image_shape = image_shape
  43. self.infer_mode = infer_mode
  44. self.character_type = character_type
  45. def __call__(self, data):
  46. img = data['image']
  47. if self.infer_mode and self.character_type == "ch":
  48. norm_img = resize_norm_img_chinese(img, self.image_shape)
  49. else:
  50. norm_img = resize_norm_img(img, self.image_shape)
  51. data['image'] = norm_img
  52. return data
  53. class SRNRecResizeImg(object):
  54. def __init__(self, image_shape, num_heads, max_text_length, **kwargs):
  55. self.image_shape = image_shape
  56. self.num_heads = num_heads
  57. self.max_text_length = max_text_length
  58. def __call__(self, data):
  59. img = data['image']
  60. norm_img = resize_norm_img_srn(img, self.image_shape)
  61. data['image'] = norm_img
  62. [encoder_word_pos, gsrm_word_pos, gsrm_slf_attn_bias1, gsrm_slf_attn_bias2] = \
  63. srn_other_inputs(self.image_shape, self.num_heads, self.max_text_length)
  64. data['encoder_word_pos'] = encoder_word_pos
  65. data['gsrm_word_pos'] = gsrm_word_pos
  66. data['gsrm_slf_attn_bias1'] = gsrm_slf_attn_bias1
  67. data['gsrm_slf_attn_bias2'] = gsrm_slf_attn_bias2
  68. return data
  69. def resize_norm_img(img, image_shape):
  70. imgC, imgH, imgW = image_shape
  71. h = img.shape[0]
  72. w = img.shape[1]
  73. ratio = w / float(h)
  74. if math.ceil(imgH * ratio) > imgW:
  75. resized_w = imgW
  76. else:
  77. resized_w = int(math.ceil(imgH * ratio))
  78. resized_image = cv2.resize(img, (resized_w, imgH))
  79. resized_image = resized_image.astype('float32')
  80. if image_shape[0] == 1:
  81. resized_image = resized_image / 255
  82. resized_image = resized_image[np.newaxis, :]
  83. else:
  84. resized_image = resized_image.transpose((2, 0, 1)) / 255
  85. resized_image -= 0.5
  86. resized_image /= 0.5
  87. padding_im = np.zeros((imgC, imgH, imgW), dtype=np.float32)
  88. padding_im[:, :, 0:resized_w] = resized_image
  89. return padding_im
  90. def resize_norm_img_chinese(img, image_shape):
  91. imgC, imgH, imgW = image_shape
  92. # todo: change to 0 and modified image shape
  93. max_wh_ratio = imgW * 1.0 / imgH
  94. h, w = img.shape[0], img.shape[1]
  95. ratio = w * 1.0 / h
  96. max_wh_ratio = max(max_wh_ratio, ratio)
  97. imgW = int(32 * max_wh_ratio)
  98. if math.ceil(imgH * ratio) > imgW:
  99. resized_w = imgW
  100. else:
  101. resized_w = int(math.ceil(imgH * ratio))
  102. resized_image = cv2.resize(img, (resized_w, imgH))
  103. resized_image = resized_image.astype('float32')
  104. if image_shape[0] == 1:
  105. resized_image = resized_image / 255
  106. resized_image = resized_image[np.newaxis, :]
  107. else:
  108. resized_image = resized_image.transpose((2, 0, 1)) / 255
  109. resized_image -= 0.5
  110. resized_image /= 0.5
  111. padding_im = np.zeros((imgC, imgH, imgW), dtype=np.float32)
  112. padding_im[:, :, 0:resized_w] = resized_image
  113. return padding_im
  114. def resize_norm_img_srn(img, image_shape):
  115. imgC, imgH, imgW = image_shape
  116. img_black = np.zeros((imgH, imgW))
  117. im_hei = img.shape[0]
  118. im_wid = img.shape[1]
  119. if im_wid <= im_hei * 1:
  120. img_new = cv2.resize(img, (imgH * 1, imgH))
  121. elif im_wid <= im_hei * 2:
  122. img_new = cv2.resize(img, (imgH * 2, imgH))
  123. elif im_wid <= im_hei * 3:
  124. img_new = cv2.resize(img, (imgH * 3, imgH))
  125. else:
  126. img_new = cv2.resize(img, (imgW, imgH))
  127. img_np = np.asarray(img_new)
  128. img_np = cv2.cvtColor(img_np, cv2.COLOR_BGR2GRAY)
  129. img_black[:, 0:img_np.shape[1]] = img_np
  130. img_black = img_black[:, :, np.newaxis]
  131. row, col, c = img_black.shape
  132. c = 1
  133. return np.reshape(img_black, (c, row, col)).astype(np.float32)
  134. def srn_other_inputs(image_shape, num_heads, max_text_length):
  135. imgC, imgH, imgW = image_shape
  136. feature_dim = int((imgH / 8) * (imgW / 8))
  137. encoder_word_pos = np.array(range(0, feature_dim)).reshape(
  138. (feature_dim, 1)).astype('int64')
  139. gsrm_word_pos = np.array(range(0, max_text_length)).reshape(
  140. (max_text_length, 1)).astype('int64')
  141. gsrm_attn_bias_data = np.ones((1, max_text_length, max_text_length))
  142. gsrm_slf_attn_bias1 = np.triu(gsrm_attn_bias_data, 1).reshape(
  143. [1, max_text_length, max_text_length])
  144. gsrm_slf_attn_bias1 = np.tile(gsrm_slf_attn_bias1,
  145. [num_heads, 1, 1]) * [-1e9]
  146. gsrm_slf_attn_bias2 = np.tril(gsrm_attn_bias_data, -1).reshape(
  147. [1, max_text_length, max_text_length])
  148. gsrm_slf_attn_bias2 = np.tile(gsrm_slf_attn_bias2,
  149. [num_heads, 1, 1]) * [-1e9]
  150. return [
  151. encoder_word_pos, gsrm_word_pos, gsrm_slf_attn_bias1,
  152. gsrm_slf_attn_bias2
  153. ]
  154. def flag():
  155. """
  156. flag
  157. """
  158. return 1 if random.random() > 0.5000001 else -1
  159. def cvtColor(img):
  160. """
  161. cvtColor
  162. """
  163. hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
  164. delta = 0.001 * random.random() * flag()
  165. hsv[:, :, 2] = hsv[:, :, 2] * (1 + delta)
  166. new_img = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)
  167. return new_img
  168. def blur(img):
  169. """
  170. blur
  171. """
  172. h, w, _ = img.shape
  173. if h > 10 and w > 10:
  174. return cv2.GaussianBlur(img, (5, 5), 1)
  175. else:
  176. return img
  177. def jitter(img):
  178. """
  179. jitter
  180. """
  181. w, h, _ = img.shape
  182. if h > 10 and w > 10:
  183. thres = min(w, h)
  184. s = int(random.random() * thres * 0.01)
  185. src_img = img.copy()
  186. for i in range(s):
  187. img[i:, i:, :] = src_img[:w - i, :h - i, :]
  188. return img
  189. else:
  190. return img
  191. def add_gasuss_noise(image, mean=0, var=0.1):
  192. """
  193. Gasuss noise
  194. """
  195. noise = np.random.normal(mean, var**0.5, image.shape)
  196. out = image + 0.5 * noise
  197. out = np.clip(out, 0, 255)
  198. out = np.uint8(out)
  199. return out
  200. def get_crop(image):
  201. """
  202. random crop
  203. """
  204. h, w, _ = image.shape
  205. top_min = 1
  206. top_max = 8
  207. top_crop = int(random.randint(top_min, top_max))
  208. top_crop = min(top_crop, h - 1)
  209. crop_img = image.copy()
  210. ratio = random.randint(0, 1)
  211. if ratio:
  212. crop_img = crop_img[top_crop:h, :, :]
  213. else:
  214. crop_img = crop_img[0:h - top_crop, :, :]
  215. return crop_img
  216. class Config:
  217. """
  218. Config
  219. """
  220. def __init__(self, use_tia):
  221. self.anglex = random.random() * 30
  222. self.angley = random.random() * 15
  223. self.anglez = random.random() * 10
  224. self.fov = 42
  225. self.r = 0
  226. self.shearx = random.random() * 0.3
  227. self.sheary = random.random() * 0.05
  228. self.borderMode = cv2.BORDER_REPLICATE
  229. self.use_tia = use_tia
  230. def make(self, w, h, ang):
  231. """
  232. make
  233. """
  234. self.anglex = random.random() * 5 * flag()
  235. self.angley = random.random() * 5 * flag()
  236. self.anglez = -1 * random.random() * int(ang) * flag()
  237. self.fov = 42
  238. self.r = 0
  239. self.shearx = 0
  240. self.sheary = 0
  241. self.borderMode = cv2.BORDER_REPLICATE
  242. self.w = w
  243. self.h = h
  244. self.perspective = self.use_tia
  245. self.stretch = self.use_tia
  246. self.distort = self.use_tia
  247. self.crop = True
  248. self.affine = False
  249. self.reverse = True
  250. self.noise = True
  251. self.jitter = True
  252. self.blur = True
  253. self.color = True
  254. def rad(x):
  255. """
  256. rad
  257. """
  258. return x * np.pi / 180
  259. def get_warpR(config):
  260. """
  261. get_warpR
  262. """
  263. anglex, angley, anglez, fov, w, h, r = \
  264. config.anglex, config.angley, config.anglez, config.fov, config.w, config.h, config.r
  265. if w > 69 and w < 112:
  266. anglex = anglex * 1.5
  267. z = np.sqrt(w**2 + h**2) / 2 / np.tan(rad(fov / 2))
  268. # Homogeneous coordinate transformation matrix
  269. rx = np.array([[1, 0, 0, 0],
  270. [0, np.cos(rad(anglex)), -np.sin(rad(anglex)), 0], [
  271. 0,
  272. -np.sin(rad(anglex)),
  273. np.cos(rad(anglex)),
  274. 0,
  275. ], [0, 0, 0, 1]], np.float32)
  276. ry = np.array([[np.cos(rad(angley)), 0, np.sin(rad(angley)), 0],
  277. [0, 1, 0, 0], [
  278. -np.sin(rad(angley)),
  279. 0,
  280. np.cos(rad(angley)),
  281. 0,
  282. ], [0, 0, 0, 1]], np.float32)
  283. rz = np.array([[np.cos(rad(anglez)), np.sin(rad(anglez)), 0, 0],
  284. [-np.sin(rad(anglez)), np.cos(rad(anglez)), 0, 0],
  285. [0, 0, 1, 0], [0, 0, 0, 1]], np.float32)
  286. r = rx.dot(ry).dot(rz)
  287. # generate 4 points
  288. pcenter = np.array([h / 2, w / 2, 0, 0], np.float32)
  289. p1 = np.array([0, 0, 0, 0], np.float32) - pcenter
  290. p2 = np.array([w, 0, 0, 0], np.float32) - pcenter
  291. p3 = np.array([0, h, 0, 0], np.float32) - pcenter
  292. p4 = np.array([w, h, 0, 0], np.float32) - pcenter
  293. dst1 = r.dot(p1)
  294. dst2 = r.dot(p2)
  295. dst3 = r.dot(p3)
  296. dst4 = r.dot(p4)
  297. list_dst = np.array([dst1, dst2, dst3, dst4])
  298. org = np.array([[0, 0], [w, 0], [0, h], [w, h]], np.float32)
  299. dst = np.zeros((4, 2), np.float32)
  300. # Project onto the image plane
  301. dst[:, 0] = list_dst[:, 0] * z / (z - list_dst[:, 2]) + pcenter[0]
  302. dst[:, 1] = list_dst[:, 1] * z / (z - list_dst[:, 2]) + pcenter[1]
  303. warpR = cv2.getPerspectiveTransform(org, dst)
  304. dst1, dst2, dst3, dst4 = dst
  305. r1 = int(min(dst1[1], dst2[1]))
  306. r2 = int(max(dst3[1], dst4[1]))
  307. c1 = int(min(dst1[0], dst3[0]))
  308. c2 = int(max(dst2[0], dst4[0]))
  309. try:
  310. ratio = min(1.0 * h / (r2 - r1), 1.0 * w / (c2 - c1))
  311. dx = -c1
  312. dy = -r1
  313. T1 = np.float32([[1., 0, dx], [0, 1., dy], [0, 0, 1.0 / ratio]])
  314. ret = T1.dot(warpR)
  315. except:
  316. ratio = 1.0
  317. T1 = np.float32([[1., 0, 0], [0, 1., 0], [0, 0, 1.]])
  318. ret = T1
  319. return ret, (-r1, -c1), ratio, dst
  320. def get_warpAffine(config):
  321. """
  322. get_warpAffine
  323. """
  324. anglez = config.anglez
  325. rz = np.array([[np.cos(rad(anglez)), np.sin(rad(anglez)), 0],
  326. [-np.sin(rad(anglez)), np.cos(rad(anglez)), 0]], np.float32)
  327. return rz
  328. def warp(img, ang, use_tia=True, prob=0.4):
  329. """
  330. warp
  331. """
  332. h, w, _ = img.shape
  333. config = Config(use_tia=use_tia)
  334. config.make(w, h, ang)
  335. new_img = img
  336. if config.distort:
  337. img_height, img_width = img.shape[0:2]
  338. if random.random() <= prob and img_height >= 20 and img_width >= 20:
  339. new_img = tia_distort(new_img, random.randint(3, 6))
  340. if config.stretch:
  341. img_height, img_width = img.shape[0:2]
  342. if random.random() <= prob and img_height >= 20 and img_width >= 20:
  343. new_img = tia_stretch(new_img, random.randint(3, 6))
  344. if config.perspective:
  345. if random.random() <= prob:
  346. new_img = tia_perspective(new_img)
  347. if config.crop:
  348. img_height, img_width = img.shape[0:2]
  349. if random.random() <= prob and img_height >= 20 and img_width >= 20:
  350. new_img = get_crop(new_img)
  351. if config.blur:
  352. if random.random() <= prob:
  353. new_img = blur(new_img)
  354. if config.color:
  355. if random.random() <= prob:
  356. new_img = cvtColor(new_img)
  357. if config.jitter:
  358. new_img = jitter(new_img)
  359. if config.noise:
  360. if random.random() <= prob:
  361. new_img = add_gasuss_noise(new_img)
  362. if config.reverse:
  363. if random.random() <= prob:
  364. new_img = 255 - new_img
  365. return new_img