__init__.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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 PIL
  16. from PIL import ImageFont
  17. from .. import logging
  18. from ..download import download
  19. def get_font_file_path(file_name: str) -> str:
  20. """
  21. Get the path of the font file.
  22. Returns:
  23. str: The path to the font file.
  24. """
  25. font_path = (Path(__file__).parent / file_name).resolve().as_posix()
  26. if not Path(font_path).exists():
  27. download(
  28. url=f"https://paddle-model-ecology.bj.bcebos.com/paddlex/PaddleX3.0/fonts/{file_name}",
  29. save_path=font_path,
  30. )
  31. return font_path
  32. def create_font(txt: str, sz: tuple, font_path: str) -> ImageFont:
  33. """
  34. Create a font object with specified size and path, adjusted to fit within the given image region.
  35. Parameters:
  36. txt (str): The text to be rendered with the font.
  37. sz (tuple): A tuple containing the height and width of an image region, used for font size.
  38. font_path (str): The path to the font file.
  39. Returns:
  40. ImageFont: An ImageFont object adjusted to fit within the given image region.
  41. """
  42. font_size = int(sz[1] * 0.8)
  43. font = ImageFont.truetype(font_path, font_size, encoding="utf-8")
  44. if int(PIL.__version__.split(".")[0]) < 10:
  45. length = font.getsize(txt)[0]
  46. else:
  47. length = font.getlength(txt)
  48. if length > sz[0]:
  49. font_size = int(font_size * sz[0] / length)
  50. font = ImageFont.truetype(font_path, font_size, encoding="utf-8")
  51. return font
  52. PINGFANG_FONT_FILE_PATH = get_font_file_path("PingFang-SC-Regular.ttf")
  53. SIMFANG_FONT_FILE_PATH = get_font_file_path("simfang.ttf")