result.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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 copy
  15. import PIL
  16. from PIL import Image, ImageDraw, ImageFont
  17. from ....utils.fonts import PINGFANG_FONT_FILE_PATH
  18. from ...common.result import BaseCVResult, JsonMixin
  19. class TextRecResult(BaseCVResult):
  20. def _to_str(self, *args, **kwargs):
  21. data = copy.deepcopy(self)
  22. data.pop("input_img")
  23. return JsonMixin._to_str(data, *args, **kwargs)
  24. def _to_json(self, *args, **kwargs):
  25. data = copy.deepcopy(self)
  26. data.pop("input_img")
  27. return JsonMixin._to_json(data, *args, **kwargs)
  28. def _to_img(self):
  29. """Draw label on image"""
  30. image = Image.fromarray(self["input_img"])
  31. rec_text = self["rec_text"]
  32. rec_score = self["rec_score"]
  33. image = image.convert("RGB")
  34. image_width, image_height = image.size
  35. text = f"{rec_text} ({rec_score})"
  36. font = self.adjust_font_size(image_width, text, PINGFANG_FONT_FILE_PATH)
  37. row_height = font.getbbox(text)[3]
  38. new_image_height = image_height + int(row_height * 1.2)
  39. new_image = Image.new("RGB", (image_width, new_image_height), (255, 255, 255))
  40. new_image.paste(image, (0, 0))
  41. draw = ImageDraw.Draw(new_image)
  42. draw.text(
  43. (0, image_height),
  44. text,
  45. fill=(0, 0, 0),
  46. font=font,
  47. )
  48. return {"res": new_image}
  49. def adjust_font_size(self, image_width, text, font_path):
  50. font_size = int(image_width * 0.06)
  51. font = ImageFont.truetype(font_path, font_size)
  52. if int(PIL.__version__.split(".")[0]) < 10:
  53. text_width, _ = font.getsize(text)
  54. else:
  55. text_width, _ = font.getbbox(text)[2:]
  56. while text_width > image_width:
  57. font_size -= 1
  58. font = ImageFont.truetype(font_path, font_size)
  59. if int(PIL.__version__.split(".")[0]) < 10:
  60. text_width, _ = font.getsize(text)
  61. else:
  62. text_width, _ = font.getbbox(text)[2:]
  63. return font