east_process.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  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 json
  18. import sys
  19. import os
  20. __all__ = ['EASTProcessTrain']
  21. class EASTProcessTrain(object):
  22. def __init__(self,
  23. image_shape = [512, 512],
  24. background_ratio = 0.125,
  25. min_crop_side_ratio = 0.1,
  26. min_text_size = 10,
  27. **kwargs):
  28. self.input_size = image_shape[1]
  29. self.random_scale = np.array([0.5, 1, 2.0, 3.0])
  30. self.background_ratio = background_ratio
  31. self.min_crop_side_ratio = min_crop_side_ratio
  32. self.min_text_size = min_text_size
  33. def preprocess(self, im):
  34. input_size = self.input_size
  35. im_shape = im.shape
  36. im_size_min = np.min(im_shape[0:2])
  37. im_size_max = np.max(im_shape[0:2])
  38. im_scale = float(input_size) / float(im_size_max)
  39. im = cv2.resize(im, None, None, fx=im_scale, fy=im_scale)
  40. img_mean = [0.485, 0.456, 0.406]
  41. img_std = [0.229, 0.224, 0.225]
  42. # im = im[:, :, ::-1].astype(np.float32)
  43. im = im / 255
  44. im -= img_mean
  45. im /= img_std
  46. new_h, new_w, _ = im.shape
  47. im_padded = np.zeros((input_size, input_size, 3), dtype=np.float32)
  48. im_padded[:new_h, :new_w, :] = im
  49. im_padded = im_padded.transpose((2, 0, 1))
  50. im_padded = im_padded[np.newaxis, :]
  51. return im_padded, im_scale
  52. def rotate_im_poly(self, im, text_polys):
  53. """
  54. rotate image with 90 / 180 / 270 degre
  55. """
  56. im_w, im_h = im.shape[1], im.shape[0]
  57. dst_im = im.copy()
  58. dst_polys = []
  59. rand_degree_ratio = np.random.rand()
  60. rand_degree_cnt = 1
  61. if 0.333 < rand_degree_ratio < 0.666:
  62. rand_degree_cnt = 2
  63. elif rand_degree_ratio > 0.666:
  64. rand_degree_cnt = 3
  65. for i in range(rand_degree_cnt):
  66. dst_im = np.rot90(dst_im)
  67. rot_degree = -90 * rand_degree_cnt
  68. rot_angle = rot_degree * math.pi / 180.0
  69. n_poly = text_polys.shape[0]
  70. cx, cy = 0.5 * im_w, 0.5 * im_h
  71. ncx, ncy = 0.5 * dst_im.shape[1], 0.5 * dst_im.shape[0]
  72. for i in range(n_poly):
  73. wordBB = text_polys[i]
  74. poly = []
  75. for j in range(4):
  76. sx, sy = wordBB[j][0], wordBB[j][1]
  77. dx = math.cos(rot_angle) * (sx - cx)\
  78. - math.sin(rot_angle) * (sy - cy) + ncx
  79. dy = math.sin(rot_angle) * (sx - cx)\
  80. + math.cos(rot_angle) * (sy - cy) + ncy
  81. poly.append([dx, dy])
  82. dst_polys.append(poly)
  83. dst_polys = np.array(dst_polys, dtype=np.float32)
  84. return dst_im, dst_polys
  85. def polygon_area(self, poly):
  86. """
  87. compute area of a polygon
  88. :param poly:
  89. :return:
  90. """
  91. edge = [(poly[1][0] - poly[0][0]) * (poly[1][1] + poly[0][1]),
  92. (poly[2][0] - poly[1][0]) * (poly[2][1] + poly[1][1]),
  93. (poly[3][0] - poly[2][0]) * (poly[3][1] + poly[2][1]),
  94. (poly[0][0] - poly[3][0]) * (poly[0][1] + poly[3][1])]
  95. return np.sum(edge) / 2.
  96. def check_and_validate_polys(self, polys, tags, img_height, img_width):
  97. """
  98. check so that the text poly is in the same direction,
  99. and also filter some invalid polygons
  100. :param polys:
  101. :param tags:
  102. :return:
  103. """
  104. h, w = img_height, img_width
  105. if polys.shape[0] == 0:
  106. return polys
  107. polys[:, :, 0] = np.clip(polys[:, :, 0], 0, w - 1)
  108. polys[:, :, 1] = np.clip(polys[:, :, 1], 0, h - 1)
  109. validated_polys = []
  110. validated_tags = []
  111. for poly, tag in zip(polys, tags):
  112. p_area = self.polygon_area(poly)
  113. #invalid poly
  114. if abs(p_area) < 1:
  115. continue
  116. if p_area > 0:
  117. #'poly in wrong direction'
  118. if not tag:
  119. tag = True #reversed cases should be ignore
  120. poly = poly[(0, 3, 2, 1), :]
  121. validated_polys.append(poly)
  122. validated_tags.append(tag)
  123. return np.array(validated_polys), np.array(validated_tags)
  124. def draw_img_polys(self, img, polys):
  125. if len(img.shape) == 4:
  126. img = np.squeeze(img, axis=0)
  127. if img.shape[0] == 3:
  128. img = img.transpose((1, 2, 0))
  129. img[:, :, 2] += 123.68
  130. img[:, :, 1] += 116.78
  131. img[:, :, 0] += 103.94
  132. cv2.imwrite("tmp.jpg", img)
  133. img = cv2.imread("tmp.jpg")
  134. for box in polys:
  135. box = box.astype(np.int32).reshape((-1, 1, 2))
  136. cv2.polylines(img, [box], True, color=(255, 255, 0), thickness=2)
  137. import random
  138. ino = random.randint(0, 100)
  139. cv2.imwrite("tmp_%d.jpg" % ino, img)
  140. return
  141. def shrink_poly(self, poly, r):
  142. """
  143. fit a poly inside the origin poly, maybe bugs here...
  144. used for generate the score map
  145. :param poly: the text poly
  146. :param r: r in the paper
  147. :return: the shrinked poly
  148. """
  149. # shrink ratio
  150. R = 0.3
  151. # find the longer pair
  152. dist0 = np.linalg.norm(poly[0] - poly[1])
  153. dist1 = np.linalg.norm(poly[2] - poly[3])
  154. dist2 = np.linalg.norm(poly[0] - poly[3])
  155. dist3 = np.linalg.norm(poly[1] - poly[2])
  156. if dist0 + dist1 > dist2 + dist3:
  157. # first move (p0, p1), (p2, p3), then (p0, p3), (p1, p2)
  158. ## p0, p1
  159. theta = np.arctan2((poly[1][1] - poly[0][1]),
  160. (poly[1][0] - poly[0][0]))
  161. poly[0][0] += R * r[0] * np.cos(theta)
  162. poly[0][1] += R * r[0] * np.sin(theta)
  163. poly[1][0] -= R * r[1] * np.cos(theta)
  164. poly[1][1] -= R * r[1] * np.sin(theta)
  165. ## p2, p3
  166. theta = np.arctan2((poly[2][1] - poly[3][1]),
  167. (poly[2][0] - poly[3][0]))
  168. poly[3][0] += R * r[3] * np.cos(theta)
  169. poly[3][1] += R * r[3] * np.sin(theta)
  170. poly[2][0] -= R * r[2] * np.cos(theta)
  171. poly[2][1] -= R * r[2] * np.sin(theta)
  172. ## p0, p3
  173. theta = np.arctan2((poly[3][0] - poly[0][0]),
  174. (poly[3][1] - poly[0][1]))
  175. poly[0][0] += R * r[0] * np.sin(theta)
  176. poly[0][1] += R * r[0] * np.cos(theta)
  177. poly[3][0] -= R * r[3] * np.sin(theta)
  178. poly[3][1] -= R * r[3] * np.cos(theta)
  179. ## p1, p2
  180. theta = np.arctan2((poly[2][0] - poly[1][0]),
  181. (poly[2][1] - poly[1][1]))
  182. poly[1][0] += R * r[1] * np.sin(theta)
  183. poly[1][1] += R * r[1] * np.cos(theta)
  184. poly[2][0] -= R * r[2] * np.sin(theta)
  185. poly[2][1] -= R * r[2] * np.cos(theta)
  186. else:
  187. ## p0, p3
  188. # print poly
  189. theta = np.arctan2((poly[3][0] - poly[0][0]),
  190. (poly[3][1] - poly[0][1]))
  191. poly[0][0] += R * r[0] * np.sin(theta)
  192. poly[0][1] += R * r[0] * np.cos(theta)
  193. poly[3][0] -= R * r[3] * np.sin(theta)
  194. poly[3][1] -= R * r[3] * np.cos(theta)
  195. ## p1, p2
  196. theta = np.arctan2((poly[2][0] - poly[1][0]),
  197. (poly[2][1] - poly[1][1]))
  198. poly[1][0] += R * r[1] * np.sin(theta)
  199. poly[1][1] += R * r[1] * np.cos(theta)
  200. poly[2][0] -= R * r[2] * np.sin(theta)
  201. poly[2][1] -= R * r[2] * np.cos(theta)
  202. ## p0, p1
  203. theta = np.arctan2((poly[1][1] - poly[0][1]),
  204. (poly[1][0] - poly[0][0]))
  205. poly[0][0] += R * r[0] * np.cos(theta)
  206. poly[0][1] += R * r[0] * np.sin(theta)
  207. poly[1][0] -= R * r[1] * np.cos(theta)
  208. poly[1][1] -= R * r[1] * np.sin(theta)
  209. ## p2, p3
  210. theta = np.arctan2((poly[2][1] - poly[3][1]),
  211. (poly[2][0] - poly[3][0]))
  212. poly[3][0] += R * r[3] * np.cos(theta)
  213. poly[3][1] += R * r[3] * np.sin(theta)
  214. poly[2][0] -= R * r[2] * np.cos(theta)
  215. poly[2][1] -= R * r[2] * np.sin(theta)
  216. return poly
  217. def generate_quad(self, im_size, polys, tags):
  218. """
  219. Generate quadrangle.
  220. """
  221. h, w = im_size
  222. poly_mask = np.zeros((h, w), dtype=np.uint8)
  223. score_map = np.zeros((h, w), dtype=np.uint8)
  224. # (x1, y1, ..., x4, y4, short_edge_norm)
  225. geo_map = np.zeros((h, w, 9), dtype=np.float32)
  226. # mask used during traning, to ignore some hard areas
  227. training_mask = np.ones((h, w), dtype=np.uint8)
  228. for poly_idx, poly_tag in enumerate(zip(polys, tags)):
  229. poly = poly_tag[0]
  230. tag = poly_tag[1]
  231. r = [None, None, None, None]
  232. for i in range(4):
  233. dist1 = np.linalg.norm(poly[i] - poly[(i + 1) % 4])
  234. dist2 = np.linalg.norm(poly[i] - poly[(i - 1) % 4])
  235. r[i] = min(dist1, dist2)
  236. # score map
  237. shrinked_poly = self.shrink_poly(
  238. poly.copy(), r).astype(np.int32)[np.newaxis, :, :]
  239. cv2.fillPoly(score_map, shrinked_poly, 1)
  240. cv2.fillPoly(poly_mask, shrinked_poly, poly_idx + 1)
  241. # if the poly is too small, then ignore it during training
  242. poly_h = min(
  243. np.linalg.norm(poly[0] - poly[3]),
  244. np.linalg.norm(poly[1] - poly[2]))
  245. poly_w = min(
  246. np.linalg.norm(poly[0] - poly[1]),
  247. np.linalg.norm(poly[2] - poly[3]))
  248. if min(poly_h, poly_w) < self.min_text_size:
  249. cv2.fillPoly(training_mask,
  250. poly.astype(np.int32)[np.newaxis, :, :], 0)
  251. if tag:
  252. cv2.fillPoly(training_mask,
  253. poly.astype(np.int32)[np.newaxis, :, :], 0)
  254. xy_in_poly = np.argwhere(poly_mask == (poly_idx + 1))
  255. # geo map.
  256. y_in_poly = xy_in_poly[:, 0]
  257. x_in_poly = xy_in_poly[:, 1]
  258. poly[:, 0] = np.minimum(np.maximum(poly[:, 0], 0), w)
  259. poly[:, 1] = np.minimum(np.maximum(poly[:, 1], 0), h)
  260. for pno in range(4):
  261. geo_channel_beg = pno * 2
  262. geo_map[y_in_poly, x_in_poly, geo_channel_beg] =\
  263. x_in_poly - poly[pno, 0]
  264. geo_map[y_in_poly, x_in_poly, geo_channel_beg+1] =\
  265. y_in_poly - poly[pno, 1]
  266. geo_map[y_in_poly, x_in_poly, 8] = \
  267. 1.0 / max(min(poly_h, poly_w), 1.0)
  268. return score_map, geo_map, training_mask
  269. def crop_area(self,
  270. im,
  271. polys,
  272. tags,
  273. crop_background=False,
  274. max_tries=50):
  275. """
  276. make random crop from the input image
  277. :param im:
  278. :param polys:
  279. :param tags:
  280. :param crop_background:
  281. :param max_tries:
  282. :return:
  283. """
  284. h, w, _ = im.shape
  285. pad_h = h // 10
  286. pad_w = w // 10
  287. h_array = np.zeros((h + pad_h * 2), dtype=np.int32)
  288. w_array = np.zeros((w + pad_w * 2), dtype=np.int32)
  289. for poly in polys:
  290. poly = np.round(poly, decimals=0).astype(np.int32)
  291. minx = np.min(poly[:, 0])
  292. maxx = np.max(poly[:, 0])
  293. w_array[minx + pad_w:maxx + pad_w] = 1
  294. miny = np.min(poly[:, 1])
  295. maxy = np.max(poly[:, 1])
  296. h_array[miny + pad_h:maxy + pad_h] = 1
  297. # ensure the cropped area not across a text
  298. h_axis = np.where(h_array == 0)[0]
  299. w_axis = np.where(w_array == 0)[0]
  300. if len(h_axis) == 0 or len(w_axis) == 0:
  301. return im, polys, tags
  302. for i in range(max_tries):
  303. xx = np.random.choice(w_axis, size=2)
  304. xmin = np.min(xx) - pad_w
  305. xmax = np.max(xx) - pad_w
  306. xmin = np.clip(xmin, 0, w - 1)
  307. xmax = np.clip(xmax, 0, w - 1)
  308. yy = np.random.choice(h_axis, size=2)
  309. ymin = np.min(yy) - pad_h
  310. ymax = np.max(yy) - pad_h
  311. ymin = np.clip(ymin, 0, h - 1)
  312. ymax = np.clip(ymax, 0, h - 1)
  313. if xmax - xmin < self.min_crop_side_ratio * w or \
  314. ymax - ymin < self.min_crop_side_ratio * h:
  315. # area too small
  316. continue
  317. if polys.shape[0] != 0:
  318. poly_axis_in_area = (polys[:, :, 0] >= xmin)\
  319. & (polys[:, :, 0] <= xmax)\
  320. & (polys[:, :, 1] >= ymin)\
  321. & (polys[:, :, 1] <= ymax)
  322. selected_polys = np.where(
  323. np.sum(poly_axis_in_area, axis=1) == 4)[0]
  324. else:
  325. selected_polys = []
  326. if len(selected_polys) == 0:
  327. # no text in this area
  328. if crop_background:
  329. im = im[ymin:ymax + 1, xmin:xmax + 1, :]
  330. polys = []
  331. tags = []
  332. return im, polys, tags
  333. else:
  334. continue
  335. im = im[ymin:ymax + 1, xmin:xmax + 1, :]
  336. polys = polys[selected_polys]
  337. tags = tags[selected_polys]
  338. polys[:, :, 0] -= xmin
  339. polys[:, :, 1] -= ymin
  340. return im, polys, tags
  341. return im, polys, tags
  342. def crop_background_infor(self, im, text_polys, text_tags):
  343. im, text_polys, text_tags = self.crop_area(
  344. im, text_polys, text_tags, crop_background=True)
  345. if len(text_polys) > 0:
  346. return None
  347. # pad and resize image
  348. input_size = self.input_size
  349. im, ratio = self.preprocess(im)
  350. score_map = np.zeros((input_size, input_size), dtype=np.float32)
  351. geo_map = np.zeros((input_size, input_size, 9), dtype=np.float32)
  352. training_mask = np.ones((input_size, input_size), dtype=np.float32)
  353. return im, score_map, geo_map, training_mask
  354. def crop_foreground_infor(self, im, text_polys, text_tags):
  355. im, text_polys, text_tags = self.crop_area(
  356. im, text_polys, text_tags, crop_background=False)
  357. if text_polys.shape[0] == 0:
  358. return None
  359. #continue for all ignore case
  360. if np.sum((text_tags * 1.0)) >= text_tags.size:
  361. return None
  362. # pad and resize image
  363. input_size = self.input_size
  364. im, ratio = self.preprocess(im)
  365. text_polys[:, :, 0] *= ratio
  366. text_polys[:, :, 1] *= ratio
  367. _, _, new_h, new_w = im.shape
  368. # print(im.shape)
  369. # self.draw_img_polys(im, text_polys)
  370. score_map, geo_map, training_mask = self.generate_quad(
  371. (new_h, new_w), text_polys, text_tags)
  372. return im, score_map, geo_map, training_mask
  373. def __call__(self, data):
  374. im = data['image']
  375. text_polys = data['polys']
  376. text_tags = data['ignore_tags']
  377. if im is None:
  378. return None
  379. if text_polys.shape[0] == 0:
  380. return None
  381. #add rotate cases
  382. if np.random.rand() < 0.5:
  383. im, text_polys = self.rotate_im_poly(im, text_polys)
  384. h, w, _ = im.shape
  385. text_polys, text_tags = self.check_and_validate_polys(text_polys,
  386. text_tags, h, w)
  387. if text_polys.shape[0] == 0:
  388. return None
  389. # random scale this image
  390. rd_scale = np.random.choice(self.random_scale)
  391. im = cv2.resize(im, dsize=None, fx=rd_scale, fy=rd_scale)
  392. text_polys *= rd_scale
  393. if np.random.rand() < self.background_ratio:
  394. outs = self.crop_background_infor(im, text_polys, text_tags)
  395. else:
  396. outs = self.crop_foreground_infor(im, text_polys, text_tags)
  397. if outs is None:
  398. return None
  399. im, score_map, geo_map, training_mask = outs
  400. score_map = score_map[np.newaxis, ::4, ::4].astype(np.float32)
  401. geo_map = np.swapaxes(geo_map, 1, 2)
  402. geo_map = np.swapaxes(geo_map, 1, 0)
  403. geo_map = geo_map[:, ::4, ::4].astype(np.float32)
  404. training_mask = training_mask[np.newaxis, ::4, ::4]
  405. training_mask = training_mask.astype(np.float32)
  406. data['image'] = im[0]
  407. data['score_map'] = score_map
  408. data['geo_map'] = geo_map
  409. data['training_mask'] = training_mask
  410. # print(im.shape, score_map.shape, geo_map.shape, training_mask.shape)
  411. return data