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