result.py 6.9 KB

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