ocr.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  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 json
  16. import math
  17. import random
  18. import numpy as np
  19. import cv2
  20. import PIL
  21. from PIL import Image, ImageDraw, ImageFont
  22. from ...utils import logging
  23. from ...utils.fonts import PINGFANG_FONT_FILE_PATH
  24. from ..utils.io import JsonWriter, ImageWriter, ImageReader
  25. class OCRResult(dict):
  26. def __init__(self, data):
  27. super().__init__(data)
  28. self._json_writer = JsonWriter()
  29. self._img_reader = ImageReader(backend="opencv")
  30. self._img_writer = ImageWriter(backend="opencv")
  31. def save_json(self, save_path, indent=4, ensure_ascii=False):
  32. if not save_path.endswith(".json"):
  33. save_path = Path(save_path) / f"{Path(self['img_path']).stem}.json"
  34. self._json_writer.write(save_path, self, indent=4, ensure_ascii=False)
  35. def save_img(self, save_path):
  36. if not save_path.lower().endswith((".jpg", ".png")):
  37. save_path = Path(save_path) / f"{Path(self['img_path']).stem}.jpg"
  38. res_img = self._draw_ocr_box_txt(
  39. self["img_path"], self["dt_polys"], self["rec_text"], self["rec_score"]
  40. )
  41. self._img_writer.write(save_path.as_posix(), res_img)
  42. logging.info(f"The result has been saved in {save_path}.")
  43. def print(self, json_format=True, indent=4, ensure_ascii=False):
  44. str_ = self
  45. if json_format:
  46. str_ = json.dumps(str_, indent=indent, ensure_ascii=ensure_ascii)
  47. logging.info(str_)
  48. def _draw_ocr_box_txt(
  49. self,
  50. img_path,
  51. boxes,
  52. txts=None,
  53. scores=None,
  54. drop_score=0.5,
  55. font_path=PINGFANG_FONT_FILE_PATH,
  56. ):
  57. """draw ocr result"""
  58. img = self._img_reader.read(img_path)
  59. image = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
  60. h, w = image.height, image.width
  61. img_left = image.copy()
  62. img_right = np.ones((h, w, 3), dtype=np.uint8) * 255
  63. random.seed(0)
  64. draw_left = ImageDraw.Draw(img_left)
  65. if txts is None or len(txts) != len(boxes):
  66. txts = [None] * len(boxes)
  67. for idx, (box, txt) in enumerate(zip(boxes, txts)):
  68. if scores is not None and scores[idx] < drop_score:
  69. continue
  70. color = (
  71. random.randint(0, 255),
  72. random.randint(0, 255),
  73. random.randint(0, 255),
  74. )
  75. draw_left.polygon(box, fill=color)
  76. img_right_text = draw_box_txt_fine((w, h), box, txt, font_path)
  77. pts = np.array(box, np.int32).reshape((-1, 1, 2))
  78. cv2.polylines(img_right_text, [pts], True, color, 1)
  79. img_right = cv2.bitwise_and(img_right, img_right_text)
  80. img_left = Image.blend(image, img_left, 0.5)
  81. img_show = Image.new("RGB", (w * 2, h), (255, 255, 255))
  82. img_show.paste(img_left, (0, 0, w, h))
  83. img_show.paste(Image.fromarray(img_right), (w, 0, w * 2, h))
  84. return np.array(img_show)
  85. def draw_box_txt_fine(img_size, box, txt, font_path=PINGFANG_FONT_FILE_PATH):
  86. """draw box text"""
  87. box_height = int(
  88. math.sqrt((box[0][0] - box[3][0]) ** 2 + (box[0][1] - box[3][1]) ** 2)
  89. )
  90. box_width = int(
  91. math.sqrt((box[0][0] - box[1][0]) ** 2 + (box[0][1] - box[1][1]) ** 2)
  92. )
  93. if box_height > 2 * box_width and box_height > 30:
  94. img_text = Image.new("RGB", (box_height, box_width), (255, 255, 255))
  95. draw_text = ImageDraw.Draw(img_text)
  96. if txt:
  97. font = create_font(txt, (box_height, box_width), font_path)
  98. draw_text.text([0, 0], txt, fill=(0, 0, 0), font=font)
  99. img_text = img_text.transpose(Image.ROTATE_270)
  100. else:
  101. img_text = Image.new("RGB", (box_width, box_height), (255, 255, 255))
  102. draw_text = ImageDraw.Draw(img_text)
  103. if txt:
  104. font = create_font(txt, (box_width, box_height), font_path)
  105. draw_text.text([0, 0], txt, fill=(0, 0, 0), font=font)
  106. pts1 = np.float32(
  107. [[0, 0], [box_width, 0], [box_width, box_height], [0, box_height]]
  108. )
  109. pts2 = np.array(box, dtype=np.float32)
  110. M = cv2.getPerspectiveTransform(pts1, pts2)
  111. img_text = np.array(img_text, dtype=np.uint8)
  112. img_right_text = cv2.warpPerspective(
  113. img_text,
  114. M,
  115. img_size,
  116. flags=cv2.INTER_NEAREST,
  117. borderMode=cv2.BORDER_CONSTANT,
  118. borderValue=(255, 255, 255),
  119. )
  120. return img_right_text
  121. def create_font(txt, sz, font_path=PINGFANG_FONT_FILE_PATH):
  122. """create font"""
  123. font_size = int(sz[1] * 0.8)
  124. font = ImageFont.truetype(font_path, font_size, encoding="utf-8")
  125. if int(PIL.__version__.split(".")[0]) < 10:
  126. length = font.getsize(txt)[0]
  127. else:
  128. length = font.getlength(txt)
  129. if length > sz[0]:
  130. font_size = int(font_size * sz[0] / length)
  131. font = ImageFont.truetype(font_path, font_size, encoding="utf-8")
  132. return font