result.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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 math
  15. import random
  16. import numpy as np
  17. import cv2
  18. import PIL
  19. from PIL import Image, ImageDraw, ImageFont
  20. from ....utils.fonts import PINGFANG_FONT_FILE_PATH, create_font
  21. from ..components import CVResult
  22. class DocPreprocessorResult(CVResult):
  23. """doc preprocessor result"""
  24. def save_to_img(self, save_path: str, *args, **kwargs) -> None:
  25. """
  26. Save the image to the specified path.
  27. Args:
  28. save_path (str): The path to save the image.
  29. If the path does not end with '.jpg' or '.png', it appends '_res_doc_preprocess_<img_id>.jpg'
  30. to the path where <img_id> is retrieved from the object's 'img_id' attribute.
  31. *args: Variable length argument list.
  32. **kwargs: Arbitrary keyword arguments.
  33. Returns:
  34. None
  35. """
  36. if not str(save_path).lower().endswith((".jpg", ".png")):
  37. img_id = self["img_id"]
  38. save_path = save_path + "/res_doc_preprocess_%d.jpg" % img_id
  39. super().save_to_img(save_path, *args, **kwargs)
  40. def _to_img(self) -> PIL.Image:
  41. """
  42. Generate an image combining the original, rotated, and unwarping images.
  43. Returns:
  44. PIL.Image: A new image that displays the original, rotated, and unwarping images side by side.
  45. """
  46. image = self["input_image"][:, :, ::-1]
  47. angle = self["angle"]
  48. rot_img = self["rot_img"][:, :, ::-1]
  49. output_img = self["output_img"][:, :, ::-1]
  50. h, w = image.shape[0:2]
  51. img_show = Image.new("RGB", (w * 3, h + 25), (255, 255, 255))
  52. img_show.paste(Image.fromarray(image), (0, 0, w, h))
  53. img_show.paste(Image.fromarray(rot_img), (w, 0, w * 2, h))
  54. img_show.paste(Image.fromarray(output_img), (w * 2, 0, w * 3, h))
  55. draw_text = ImageDraw.Draw(img_show)
  56. txt_list = ["Original Image", "Rotated Image", "Unwarping Image"]
  57. for tno in range(len(txt_list)):
  58. txt = txt_list[tno]
  59. font = create_font(txt, (w, 20), PINGFANG_FONT_FILE_PATH)
  60. draw_text.text([10 + w * tno, h + 2], txt, fill=(0, 0, 0), font=font)
  61. return img_show