craft_utils.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. """
  2. Copyright (c) 2019-present NAVER Corp.
  3. MIT License
  4. """
  5. # -*- coding: utf-8 -*-
  6. import numpy as np
  7. import cv2
  8. import math
  9. """ auxilary functions """
  10. # unwarp corodinates
  11. def warpCoord(Minv, pt):
  12. out = np.matmul(Minv, (pt[0], pt[1], 1))
  13. return np.array([out[0]/out[2], out[1]/out[2]])
  14. """ end of auxilary functions """
  15. def getDetBoxes_core(textmap, linkmap, text_threshold, link_threshold, low_text):
  16. # prepare data
  17. linkmap = linkmap.copy()
  18. textmap = textmap.copy()
  19. img_h, img_w = textmap.shape
  20. """ labeling method """
  21. ret, text_score = cv2.threshold(textmap, low_text, 1, 0)
  22. ret, link_score = cv2.threshold(linkmap, link_threshold, 1, 0)
  23. text_score_comb = np.clip(text_score + link_score, 0, 1)
  24. nLabels, labels, stats, centroids = cv2.connectedComponentsWithStats(text_score_comb.astype(np.uint8), connectivity=4)
  25. det = []
  26. mapper = []
  27. for k in range(1,nLabels):
  28. # size filtering
  29. size = stats[k, cv2.CC_STAT_AREA]
  30. if size < 10: continue
  31. # thresholding
  32. if np.max(textmap[labels==k]) < text_threshold: continue
  33. # make segmentation map
  34. segmap = np.zeros(textmap.shape, dtype=np.uint8)
  35. segmap[labels==k] = 255
  36. segmap[np.logical_and(link_score==1, text_score==0)] = 0 # remove link area
  37. x, y = stats[k, cv2.CC_STAT_LEFT], stats[k, cv2.CC_STAT_TOP]
  38. w, h = stats[k, cv2.CC_STAT_WIDTH], stats[k, cv2.CC_STAT_HEIGHT]
  39. niter = int(math.sqrt(size * min(w, h) / (w * h)) * 2)
  40. sx, ex, sy, ey = x - niter, x + w + niter + 1, y - niter, y + h + niter + 1
  41. # boundary check
  42. if sx < 0 : sx = 0
  43. if sy < 0 : sy = 0
  44. if ex >= img_w: ex = img_w
  45. if ey >= img_h: ey = img_h
  46. kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(1 + niter, 1 + niter))
  47. segmap[sy:ey, sx:ex] = cv2.dilate(segmap[sy:ey, sx:ex], kernel)
  48. # make box
  49. np_contours = np.roll(np.array(np.where(segmap!=0)),1,axis=0).transpose().reshape(-1,2)
  50. rectangle = cv2.minAreaRect(np_contours)
  51. box = cv2.boxPoints(rectangle)
  52. # align diamond-shape
  53. w, h = np.linalg.norm(box[0] - box[1]), np.linalg.norm(box[1] - box[2])
  54. box_ratio = max(w, h) / (min(w, h) + 1e-5)
  55. if abs(1 - box_ratio) <= 0.1:
  56. l, r = min(np_contours[:,0]), max(np_contours[:,0])
  57. t, b = min(np_contours[:,1]), max(np_contours[:,1])
  58. box = np.array([[l, t], [r, t], [r, b], [l, b]], dtype=np.float32)
  59. # make clock-wise order
  60. startidx = box.sum(axis=1).argmin()
  61. box = np.roll(box, 4-startidx, 0)
  62. box = np.array(box)
  63. det.append(box)
  64. mapper.append(k)
  65. return det, labels, mapper
  66. def getPoly_core(boxes, labels, mapper, linkmap):
  67. # configs
  68. num_cp = 5
  69. max_len_ratio = 0.7
  70. expand_ratio = 1.45
  71. max_r = 2.0
  72. step_r = 0.2
  73. polys = []
  74. for k, box in enumerate(boxes):
  75. # size filter for small instance
  76. w, h = int(np.linalg.norm(box[0] - box[1]) + 1), int(np.linalg.norm(box[1] - box[2]) + 1)
  77. if w < 10 or h < 10:
  78. polys.append(None); continue
  79. # warp image
  80. tar = np.float32([[0,0],[w,0],[w,h],[0,h]])
  81. M = cv2.getPerspectiveTransform(box, tar)
  82. word_label = cv2.warpPerspective(labels, M, (w, h), flags=cv2.INTER_NEAREST)
  83. try:
  84. Minv = np.linalg.inv(M)
  85. except:
  86. polys.append(None); continue
  87. # binarization for selected label
  88. cur_label = mapper[k]
  89. word_label[word_label != cur_label] = 0
  90. word_label[word_label > 0] = 1
  91. """ Polygon generation """
  92. # find top/bottom contours
  93. cp = []
  94. max_len = -1
  95. for i in range(w):
  96. region = np.where(word_label[:,i] != 0)[0]
  97. if len(region) < 2 : continue
  98. cp.append((i, region[0], region[-1]))
  99. length = region[-1] - region[0] + 1
  100. if length > max_len: max_len = length
  101. # pass if max_len is similar to h
  102. if h * max_len_ratio < max_len:
  103. polys.append(None); continue
  104. # get pivot points with fixed length
  105. tot_seg = num_cp * 2 + 1
  106. seg_w = w / tot_seg # segment width
  107. pp = [None] * num_cp # init pivot points
  108. cp_section = [[0, 0]] * tot_seg
  109. seg_height = [0] * num_cp
  110. seg_num = 0
  111. num_sec = 0
  112. prev_h = -1
  113. for i in range(0,len(cp)):
  114. (x, sy, ey) = cp[i]
  115. if (seg_num + 1) * seg_w <= x and seg_num <= tot_seg:
  116. # average previous segment
  117. if num_sec == 0: break
  118. cp_section[seg_num] = [cp_section[seg_num][0] / num_sec, cp_section[seg_num][1] / num_sec]
  119. num_sec = 0
  120. # reset variables
  121. seg_num += 1
  122. prev_h = -1
  123. # accumulate center points
  124. cy = (sy + ey) * 0.5
  125. cur_h = ey - sy + 1
  126. cp_section[seg_num] = [cp_section[seg_num][0] + x, cp_section[seg_num][1] + cy]
  127. num_sec += 1
  128. if seg_num % 2 == 0: continue # No polygon area
  129. if prev_h < cur_h:
  130. pp[int((seg_num - 1)/2)] = (x, cy)
  131. seg_height[int((seg_num - 1)/2)] = cur_h
  132. prev_h = cur_h
  133. # processing last segment
  134. if num_sec != 0:
  135. cp_section[-1] = [cp_section[-1][0] / num_sec, cp_section[-1][1] / num_sec]
  136. # pass if num of pivots is not sufficient or segment widh is smaller than character height
  137. if None in pp or seg_w < np.max(seg_height) * 0.25:
  138. polys.append(None); continue
  139. # calc median maximum of pivot points
  140. half_char_h = np.median(seg_height) * expand_ratio / 2
  141. # calc gradiant and apply to make horizontal pivots
  142. new_pp = []
  143. for i, (x, cy) in enumerate(pp):
  144. dx = cp_section[i * 2 + 2][0] - cp_section[i * 2][0]
  145. dy = cp_section[i * 2 + 2][1] - cp_section[i * 2][1]
  146. if dx == 0: # gradient if zero
  147. new_pp.append([x, cy - half_char_h, x, cy + half_char_h])
  148. continue
  149. rad = - math.atan2(dy, dx)
  150. c, s = half_char_h * math.cos(rad), half_char_h * math.sin(rad)
  151. new_pp.append([x - s, cy - c, x + s, cy + c])
  152. # get edge points to cover character heatmaps
  153. isSppFound, isEppFound = False, False
  154. grad_s = (pp[1][1] - pp[0][1]) / (pp[1][0] - pp[0][0]) + (pp[2][1] - pp[1][1]) / (pp[2][0] - pp[1][0])
  155. grad_e = (pp[-2][1] - pp[-1][1]) / (pp[-2][0] - pp[-1][0]) + (pp[-3][1] - pp[-2][1]) / (pp[-3][0] - pp[-2][0])
  156. for r in np.arange(0.5, max_r, step_r):
  157. dx = 2 * half_char_h * r
  158. if not isSppFound:
  159. line_img = np.zeros(word_label.shape, dtype=np.uint8)
  160. dy = grad_s * dx
  161. p = np.array(new_pp[0]) - np.array([dx, dy, dx, dy])
  162. cv2.line(line_img, (int(p[0]), int(p[1])), (int(p[2]), int(p[3])), 1, thickness=1)
  163. if np.sum(np.logical_and(word_label, line_img)) == 0 or r + 2 * step_r >= max_r:
  164. spp = p
  165. isSppFound = True
  166. if not isEppFound:
  167. line_img = np.zeros(word_label.shape, dtype=np.uint8)
  168. dy = grad_e * dx
  169. p = np.array(new_pp[-1]) + np.array([dx, dy, dx, dy])
  170. cv2.line(line_img, (int(p[0]), int(p[1])), (int(p[2]), int(p[3])), 1, thickness=1)
  171. if np.sum(np.logical_and(word_label, line_img)) == 0 or r + 2 * step_r >= max_r:
  172. epp = p
  173. isEppFound = True
  174. if isSppFound and isEppFound:
  175. break
  176. # pass if boundary of polygon is not found
  177. if not (isSppFound and isEppFound):
  178. polys.append(None); continue
  179. # make final polygon
  180. poly = []
  181. poly.append(warpCoord(Minv, (spp[0], spp[1])))
  182. for p in new_pp:
  183. poly.append(warpCoord(Minv, (p[0], p[1])))
  184. poly.append(warpCoord(Minv, (epp[0], epp[1])))
  185. poly.append(warpCoord(Minv, (epp[2], epp[3])))
  186. for p in reversed(new_pp):
  187. poly.append(warpCoord(Minv, (p[2], p[3])))
  188. poly.append(warpCoord(Minv, (spp[2], spp[3])))
  189. # add to final result
  190. polys.append(np.array(poly))
  191. return polys
  192. def getDetBoxes(textmap, linkmap, text_threshold, link_threshold, low_text, poly=False):
  193. boxes, labels, mapper = getDetBoxes_core(textmap, linkmap, text_threshold, link_threshold, low_text)
  194. if poly:
  195. polys = getPoly_core(boxes, labels, mapper, linkmap)
  196. else:
  197. polys = [None] * len(boxes)
  198. return boxes, polys
  199. def adjustResultCoordinates(polys, ratio_w, ratio_h, ratio_net = 2):
  200. if len(polys) > 0:
  201. polys = np.array(polys)
  202. for k in range(len(polys)):
  203. if polys[k] is not None:
  204. polys[k] *= (ratio_w * ratio_net, ratio_h * ratio_net)
  205. return polys