result.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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 typing import Dict
  15. import math
  16. import random
  17. from pathlib import Path
  18. import copy
  19. import numpy as np
  20. import cv2
  21. import PIL
  22. from PIL import Image, ImageDraw, ImageFont
  23. from ....utils.fonts import PINGFANG_FONT_FILE_PATH, create_font
  24. from ...common.result import BaseCVResult
  25. class DocPreprocessorResult(BaseCVResult):
  26. """doc preprocessor result"""
  27. def _to_img(self) -> Dict[str, Image.Image]:
  28. """
  29. Generate an image combining the original, rotated, and unwarping images.
  30. Returns:
  31. Dict[Image.Image]: A new image combining the original, rotated, and unwarping images
  32. """
  33. image = self["input_image"][:, :, ::-1]
  34. rot_img = self["rot_img"][:, :, ::-1]
  35. angle = self["angle"]
  36. output_img = self["output_img"][:, :, ::-1]
  37. use_doc_orientation_classify = self["model_settings"][
  38. "use_doc_orientation_classify"
  39. ]
  40. use_doc_unwarping = self["model_settings"]["use_doc_unwarping"]
  41. h1, w1 = image.shape[0:2]
  42. h2, w2 = rot_img.shape[0:2]
  43. h3, w3 = output_img.shape[0:2]
  44. h = max(max(h1, h2), h3)
  45. img_show = Image.new("RGB", (w1 + w2 + w3, h + 25), (255, 255, 255))
  46. img_show.paste(Image.fromarray(image), (0, 0, w1, h1))
  47. img_show.paste(Image.fromarray(rot_img), (w1, 0, w1 + w2, h2))
  48. img_show.paste(Image.fromarray(output_img), (w1 + w2, 0, w1 + w2 + w3, h3))
  49. draw_text = ImageDraw.Draw(img_show)
  50. txt_list = ["Original Image", "Rotated Image", "Unwarping Image"]
  51. txt_list[1] = f"Rotated Image ({use_doc_orientation_classify}, {angle})"
  52. txt_list[2] = f"Unwarping Image ({use_doc_unwarping})"
  53. region_w_list = [w1, w2, w3]
  54. beg_w_list = [0, w1, w1 + w2]
  55. for tno in range(len(txt_list)):
  56. txt = txt_list[tno]
  57. font = create_font(txt, (region_w_list[tno], 20), PINGFANG_FONT_FILE_PATH)
  58. draw_text.text(
  59. [10 + beg_w_list[tno], h + 2], txt, fill=(0, 0, 0), font=font
  60. )
  61. imgs = {"preprocessed_img": img_show}
  62. return imgs