rec_img_aug.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827
  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. import copy
  19. from PIL import Image
  20. from .text_image_aug import tia_perspective, tia_stretch, tia_distort
  21. from .abinet_aug import CVGeometry, CVDeterioration, CVColorJitter, SVTRGeometry, SVTRDeterioration
  22. from paddle.vision.transforms import Compose
  23. class RecAug(object):
  24. def __init__(self,
  25. tia_prob=0.4,
  26. crop_prob=0.4,
  27. reverse_prob=0.4,
  28. noise_prob=0.4,
  29. jitter_prob=0.4,
  30. blur_prob=0.4,
  31. hsv_aug_prob=0.4,
  32. **kwargs):
  33. self.tia_prob = tia_prob
  34. self.bda = BaseDataAugmentation(crop_prob, reverse_prob, noise_prob,
  35. jitter_prob, blur_prob, hsv_aug_prob)
  36. def __call__(self, data):
  37. img = data['image']
  38. h, w, _ = img.shape
  39. # tia
  40. if random.random() <= self.tia_prob:
  41. if h >= 20 and w >= 20:
  42. img = tia_distort(img, random.randint(3, 6))
  43. img = tia_stretch(img, random.randint(3, 6))
  44. img = tia_perspective(img)
  45. # bda
  46. data['image'] = img
  47. data = self.bda(data)
  48. return data
  49. class BaseDataAugmentation(object):
  50. def __init__(self,
  51. crop_prob=0.4,
  52. reverse_prob=0.4,
  53. noise_prob=0.4,
  54. jitter_prob=0.4,
  55. blur_prob=0.4,
  56. hsv_aug_prob=0.4,
  57. **kwargs):
  58. self.crop_prob = crop_prob
  59. self.reverse_prob = reverse_prob
  60. self.noise_prob = noise_prob
  61. self.jitter_prob = jitter_prob
  62. self.blur_prob = blur_prob
  63. self.hsv_aug_prob = hsv_aug_prob
  64. def __call__(self, data):
  65. img = data['image']
  66. h, w, _ = img.shape
  67. if random.random() <= self.crop_prob and h >= 20 and w >= 20:
  68. img = get_crop(img)
  69. if random.random() <= self.blur_prob:
  70. img = blur(img)
  71. if random.random() <= self.hsv_aug_prob:
  72. img = hsv_aug(img)
  73. if random.random() <= self.jitter_prob:
  74. img = jitter(img)
  75. if random.random() <= self.noise_prob:
  76. img = add_gasuss_noise(img)
  77. if random.random() <= self.reverse_prob:
  78. img = 255 - img
  79. data['image'] = img
  80. return data
  81. class ABINetRecAug(object):
  82. def __init__(self,
  83. geometry_p=0.5,
  84. deterioration_p=0.25,
  85. colorjitter_p=0.25,
  86. **kwargs):
  87. self.transforms = Compose([
  88. CVGeometry(
  89. degrees=45,
  90. translate=(0.0, 0.0),
  91. scale=(0.5, 2.),
  92. shear=(45, 15),
  93. distortion=0.5,
  94. p=geometry_p),
  95. CVDeterioration(
  96. var=20, degrees=6, factor=4, p=deterioration_p),
  97. CVColorJitter(
  98. brightness=0.5,
  99. contrast=0.5,
  100. saturation=0.5,
  101. hue=0.1,
  102. p=colorjitter_p)
  103. ])
  104. def __call__(self, data):
  105. img = data['image']
  106. img = self.transforms(img)
  107. data['image'] = img
  108. return data
  109. class RecConAug(object):
  110. def __init__(self,
  111. prob=0.5,
  112. image_shape=(32, 320, 3),
  113. max_text_length=25,
  114. ext_data_num=1,
  115. **kwargs):
  116. self.ext_data_num = ext_data_num
  117. self.prob = prob
  118. self.max_text_length = max_text_length
  119. self.image_shape = image_shape
  120. self.max_wh_ratio = self.image_shape[1] / self.image_shape[0]
  121. def merge_ext_data(self, data, ext_data):
  122. ori_w = round(data['image'].shape[1] / data['image'].shape[0] *
  123. self.image_shape[0])
  124. ext_w = round(ext_data['image'].shape[1] / ext_data['image'].shape[0] *
  125. self.image_shape[0])
  126. data['image'] = cv2.resize(data['image'], (ori_w, self.image_shape[0]))
  127. ext_data['image'] = cv2.resize(ext_data['image'],
  128. (ext_w, self.image_shape[0]))
  129. data['image'] = np.concatenate(
  130. [data['image'], ext_data['image']], axis=1)
  131. data["label"] += ext_data["label"]
  132. return data
  133. def __call__(self, data):
  134. rnd_num = random.random()
  135. if rnd_num > self.prob:
  136. return data
  137. for idx, ext_data in enumerate(data["ext_data"]):
  138. if len(data["label"]) + len(ext_data[
  139. "label"]) > self.max_text_length:
  140. break
  141. concat_ratio = data['image'].shape[1] / data['image'].shape[
  142. 0] + ext_data['image'].shape[1] / ext_data['image'].shape[0]
  143. if concat_ratio > self.max_wh_ratio:
  144. break
  145. data = self.merge_ext_data(data, ext_data)
  146. data.pop("ext_data")
  147. return data
  148. class SVTRRecAug(object):
  149. def __init__(self,
  150. aug_type=0,
  151. geometry_p=0.5,
  152. deterioration_p=0.25,
  153. colorjitter_p=0.25,
  154. **kwargs):
  155. self.transforms = Compose([
  156. SVTRGeometry(
  157. aug_type=aug_type,
  158. degrees=45,
  159. translate=(0.0, 0.0),
  160. scale=(0.5, 2.),
  161. shear=(45, 15),
  162. distortion=0.5,
  163. p=geometry_p),
  164. SVTRDeterioration(
  165. var=20, degrees=6, factor=4, p=deterioration_p),
  166. CVColorJitter(
  167. brightness=0.5,
  168. contrast=0.5,
  169. saturation=0.5,
  170. hue=0.1,
  171. p=colorjitter_p)
  172. ])
  173. def __call__(self, data):
  174. img = data['image']
  175. img = self.transforms(img)
  176. data['image'] = img
  177. return data
  178. class ClsResizeImg(object):
  179. def __init__(self, image_shape, **kwargs):
  180. self.image_shape = image_shape
  181. def __call__(self, data):
  182. img = data['image']
  183. norm_img, _ = resize_norm_img(img, self.image_shape)
  184. data['image'] = norm_img
  185. return data
  186. class RecResizeImg(object):
  187. def __init__(self,
  188. image_shape,
  189. infer_mode=False,
  190. character_dict_path='./ppocr/utils/ppocr_keys_v1.txt',
  191. padding=True,
  192. **kwargs):
  193. self.image_shape = image_shape
  194. self.infer_mode = infer_mode
  195. self.character_dict_path = character_dict_path
  196. self.padding = padding
  197. def __call__(self, data):
  198. img = data['image']
  199. if self.infer_mode and self.character_dict_path is not None:
  200. norm_img, valid_ratio = resize_norm_img_chinese(img,
  201. self.image_shape)
  202. else:
  203. norm_img, valid_ratio = resize_norm_img(img, self.image_shape,
  204. self.padding)
  205. data['image'] = norm_img
  206. data['valid_ratio'] = valid_ratio
  207. return data
  208. class VLRecResizeImg(object):
  209. def __init__(self,
  210. image_shape,
  211. infer_mode=False,
  212. character_dict_path='./ppocr/utils/ppocr_keys_v1.txt',
  213. padding=True,
  214. **kwargs):
  215. self.image_shape = image_shape
  216. self.infer_mode = infer_mode
  217. self.character_dict_path = character_dict_path
  218. self.padding = padding
  219. def __call__(self, data):
  220. img = data['image']
  221. imgC, imgH, imgW = self.image_shape
  222. resized_image = cv2.resize(
  223. img, (imgW, imgH), interpolation=cv2.INTER_LINEAR)
  224. resized_w = imgW
  225. resized_image = resized_image.astype('float32')
  226. if self.image_shape[0] == 1:
  227. resized_image = resized_image / 255
  228. norm_img = resized_image[np.newaxis, :]
  229. else:
  230. norm_img = resized_image.transpose((2, 0, 1)) / 255
  231. valid_ratio = min(1.0, float(resized_w / imgW))
  232. data['image'] = norm_img
  233. data['valid_ratio'] = valid_ratio
  234. return data
  235. class RFLRecResizeImg(object):
  236. def __init__(self, image_shape, padding=True, interpolation=1, **kwargs):
  237. self.image_shape = image_shape
  238. self.padding = padding
  239. self.interpolation = interpolation
  240. if self.interpolation == 0:
  241. self.interpolation = cv2.INTER_NEAREST
  242. elif self.interpolation == 1:
  243. self.interpolation = cv2.INTER_LINEAR
  244. elif self.interpolation == 2:
  245. self.interpolation = cv2.INTER_CUBIC
  246. elif self.interpolation == 3:
  247. self.interpolation = cv2.INTER_AREA
  248. else:
  249. raise Exception("Unsupported interpolation type !!!")
  250. def __call__(self, data):
  251. img = data['image']
  252. img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  253. norm_img, valid_ratio = resize_norm_img(
  254. img, self.image_shape, self.padding, self.interpolation)
  255. data['image'] = norm_img
  256. data['valid_ratio'] = valid_ratio
  257. return data
  258. class SRNRecResizeImg(object):
  259. def __init__(self, image_shape, num_heads, max_text_length, **kwargs):
  260. self.image_shape = image_shape
  261. self.num_heads = num_heads
  262. self.max_text_length = max_text_length
  263. def __call__(self, data):
  264. img = data['image']
  265. norm_img = resize_norm_img_srn(img, self.image_shape)
  266. data['image'] = norm_img
  267. [encoder_word_pos, gsrm_word_pos, gsrm_slf_attn_bias1, gsrm_slf_attn_bias2] = \
  268. srn_other_inputs(self.image_shape, self.num_heads, self.max_text_length)
  269. data['encoder_word_pos'] = encoder_word_pos
  270. data['gsrm_word_pos'] = gsrm_word_pos
  271. data['gsrm_slf_attn_bias1'] = gsrm_slf_attn_bias1
  272. data['gsrm_slf_attn_bias2'] = gsrm_slf_attn_bias2
  273. return data
  274. class SARRecResizeImg(object):
  275. def __init__(self, image_shape, width_downsample_ratio=0.25, **kwargs):
  276. self.image_shape = image_shape
  277. self.width_downsample_ratio = width_downsample_ratio
  278. def __call__(self, data):
  279. img = data['image']
  280. norm_img, resize_shape, pad_shape, valid_ratio = resize_norm_img_sar(
  281. img, self.image_shape, self.width_downsample_ratio)
  282. data['image'] = norm_img
  283. data['resized_shape'] = resize_shape
  284. data['pad_shape'] = pad_shape
  285. data['valid_ratio'] = valid_ratio
  286. return data
  287. class PRENResizeImg(object):
  288. def __init__(self, image_shape, **kwargs):
  289. """
  290. Accroding to original paper's realization, it's a hard resize method here.
  291. So maybe you should optimize it to fit for your task better.
  292. """
  293. self.dst_h, self.dst_w = image_shape
  294. def __call__(self, data):
  295. img = data['image']
  296. resized_img = cv2.resize(
  297. img, (self.dst_w, self.dst_h), interpolation=cv2.INTER_LINEAR)
  298. resized_img = resized_img.transpose((2, 0, 1)) / 255
  299. resized_img -= 0.5
  300. resized_img /= 0.5
  301. data['image'] = resized_img.astype(np.float32)
  302. return data
  303. class SPINRecResizeImg(object):
  304. def __init__(self,
  305. image_shape,
  306. interpolation=2,
  307. mean=(127.5, 127.5, 127.5),
  308. std=(127.5, 127.5, 127.5),
  309. **kwargs):
  310. self.image_shape = image_shape
  311. self.mean = np.array(mean, dtype=np.float32)
  312. self.std = np.array(std, dtype=np.float32)
  313. self.interpolation = interpolation
  314. def __call__(self, data):
  315. img = data['image']
  316. img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  317. # different interpolation type corresponding the OpenCV
  318. if self.interpolation == 0:
  319. interpolation = cv2.INTER_NEAREST
  320. elif self.interpolation == 1:
  321. interpolation = cv2.INTER_LINEAR
  322. elif self.interpolation == 2:
  323. interpolation = cv2.INTER_CUBIC
  324. elif self.interpolation == 3:
  325. interpolation = cv2.INTER_AREA
  326. else:
  327. raise Exception("Unsupported interpolation type !!!")
  328. # Deal with the image error during image loading
  329. if img is None:
  330. return None
  331. img = cv2.resize(img, tuple(self.image_shape), interpolation)
  332. img = np.array(img, np.float32)
  333. img = np.expand_dims(img, -1)
  334. img = img.transpose((2, 0, 1))
  335. # normalize the image
  336. img = img.copy().astype(np.float32)
  337. mean = np.float64(self.mean.reshape(1, -1))
  338. stdinv = 1 / np.float64(self.std.reshape(1, -1))
  339. img -= mean
  340. img *= stdinv
  341. data['image'] = img
  342. return data
  343. class GrayRecResizeImg(object):
  344. def __init__(self,
  345. image_shape,
  346. resize_type,
  347. inter_type='Image.ANTIALIAS',
  348. scale=True,
  349. padding=False,
  350. **kwargs):
  351. self.image_shape = image_shape
  352. self.resize_type = resize_type
  353. self.padding = padding
  354. self.inter_type = eval(inter_type)
  355. self.scale = scale
  356. def __call__(self, data):
  357. img = data['image']
  358. img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  359. image_shape = self.image_shape
  360. if self.padding:
  361. imgC, imgH, imgW = image_shape
  362. # todo: change to 0 and modified image shape
  363. h = img.shape[0]
  364. w = img.shape[1]
  365. ratio = w / float(h)
  366. if math.ceil(imgH * ratio) > imgW:
  367. resized_w = imgW
  368. else:
  369. resized_w = int(math.ceil(imgH * ratio))
  370. resized_image = cv2.resize(img, (resized_w, imgH))
  371. norm_img = np.expand_dims(resized_image, -1)
  372. norm_img = norm_img.transpose((2, 0, 1))
  373. resized_image = norm_img.astype(np.float32) / 128. - 1.
  374. padding_im = np.zeros((imgC, imgH, imgW), dtype=np.float32)
  375. padding_im[:, :, 0:resized_w] = resized_image
  376. data['image'] = padding_im
  377. return data
  378. if self.resize_type == 'PIL':
  379. image_pil = Image.fromarray(np.uint8(img))
  380. img = image_pil.resize(self.image_shape, self.inter_type)
  381. img = np.array(img)
  382. if self.resize_type == 'OpenCV':
  383. img = cv2.resize(img, self.image_shape)
  384. norm_img = np.expand_dims(img, -1)
  385. norm_img = norm_img.transpose((2, 0, 1))
  386. if self.scale:
  387. data['image'] = norm_img.astype(np.float32) / 128. - 1.
  388. else:
  389. data['image'] = norm_img.astype(np.float32) / 255.
  390. return data
  391. class ABINetRecResizeImg(object):
  392. def __init__(self, image_shape, **kwargs):
  393. self.image_shape = image_shape
  394. def __call__(self, data):
  395. img = data['image']
  396. norm_img, valid_ratio = resize_norm_img_abinet(img, self.image_shape)
  397. data['image'] = norm_img
  398. data['valid_ratio'] = valid_ratio
  399. return data
  400. class SVTRRecResizeImg(object):
  401. def __init__(self, image_shape, padding=True, **kwargs):
  402. self.image_shape = image_shape
  403. self.padding = padding
  404. def __call__(self, data):
  405. img = data['image']
  406. norm_img, valid_ratio = resize_norm_img(img, self.image_shape,
  407. self.padding)
  408. data['image'] = norm_img
  409. data['valid_ratio'] = valid_ratio
  410. return data
  411. class RobustScannerRecResizeImg(object):
  412. def __init__(self,
  413. image_shape,
  414. max_text_length,
  415. width_downsample_ratio=0.25,
  416. **kwargs):
  417. self.image_shape = image_shape
  418. self.width_downsample_ratio = width_downsample_ratio
  419. self.max_text_length = max_text_length
  420. def __call__(self, data):
  421. img = data['image']
  422. norm_img, resize_shape, pad_shape, valid_ratio = resize_norm_img_sar(
  423. img, self.image_shape, self.width_downsample_ratio)
  424. word_positons = np.array(range(0, self.max_text_length)).astype('int64')
  425. data['image'] = norm_img
  426. data['resized_shape'] = resize_shape
  427. data['pad_shape'] = pad_shape
  428. data['valid_ratio'] = valid_ratio
  429. data['word_positons'] = word_positons
  430. return data
  431. def resize_norm_img_sar(img, image_shape, width_downsample_ratio=0.25):
  432. imgC, imgH, imgW_min, imgW_max = image_shape
  433. h = img.shape[0]
  434. w = img.shape[1]
  435. valid_ratio = 1.0
  436. # make sure new_width is an integral multiple of width_divisor.
  437. width_divisor = int(1 / width_downsample_ratio)
  438. # resize
  439. ratio = w / float(h)
  440. resize_w = math.ceil(imgH * ratio)
  441. if resize_w % width_divisor != 0:
  442. resize_w = round(resize_w / width_divisor) * width_divisor
  443. if imgW_min is not None:
  444. resize_w = max(imgW_min, resize_w)
  445. if imgW_max is not None:
  446. valid_ratio = min(1.0, 1.0 * resize_w / imgW_max)
  447. resize_w = min(imgW_max, resize_w)
  448. resized_image = cv2.resize(img, (resize_w, imgH))
  449. resized_image = resized_image.astype('float32')
  450. # norm
  451. if image_shape[0] == 1:
  452. resized_image = resized_image / 255
  453. resized_image = resized_image[np.newaxis, :]
  454. else:
  455. resized_image = resized_image.transpose((2, 0, 1)) / 255
  456. resized_image -= 0.5
  457. resized_image /= 0.5
  458. resize_shape = resized_image.shape
  459. padding_im = -1.0 * np.ones((imgC, imgH, imgW_max), dtype=np.float32)
  460. padding_im[:, :, 0:resize_w] = resized_image
  461. pad_shape = padding_im.shape
  462. return padding_im, resize_shape, pad_shape, valid_ratio
  463. def resize_norm_img(img,
  464. image_shape,
  465. padding=True,
  466. interpolation=cv2.INTER_LINEAR):
  467. imgC, imgH, imgW = image_shape
  468. h = img.shape[0]
  469. w = img.shape[1]
  470. if not padding:
  471. resized_image = cv2.resize(
  472. img, (imgW, imgH), interpolation=interpolation)
  473. resized_w = imgW
  474. else:
  475. ratio = w / float(h)
  476. if math.ceil(imgH * ratio) > imgW:
  477. resized_w = imgW
  478. else:
  479. resized_w = int(math.ceil(imgH * ratio))
  480. resized_image = cv2.resize(img, (resized_w, imgH))
  481. resized_image = resized_image.astype('float32')
  482. if image_shape[0] == 1:
  483. resized_image = resized_image / 255
  484. resized_image = resized_image[np.newaxis, :]
  485. else:
  486. resized_image = resized_image.transpose((2, 0, 1)) / 255
  487. resized_image -= 0.5
  488. resized_image /= 0.5
  489. padding_im = np.zeros((imgC, imgH, imgW), dtype=np.float32)
  490. padding_im[:, :, 0:resized_w] = resized_image
  491. valid_ratio = min(1.0, float(resized_w / imgW))
  492. return padding_im, valid_ratio
  493. def resize_norm_img_chinese(img, image_shape):
  494. imgC, imgH, imgW = image_shape
  495. # todo: change to 0 and modified image shape
  496. max_wh_ratio = imgW * 1.0 / imgH
  497. h, w = img.shape[0], img.shape[1]
  498. ratio = w * 1.0 / h
  499. max_wh_ratio = min(max(max_wh_ratio, ratio), max_wh_ratio)
  500. imgW = int(imgH * max_wh_ratio)
  501. if math.ceil(imgH * ratio) > imgW:
  502. resized_w = imgW
  503. else:
  504. resized_w = int(math.ceil(imgH * ratio))
  505. resized_image = cv2.resize(img, (resized_w, imgH))
  506. resized_image = resized_image.astype('float32')
  507. if image_shape[0] == 1:
  508. resized_image = resized_image / 255
  509. resized_image = resized_image[np.newaxis, :]
  510. else:
  511. resized_image = resized_image.transpose((2, 0, 1)) / 255
  512. resized_image -= 0.5
  513. resized_image /= 0.5
  514. padding_im = np.zeros((imgC, imgH, imgW), dtype=np.float32)
  515. padding_im[:, :, 0:resized_w] = resized_image
  516. valid_ratio = min(1.0, float(resized_w / imgW))
  517. return padding_im, valid_ratio
  518. def resize_norm_img_srn(img, image_shape):
  519. imgC, imgH, imgW = image_shape
  520. img_black = np.zeros((imgH, imgW))
  521. im_hei = img.shape[0]
  522. im_wid = img.shape[1]
  523. if im_wid <= im_hei * 1:
  524. img_new = cv2.resize(img, (imgH * 1, imgH))
  525. elif im_wid <= im_hei * 2:
  526. img_new = cv2.resize(img, (imgH * 2, imgH))
  527. elif im_wid <= im_hei * 3:
  528. img_new = cv2.resize(img, (imgH * 3, imgH))
  529. else:
  530. img_new = cv2.resize(img, (imgW, imgH))
  531. img_np = np.asarray(img_new)
  532. img_np = cv2.cvtColor(img_np, cv2.COLOR_BGR2GRAY)
  533. img_black[:, 0:img_np.shape[1]] = img_np
  534. img_black = img_black[:, :, np.newaxis]
  535. row, col, c = img_black.shape
  536. c = 1
  537. return np.reshape(img_black, (c, row, col)).astype(np.float32)
  538. def resize_norm_img_abinet(img, image_shape):
  539. imgC, imgH, imgW = image_shape
  540. resized_image = cv2.resize(
  541. img, (imgW, imgH), interpolation=cv2.INTER_LINEAR)
  542. resized_w = imgW
  543. resized_image = resized_image.astype('float32')
  544. resized_image = resized_image / 255.
  545. mean = np.array([0.485, 0.456, 0.406])
  546. std = np.array([0.229, 0.224, 0.225])
  547. resized_image = (
  548. resized_image - mean[None, None, ...]) / std[None, None, ...]
  549. resized_image = resized_image.transpose((2, 0, 1))
  550. resized_image = resized_image.astype('float32')
  551. valid_ratio = min(1.0, float(resized_w / imgW))
  552. return resized_image, valid_ratio
  553. def srn_other_inputs(image_shape, num_heads, max_text_length):
  554. imgC, imgH, imgW = image_shape
  555. feature_dim = int((imgH / 8) * (imgW / 8))
  556. encoder_word_pos = np.array(range(0, feature_dim)).reshape(
  557. (feature_dim, 1)).astype('int64')
  558. gsrm_word_pos = np.array(range(0, max_text_length)).reshape(
  559. (max_text_length, 1)).astype('int64')
  560. gsrm_attn_bias_data = np.ones((1, max_text_length, max_text_length))
  561. gsrm_slf_attn_bias1 = np.triu(gsrm_attn_bias_data, 1).reshape(
  562. [1, max_text_length, max_text_length])
  563. gsrm_slf_attn_bias1 = np.tile(gsrm_slf_attn_bias1,
  564. [num_heads, 1, 1]) * [-1e9]
  565. gsrm_slf_attn_bias2 = np.tril(gsrm_attn_bias_data, -1).reshape(
  566. [1, max_text_length, max_text_length])
  567. gsrm_slf_attn_bias2 = np.tile(gsrm_slf_attn_bias2,
  568. [num_heads, 1, 1]) * [-1e9]
  569. return [
  570. encoder_word_pos, gsrm_word_pos, gsrm_slf_attn_bias1,
  571. gsrm_slf_attn_bias2
  572. ]
  573. def flag():
  574. """
  575. flag
  576. """
  577. return 1 if random.random() > 0.5000001 else -1
  578. def hsv_aug(img):
  579. """
  580. cvtColor
  581. """
  582. hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
  583. delta = 0.001 * random.random() * flag()
  584. hsv[:, :, 2] = hsv[:, :, 2] * (1 + delta)
  585. new_img = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)
  586. return new_img
  587. def blur(img):
  588. """
  589. blur
  590. """
  591. h, w, _ = img.shape
  592. if h > 10 and w > 10:
  593. return cv2.GaussianBlur(img, (5, 5), 1)
  594. else:
  595. return img
  596. def jitter(img):
  597. """
  598. jitter
  599. """
  600. w, h, _ = img.shape
  601. if h > 10 and w > 10:
  602. thres = min(w, h)
  603. s = int(random.random() * thres * 0.01)
  604. src_img = img.copy()
  605. for i in range(s):
  606. img[i:, i:, :] = src_img[:w - i, :h - i, :]
  607. return img
  608. else:
  609. return img
  610. def add_gasuss_noise(image, mean=0, var=0.1):
  611. """
  612. Gasuss noise
  613. """
  614. noise = np.random.normal(mean, var**0.5, image.shape)
  615. out = image + 0.5 * noise
  616. out = np.clip(out, 0, 255)
  617. out = np.uint8(out)
  618. return out
  619. def get_crop(image):
  620. """
  621. random crop
  622. """
  623. h, w, _ = image.shape
  624. top_min = 1
  625. top_max = 8
  626. top_crop = int(random.randint(top_min, top_max))
  627. top_crop = min(top_crop, h - 1)
  628. crop_img = image.copy()
  629. ratio = random.randint(0, 1)
  630. if ratio:
  631. crop_img = crop_img[top_crop:h, :, :]
  632. else:
  633. crop_img = crop_img[0:h - top_crop, :, :]
  634. return crop_img
  635. def rad(x):
  636. """
  637. rad
  638. """
  639. return x * np.pi / 180
  640. def get_warpR(config):
  641. """
  642. get_warpR
  643. """
  644. anglex, angley, anglez, fov, w, h, r = \
  645. config.anglex, config.angley, config.anglez, config.fov, config.w, config.h, config.r
  646. if w > 69 and w < 112:
  647. anglex = anglex * 1.5
  648. z = np.sqrt(w**2 + h**2) / 2 / np.tan(rad(fov / 2))
  649. # Homogeneous coordinate transformation matrix
  650. rx = np.array([[1, 0, 0, 0],
  651. [0, np.cos(rad(anglex)), -np.sin(rad(anglex)), 0], [
  652. 0,
  653. -np.sin(rad(anglex)),
  654. np.cos(rad(anglex)),
  655. 0,
  656. ], [0, 0, 0, 1]], np.float32)
  657. ry = np.array([[np.cos(rad(angley)), 0, np.sin(rad(angley)), 0],
  658. [0, 1, 0, 0], [
  659. -np.sin(rad(angley)),
  660. 0,
  661. np.cos(rad(angley)),
  662. 0,
  663. ], [0, 0, 0, 1]], np.float32)
  664. rz = np.array([[np.cos(rad(anglez)), np.sin(rad(anglez)), 0, 0],
  665. [-np.sin(rad(anglez)), np.cos(rad(anglez)), 0, 0],
  666. [0, 0, 1, 0], [0, 0, 0, 1]], np.float32)
  667. r = rx.dot(ry).dot(rz)
  668. # generate 4 points
  669. pcenter = np.array([h / 2, w / 2, 0, 0], np.float32)
  670. p1 = np.array([0, 0, 0, 0], np.float32) - pcenter
  671. p2 = np.array([w, 0, 0, 0], np.float32) - pcenter
  672. p3 = np.array([0, h, 0, 0], np.float32) - pcenter
  673. p4 = np.array([w, h, 0, 0], np.float32) - pcenter
  674. dst1 = r.dot(p1)
  675. dst2 = r.dot(p2)
  676. dst3 = r.dot(p3)
  677. dst4 = r.dot(p4)
  678. list_dst = np.array([dst1, dst2, dst3, dst4])
  679. org = np.array([[0, 0], [w, 0], [0, h], [w, h]], np.float32)
  680. dst = np.zeros((4, 2), np.float32)
  681. # Project onto the image plane
  682. dst[:, 0] = list_dst[:, 0] * z / (z - list_dst[:, 2]) + pcenter[0]
  683. dst[:, 1] = list_dst[:, 1] * z / (z - list_dst[:, 2]) + pcenter[1]
  684. warpR = cv2.getPerspectiveTransform(org, dst)
  685. dst1, dst2, dst3, dst4 = dst
  686. r1 = int(min(dst1[1], dst2[1]))
  687. r2 = int(max(dst3[1], dst4[1]))
  688. c1 = int(min(dst1[0], dst3[0]))
  689. c2 = int(max(dst2[0], dst4[0]))
  690. try:
  691. ratio = min(1.0 * h / (r2 - r1), 1.0 * w / (c2 - c1))
  692. dx = -c1
  693. dy = -r1
  694. T1 = np.float32([[1., 0, dx], [0, 1., dy], [0, 0, 1.0 / ratio]])
  695. ret = T1.dot(warpR)
  696. except:
  697. ratio = 1.0
  698. T1 = np.float32([[1., 0, 0], [0, 1., 0], [0, 0, 1.]])
  699. ret = T1
  700. return ret, (-r1, -c1), ratio, dst
  701. def get_warpAffine(config):
  702. """
  703. get_warpAffine
  704. """
  705. anglez = config.anglez
  706. rz = np.array([[np.cos(rad(anglez)), np.sin(rad(anglez)), 0],
  707. [-np.sin(rad(anglez)), np.cos(rad(anglez)), 0]], np.float32)
  708. return rz