result.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  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 os
  15. from pathlib import Path
  16. from typing import Dict
  17. import copy
  18. import math
  19. import random
  20. import numpy as np
  21. import cv2
  22. import PIL
  23. from PIL import Image, ImageDraw, ImageFont
  24. from ....utils.fonts import PINGFANG_FONT_FILE_PATH, create_font
  25. from ...common.result import BaseCVResult, StrMixin, JsonMixin
  26. class OCRResult(BaseCVResult):
  27. """OCR result"""
  28. def _get_input_fn(self):
  29. fn = super()._get_input_fn()
  30. if (page_idx := self["page_index"]) is not None:
  31. fp = Path(fn)
  32. stem, suffix = fp.stem, fp.suffix
  33. return f"{stem}_{page_idx}{suffix}"
  34. else:
  35. return fn
  36. def get_minarea_rect(self, points: np.ndarray) -> np.ndarray:
  37. """
  38. Get the minimum area rectangle for the given points using OpenCV.
  39. Args:
  40. points (np.ndarray): An array of 2D points.
  41. Returns:
  42. np.ndarray: An array of 2D points representing the corners of the minimum area rectangle
  43. in a specific order (clockwise or counterclockwise starting from the top-left corner).
  44. """
  45. bounding_box = cv2.minAreaRect(points)
  46. points = sorted(list(cv2.boxPoints(bounding_box)), key=lambda x: x[0])
  47. index_a, index_b, index_c, index_d = 0, 1, 2, 3
  48. if points[1][1] > points[0][1]:
  49. index_a = 0
  50. index_d = 1
  51. else:
  52. index_a = 1
  53. index_d = 0
  54. if points[3][1] > points[2][1]:
  55. index_b = 2
  56. index_c = 3
  57. else:
  58. index_b = 3
  59. index_c = 2
  60. box = np.array(
  61. [points[index_a], points[index_b], points[index_c], points[index_d]]
  62. ).astype(np.int32)
  63. return box
  64. def _to_img(self) -> Dict[str, Image.Image]:
  65. """
  66. Converts the internal data to a PIL Image with detection and recognition results.
  67. Returns:
  68. Dict[Image.Image]: A dictionary containing two images: 'doc_preprocessor_res' and 'ocr_res_img'.
  69. """
  70. boxes = self["rec_polys"]
  71. txts = self["rec_texts"]
  72. image = self["doc_preprocessor_res"]["output_img"]
  73. h, w = image.shape[0:2]
  74. image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
  75. img_left = Image.fromarray(image_rgb)
  76. img_right = np.ones((h, w, 3), dtype=np.uint8) * 255
  77. random.seed(0)
  78. draw_left = ImageDraw.Draw(img_left)
  79. for idx, (box, txt) in enumerate(zip(boxes, txts)):
  80. try:
  81. color = (
  82. random.randint(0, 255),
  83. random.randint(0, 255),
  84. random.randint(0, 255),
  85. )
  86. box = np.array(box)
  87. if len(box) > 4:
  88. pts = [(x, y) for x, y in box.tolist()]
  89. draw_left.polygon(pts, outline=color, width=8)
  90. box = self.get_minarea_rect(box)
  91. height = int(0.5 * (max(box[:, 1]) - min(box[:, 1])))
  92. box[:2, 1] = np.mean(box[:, 1])
  93. box[2:, 1] = np.mean(box[:, 1]) + min(20, height)
  94. draw_left.polygon(box, fill=color)
  95. img_right_text = draw_box_txt_fine(
  96. (w, h), box, txt, PINGFANG_FONT_FILE_PATH
  97. )
  98. pts = np.array(box, np.int32).reshape((-1, 1, 2))
  99. cv2.polylines(img_right_text, [pts], True, color, 1)
  100. img_right = cv2.bitwise_and(img_right, img_right_text)
  101. except:
  102. continue
  103. img_left = Image.blend(Image.fromarray(image_rgb), img_left, 0.5)
  104. img_show = Image.new("RGB", (w * 2, h), (255, 255, 255))
  105. img_show.paste(img_left, (0, 0, w, h))
  106. img_show.paste(Image.fromarray(img_right), (w, 0, w * 2, h))
  107. model_settings = self["model_settings"]
  108. res_img_dict = {f"ocr_res_img": img_show}
  109. if model_settings["use_doc_preprocessor"]:
  110. res_img_dict.update(**self["doc_preprocessor_res"].img)
  111. return res_img_dict
  112. def _to_str(self, *args, **kwargs) -> Dict[str, str]:
  113. """Converts the instance's attributes to a dictionary and then to a string.
  114. Args:
  115. *args: Additional positional arguments passed to the base class method.
  116. **kwargs: Additional keyword arguments passed to the base class method.
  117. Returns:
  118. Dict[str, str]: A dictionary with the instance's attributes converted to strings.
  119. """
  120. data = {}
  121. data["input_path"] = self["input_path"]
  122. data["page_index"] = self["page_index"]
  123. data["model_settings"] = self["model_settings"]
  124. if self["model_settings"]["use_doc_preprocessor"]:
  125. data["doc_preprocessor_res"] = self["doc_preprocessor_res"].str["res"]
  126. data["dt_polys"] = (
  127. self["dt_polys"]
  128. if self["text_type"] == "seal"
  129. else np.array(self["dt_polys"])
  130. )
  131. data["text_det_params"] = self["text_det_params"]
  132. data["text_type"] = self["text_type"]
  133. if "textline_orientation_angles" in self:
  134. data["textline_orientation_angles"] = np.array(
  135. self["textline_orientation_angles"]
  136. )
  137. data["text_rec_score_thresh"] = self["text_rec_score_thresh"]
  138. data["rec_texts"] = self["rec_texts"]
  139. data["rec_scores"] = np.array(self["rec_scores"])
  140. data["rec_polys"] = (
  141. self["rec_polys"]
  142. if self["text_type"] == "seal"
  143. else np.array(self["rec_polys"])
  144. )
  145. data["rec_boxes"] = np.array(self["rec_boxes"])
  146. return JsonMixin._to_str(data, *args, **kwargs)
  147. def _to_json(self, *args, **kwargs) -> Dict[str, str]:
  148. """
  149. Converts the object's data to a JSON dictionary.
  150. Args:
  151. *args: Positional arguments passed to the JsonMixin._to_json method.
  152. **kwargs: Keyword arguments passed to the JsonMixin._to_json method.
  153. Returns:
  154. Dict[str, str]: A dictionary containing the object's data in JSON format.
  155. """
  156. data = {}
  157. data["input_path"] = self["input_path"]
  158. data["page_index"] = self["page_index"]
  159. data["model_settings"] = self["model_settings"]
  160. if self["model_settings"]["use_doc_preprocessor"]:
  161. data["doc_preprocessor_res"] = self["doc_preprocessor_res"].json["res"]
  162. data["dt_polys"] = self["dt_polys"]
  163. data["text_det_params"] = self["text_det_params"]
  164. data["text_type"] = self["text_type"]
  165. if "textline_orientation_angles" in self:
  166. data["textline_orientation_angles"] = self["textline_orientation_angles"]
  167. data["text_rec_score_thresh"] = self["text_rec_score_thresh"]
  168. data["rec_texts"] = self["rec_texts"]
  169. data["rec_scores"] = self["rec_scores"]
  170. data["rec_polys"] = self["rec_polys"]
  171. data["rec_boxes"] = self["rec_boxes"]
  172. return JsonMixin._to_json(data, *args, **kwargs)
  173. # Adds a function comment according to Google Style Guide
  174. def draw_box_txt_fine(
  175. img_size: tuple, box: np.ndarray, txt: str, font_path: str
  176. ) -> np.ndarray:
  177. """
  178. Draws text in a box on an image with fine control over size and orientation.
  179. Args:
  180. img_size (tuple): The size of the output image (width, height).
  181. box (np.ndarray): A 4x2 numpy array defining the corners of the box in (x, y) order.
  182. txt (str): The text to draw inside the box.
  183. font_path (str): The path to the font file to use for drawing the text.
  184. Returns:
  185. np.ndarray: An image with the text drawn in the specified box.
  186. """
  187. box_height = int(
  188. math.sqrt((box[0][0] - box[3][0]) ** 2 + (box[0][1] - box[3][1]) ** 2)
  189. )
  190. box_width = int(
  191. math.sqrt((box[0][0] - box[1][0]) ** 2 + (box[0][1] - box[1][1]) ** 2)
  192. )
  193. if box_height > 2 * box_width and box_height > 30:
  194. img_text = Image.new("RGB", (box_height, box_width), (255, 255, 255))
  195. draw_text = ImageDraw.Draw(img_text)
  196. if txt:
  197. font = create_font(txt, (box_height, box_width), font_path)
  198. draw_text.text([0, 0], txt, fill=(0, 0, 0), font=font)
  199. img_text = img_text.transpose(Image.ROTATE_270)
  200. else:
  201. img_text = Image.new("RGB", (box_width, box_height), (255, 255, 255))
  202. draw_text = ImageDraw.Draw(img_text)
  203. if txt:
  204. font = create_font(txt, (box_width, box_height), font_path)
  205. draw_text.text([0, 0], txt, fill=(0, 0, 0), font=font)
  206. pts1 = np.float32(
  207. [[0, 0], [box_width, 0], [box_width, box_height], [0, box_height]]
  208. )
  209. pts2 = np.array(box, dtype=np.float32)
  210. M = cv2.getPerspectiveTransform(pts1, pts2)
  211. img_text = np.array(img_text, dtype=np.uint8)
  212. img_right_text = cv2.warpPerspective(
  213. img_text,
  214. M,
  215. img_size,
  216. flags=cv2.INTER_NEAREST,
  217. borderMode=cv2.BORDER_CONSTANT,
  218. borderValue=(255, 255, 255),
  219. )
  220. return img_right_text