rec_img_aug.py 27 KB

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