result.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. # Copyright (c) 2024 PaddlePaddle Authors. All Rights Reserved.
  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. from pathlib import Path
  17. from typing import Dict
  18. import numpy as np
  19. from PIL import Image, ImageDraw
  20. from ....utils.deps import class_requires_deps, function_requires_deps, is_dep_available
  21. from ....utils.fonts import SIMFANG_FONT_FILE_PATH, create_font, create_font_vertical
  22. from ...common.result import BaseCVResult, JsonMixin
  23. if is_dep_available("opencv-contrib-python"):
  24. import cv2
  25. @class_requires_deps("opencv-contrib-python")
  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. box_pts = [(int(x), int(y)) for x, y in box.tolist()]
  95. draw_left.polygon(box_pts, fill=color)
  96. img_right_text = draw_box_txt_fine(
  97. (w, h), box, txt, SIMFANG_FONT_FILE_PATH
  98. )
  99. pts = np.array(box, np.int32).reshape((-1, 1, 2))
  100. cv2.polylines(img_right_text, [pts], True, color, 1)
  101. img_right = cv2.bitwise_and(img_right, img_right_text)
  102. except:
  103. continue
  104. img_left = Image.blend(Image.fromarray(image_rgb), img_left, 0.5)
  105. img_show = Image.new("RGB", (w * 2, h), (255, 255, 255))
  106. img_show.paste(img_left, (0, 0, w, h))
  107. img_show.paste(Image.fromarray(img_right), (w, 0, w * 2, h))
  108. model_settings = self["model_settings"]
  109. res_img_dict = {f"ocr_res_img": img_show}
  110. if model_settings["use_doc_preprocessor"]:
  111. res_img_dict.update(**self["doc_preprocessor_res"].img)
  112. return res_img_dict
  113. def _to_str(self, *args, **kwargs) -> Dict[str, str]:
  114. """Converts the instance's attributes to a dictionary and then to a string.
  115. Args:
  116. *args: Additional positional arguments passed to the base class method.
  117. **kwargs: Additional keyword arguments passed to the base class method.
  118. Returns:
  119. Dict[str, str]: A dictionary with the instance's attributes converted to strings.
  120. """
  121. data = {}
  122. data["input_path"] = self["input_path"]
  123. data["page_index"] = self["page_index"]
  124. data["model_settings"] = self["model_settings"]
  125. if self["model_settings"]["use_doc_preprocessor"]:
  126. data["doc_preprocessor_res"] = self["doc_preprocessor_res"].str["res"]
  127. data["dt_polys"] = (
  128. self["dt_polys"]
  129. if self["text_type"] == "seal"
  130. else np.array(self["dt_polys"])
  131. )
  132. data["text_det_params"] = self["text_det_params"]
  133. data["text_type"] = self["text_type"]
  134. if "textline_orientation_angles" in self:
  135. data["textline_orientation_angles"] = np.array(
  136. self["textline_orientation_angles"]
  137. )
  138. data["text_rec_score_thresh"] = self["text_rec_score_thresh"]
  139. data["rec_texts"] = self["rec_texts"]
  140. data["rec_scores"] = np.array(self["rec_scores"])
  141. data["rec_polys"] = (
  142. self["rec_polys"]
  143. if self["text_type"] == "seal"
  144. else np.array(self["rec_polys"])
  145. )
  146. data["rec_boxes"] = np.array(self["rec_boxes"])
  147. return JsonMixin._to_str(data, *args, **kwargs)
  148. def _to_json(self, *args, **kwargs) -> Dict[str, str]:
  149. """
  150. Converts the object's data to a JSON dictionary.
  151. Args:
  152. *args: Positional arguments passed to the JsonMixin._to_json method.
  153. **kwargs: Keyword arguments passed to the JsonMixin._to_json method.
  154. Returns:
  155. Dict[str, str]: A dictionary containing the object's data in JSON format.
  156. """
  157. data = {}
  158. data["input_path"] = self["input_path"]
  159. data["page_index"] = self["page_index"]
  160. data["model_settings"] = self["model_settings"]
  161. if self["model_settings"]["use_doc_preprocessor"]:
  162. data["doc_preprocessor_res"] = self["doc_preprocessor_res"].json["res"]
  163. data["dt_polys"] = self["dt_polys"]
  164. data["text_det_params"] = self["text_det_params"]
  165. data["text_type"] = self["text_type"]
  166. if "textline_orientation_angles" in self:
  167. data["textline_orientation_angles"] = self["textline_orientation_angles"]
  168. data["text_rec_score_thresh"] = self["text_rec_score_thresh"]
  169. data["rec_texts"] = self["rec_texts"]
  170. data["rec_scores"] = self["rec_scores"]
  171. data["rec_polys"] = self["rec_polys"]
  172. data["rec_boxes"] = self["rec_boxes"]
  173. return JsonMixin._to_json(data, *args, **kwargs)
  174. # Adds a function comment according to Google Style Guide
  175. @function_requires_deps("opencv-contrib-python")
  176. def draw_box_txt_fine(
  177. img_size: tuple, box: np.ndarray, txt: str, font_path: str
  178. ) -> np.ndarray:
  179. """
  180. Draws text in a box on an image with fine control over size and orientation.
  181. Args:
  182. img_size (tuple): The size of the output image (width, height).
  183. box (np.ndarray): A 4x2 numpy array defining the corners of the box in (x, y) order.
  184. txt (str): The text to draw inside the box.
  185. font_path (str): The path to the font file to use for drawing the text.
  186. Returns:
  187. np.ndarray: An image with the text drawn in the specified box.
  188. """
  189. box_height = int(
  190. math.sqrt((box[0][0] - box[3][0]) ** 2 + (box[0][1] - box[3][1]) ** 2)
  191. )
  192. box_width = int(
  193. math.sqrt((box[0][0] - box[1][0]) ** 2 + (box[0][1] - box[1][1]) ** 2)
  194. )
  195. if box_height > 2 * box_width and box_height > 30:
  196. img_text = Image.new("RGB", (box_width, box_height), (255, 255, 255))
  197. draw_text = ImageDraw.Draw(img_text)
  198. if txt:
  199. font = create_font_vertical(txt, (box_width, box_height), font_path)
  200. draw_vertical_text(
  201. draw_text, (0, 0), txt, font, fill=(0, 0, 0), line_spacing=2
  202. )
  203. else:
  204. img_text = Image.new("RGB", (box_width, box_height), (255, 255, 255))
  205. draw_text = ImageDraw.Draw(img_text)
  206. if txt:
  207. font = create_font(txt, (box_width, box_height), font_path)
  208. draw_text.text([0, 0], txt, fill=(0, 0, 0), font=font)
  209. pts1 = np.float32(
  210. [[0, 0], [box_width, 0], [box_width, box_height], [0, box_height]]
  211. )
  212. pts2 = np.array(box, dtype=np.float32)
  213. M = cv2.getPerspectiveTransform(pts1, pts2)
  214. img_text = np.array(img_text, dtype=np.uint8)
  215. img_right_text = cv2.warpPerspective(
  216. img_text,
  217. M,
  218. img_size,
  219. flags=cv2.INTER_NEAREST,
  220. borderMode=cv2.BORDER_CONSTANT,
  221. borderValue=(255, 255, 255),
  222. )
  223. return img_right_text
  224. @function_requires_deps("opencv-contrib-python")
  225. def draw_vertical_text(draw, position, text, font, fill=(0, 0, 0), line_spacing=2):
  226. x, y = position
  227. for char in text:
  228. draw.text((x, y), char, font=font, fill=fill)
  229. bbox = font.getbbox(char)
  230. char_height = bbox[3] - bbox[1]
  231. y += char_height + line_spacing