ocr.py 5.2 KB

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