east_process.py 17 KB

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