result.py 11 KB

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