result.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. # copyright (c) 2024 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 random
  16. import numpy as np
  17. import cv2
  18. import PIL
  19. from PIL import Image, ImageDraw, ImageFont
  20. from ....utils.fonts import PINGFANG_FONT_FILE_PATH
  21. from ..components import CVResult
  22. class OCRResult(CVResult):
  23. def save_to_img(self, save_path, *args, **kwargs):
  24. if not str(save_path).lower().endswith((".jpg", ".png")):
  25. img_id = self["img_id"]
  26. save_path = save_path + "/res_ocr_%d.jpg" % img_id
  27. super().save_to_img(save_path, *args, **kwargs)
  28. def get_minarea_rect(self, points):
  29. bounding_box = cv2.minAreaRect(points)
  30. points = sorted(list(cv2.boxPoints(bounding_box)), key=lambda x: x[0])
  31. index_a, index_b, index_c, index_d = 0, 1, 2, 3
  32. if points[1][1] > points[0][1]:
  33. index_a = 0
  34. index_d = 1
  35. else:
  36. index_a = 1
  37. index_d = 0
  38. if points[3][1] > points[2][1]:
  39. index_b = 2
  40. index_c = 3
  41. else:
  42. index_b = 3
  43. index_c = 2
  44. box = np.array(
  45. [points[index_a], points[index_b], points[index_c], points[index_d]]
  46. ).astype(np.int32)
  47. return box
  48. def _to_img(self):
  49. """draw ocr result"""
  50. # TODO(gaotingquan): mv to postprocess
  51. drop_score = 0.5
  52. boxes = self["dt_polys"]
  53. txts = self["rec_text"]
  54. scores = self["rec_score"]
  55. image = self['input_img']
  56. h, w = image.shape[0:2]
  57. image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
  58. img_left = Image.fromarray(image_rgb)
  59. img_right = np.ones((h, w, 3), dtype=np.uint8) * 255
  60. random.seed(0)
  61. draw_left = ImageDraw.Draw(img_left)
  62. if txts is None or len(txts) != len(boxes):
  63. txts = [None] * len(boxes)
  64. for idx, (box, txt) in enumerate(zip(boxes, txts)):
  65. try:
  66. if scores is not None and scores[idx] < drop_score:
  67. continue
  68. color = (
  69. random.randint(0, 255),
  70. random.randint(0, 255),
  71. random.randint(0, 255),
  72. )
  73. box = np.array(box)
  74. if len(box) > 4:
  75. pts = [(x, y) for x, y in box.tolist()]
  76. draw_left.polygon(pts, outline=color, width=8)
  77. box = self.get_minarea_rect(box)
  78. height = int(0.5 * (max(box[:, 1]) - min(box[:, 1])))
  79. box[:2, 1] = np.mean(box[:, 1])
  80. box[2:, 1] = np.mean(box[:, 1]) + min(20, height)
  81. draw_left.polygon(box, fill=color)
  82. img_right_text = draw_box_txt_fine(
  83. (w, h), box, txt, PINGFANG_FONT_FILE_PATH
  84. )
  85. pts = np.array(box, np.int32).reshape((-1, 1, 2))
  86. cv2.polylines(img_right_text, [pts], True, color, 1)
  87. img_right = cv2.bitwise_and(img_right, img_right_text)
  88. except:
  89. continue
  90. img_left = Image.blend(Image.fromarray(image_rgb), img_left, 0.5)
  91. img_show = Image.new("RGB", (w * 2, h), (255, 255, 255))
  92. img_show.paste(img_left, (0, 0, w, h))
  93. img_show.paste(Image.fromarray(img_right), (w, 0, w * 2, h))
  94. return img_show
  95. def draw_box_txt_fine(img_size, box, txt, font_path):
  96. """draw box text"""
  97. box_height = int(
  98. math.sqrt((box[0][0] - box[3][0]) ** 2 + (box[0][1] - box[3][1]) ** 2)
  99. )
  100. box_width = int(
  101. math.sqrt((box[0][0] - box[1][0]) ** 2 + (box[0][1] - box[1][1]) ** 2)
  102. )
  103. if box_height > 2 * box_width and box_height > 30:
  104. img_text = Image.new("RGB", (box_height, box_width), (255, 255, 255))
  105. draw_text = ImageDraw.Draw(img_text)
  106. if txt:
  107. font = create_font(txt, (box_height, box_width), font_path)
  108. draw_text.text([0, 0], txt, fill=(0, 0, 0), font=font)
  109. img_text = img_text.transpose(Image.ROTATE_270)
  110. else:
  111. img_text = Image.new("RGB", (box_width, box_height), (255, 255, 255))
  112. draw_text = ImageDraw.Draw(img_text)
  113. if txt:
  114. font = create_font(txt, (box_width, box_height), font_path)
  115. draw_text.text([0, 0], txt, fill=(0, 0, 0), font=font)
  116. pts1 = np.float32(
  117. [[0, 0], [box_width, 0], [box_width, box_height], [0, box_height]]
  118. )
  119. pts2 = np.array(box, dtype=np.float32)
  120. M = cv2.getPerspectiveTransform(pts1, pts2)
  121. img_text = np.array(img_text, dtype=np.uint8)
  122. img_right_text = cv2.warpPerspective(
  123. img_text,
  124. M,
  125. img_size,
  126. flags=cv2.INTER_NEAREST,
  127. borderMode=cv2.BORDER_CONSTANT,
  128. borderValue=(255, 255, 255),
  129. )
  130. return img_right_text
  131. def create_font(txt, sz, font_path):
  132. """create font"""
  133. font_size = int(sz[1] * 0.8)
  134. font = ImageFont.truetype(font_path, font_size, encoding="utf-8")
  135. if int(PIL.__version__.split(".")[0]) < 10:
  136. length = font.getsize(txt)[0]
  137. else:
  138. length = font.getlength(txt)
  139. if length > sz[0]:
  140. font_size = int(font_size * sz[0] / length)
  141. font = ImageFont.truetype(font_path, font_size, encoding="utf-8")
  142. return font