result.py 2.2 KB

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