result.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  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. from pathlib import Path
  15. import math
  16. import random
  17. import numpy as np
  18. import cv2
  19. import PIL
  20. from PIL import Image, ImageDraw, ImageFont
  21. from ....utils.fonts import PINGFANG_FONT_FILE_PATH, create_font
  22. from ...common.result import BaseCVResult
  23. class OCRResult(BaseCVResult):
  24. """OCR result"""
  25. def save_to_img(self, save_path: str, *args, **kwargs) -> None:
  26. """
  27. Save the image to the specified path with the appropriate extension.
  28. If the save_path does not end with '.jpg' or '.png', it appends '_res_ocr_<img_id>.jpg'
  29. to the path where <img_id> is the id of the image.
  30. Args:
  31. save_path (str): The path to save the image.
  32. *args: Additional positional arguments.
  33. **kwargs: Additional keyword arguments.
  34. """
  35. input_params = self["input_params"]
  36. img_id = self["img_id"]
  37. if input_params["use_doc_preprocessor"]:
  38. save_img_path = Path(save_path) / f"doc_preprocessor_result_img_{img_id}.jpg"
  39. self["doc_preprocessor_res"].save_to_img(save_img_path)
  40. if not str(save_path).lower().endswith((".jpg", ".png")):
  41. save_path = Path(save_path) / f"res_ocr_{img_id}.jpg"
  42. super().save_to_img(save_path, *args, **kwargs)
  43. def get_minarea_rect(self, points: np.ndarray) -> np.ndarray:
  44. """
  45. Get the minimum area rectangle for the given points using OpenCV.
  46. Args:
  47. points (np.ndarray): An array of 2D points.
  48. Returns:
  49. np.ndarray: An array of 2D points representing the corners of the minimum area rectangle
  50. in a specific order (clockwise or counterclockwise starting from the top-left corner).
  51. """
  52. bounding_box = cv2.minAreaRect(points)
  53. points = sorted(list(cv2.boxPoints(bounding_box)), key=lambda x: x[0])
  54. index_a, index_b, index_c, index_d = 0, 1, 2, 3
  55. if points[1][1] > points[0][1]:
  56. index_a = 0
  57. index_d = 1
  58. else:
  59. index_a = 1
  60. index_d = 0
  61. if points[3][1] > points[2][1]:
  62. index_b = 2
  63. index_c = 3
  64. else:
  65. index_b = 3
  66. index_c = 2
  67. box = np.array(
  68. [points[index_a], points[index_b], points[index_c], points[index_d]]
  69. ).astype(np.int32)
  70. return box
  71. def _to_img(self) -> PIL.Image:
  72. """
  73. Converts the internal data to a PIL Image with detection and recognition results.
  74. Returns:
  75. PIL.Image: An image with detection boxes, texts, and scores blended on it.
  76. """
  77. # TODO(gaotingquan): mv to postprocess
  78. drop_score = 0.5
  79. boxes = self["dt_polys"]
  80. txts = self["rec_text"]
  81. scores = self["rec_score"]
  82. image = self["doc_preprocessor_image"]
  83. h, w = image.shape[0:2]
  84. image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
  85. img_left = Image.fromarray(image_rgb)
  86. img_right = np.ones((h, w, 3), dtype=np.uint8) * 255
  87. random.seed(0)
  88. draw_left = ImageDraw.Draw(img_left)
  89. if txts is None or len(txts) != len(boxes):
  90. txts = [None] * len(boxes)
  91. for idx, (box, txt) in enumerate(zip(boxes, txts)):
  92. try:
  93. if scores is not None and scores[idx] < drop_score:
  94. continue
  95. color = (
  96. random.randint(0, 255),
  97. random.randint(0, 255),
  98. random.randint(0, 255),
  99. )
  100. box = np.array(box)
  101. if len(box) > 4:
  102. pts = [(x, y) for x, y in box.tolist()]
  103. draw_left.polygon(pts, outline=color, width=8)
  104. box = self.get_minarea_rect(box)
  105. height = int(0.5 * (max(box[:, 1]) - min(box[:, 1])))
  106. box[:2, 1] = np.mean(box[:, 1])
  107. box[2:, 1] = np.mean(box[:, 1]) + min(20, height)
  108. draw_left.polygon(box, fill=color)
  109. img_right_text = draw_box_txt_fine(
  110. (w, h), box, txt, PINGFANG_FONT_FILE_PATH
  111. )
  112. pts = np.array(box, np.int32).reshape((-1, 1, 2))
  113. cv2.polylines(img_right_text, [pts], True, color, 1)
  114. img_right = cv2.bitwise_and(img_right, img_right_text)
  115. except:
  116. continue
  117. img_left = Image.blend(Image.fromarray(image_rgb), img_left, 0.5)
  118. img_show = Image.new("RGB", (w * 2, h), (255, 255, 255))
  119. img_show.paste(img_left, (0, 0, w, h))
  120. img_show.paste(Image.fromarray(img_right), (w, 0, w * 2, h))
  121. return img_show
  122. # Adds a function comment according to Google Style Guide
  123. def draw_box_txt_fine(
  124. img_size: tuple, box: np.ndarray, txt: str, font_path: str
  125. ) -> np.ndarray:
  126. """
  127. Draws text in a box on an image with fine control over size and orientation.
  128. Args:
  129. img_size (tuple): The size of the output image (width, height).
  130. box (np.ndarray): A 4x2 numpy array defining the corners of the box in (x, y) order.
  131. txt (str): The text to draw inside the box.
  132. font_path (str): The path to the font file to use for drawing the text.
  133. Returns:
  134. np.ndarray: An image with the text drawn in the specified box.
  135. """
  136. box_height = int(
  137. math.sqrt((box[0][0] - box[3][0]) ** 2 + (box[0][1] - box[3][1]) ** 2)
  138. )
  139. box_width = int(
  140. math.sqrt((box[0][0] - box[1][0]) ** 2 + (box[0][1] - box[1][1]) ** 2)
  141. )
  142. if box_height > 2 * box_width and box_height > 30:
  143. img_text = Image.new("RGB", (box_height, box_width), (255, 255, 255))
  144. draw_text = ImageDraw.Draw(img_text)
  145. if txt:
  146. font = create_font(txt, (box_height, box_width), font_path)
  147. draw_text.text([0, 0], txt, fill=(0, 0, 0), font=font)
  148. img_text = img_text.transpose(Image.ROTATE_270)
  149. else:
  150. img_text = Image.new("RGB", (box_width, box_height), (255, 255, 255))
  151. draw_text = ImageDraw.Draw(img_text)
  152. if txt:
  153. font = create_font(txt, (box_width, box_height), font_path)
  154. draw_text.text([0, 0], txt, fill=(0, 0, 0), font=font)
  155. pts1 = np.float32(
  156. [[0, 0], [box_width, 0], [box_width, box_height], [0, box_height]]
  157. )
  158. pts2 = np.array(box, dtype=np.float32)
  159. M = cv2.getPerspectiveTransform(pts1, pts2)
  160. img_text = np.array(img_text, dtype=np.uint8)
  161. img_right_text = cv2.warpPerspective(
  162. img_text,
  163. M,
  164. img_size,
  165. flags=cv2.INTER_NEAREST,
  166. borderMode=cv2.BORDER_CONSTANT,
  167. borderValue=(255, 255, 255),
  168. )
  169. return img_right_text