PIL ImageDraw text() 中的 Latex 数学文本

Nag*_*S N 5 python latex python-imaging-library mathjax

我正在尝试注释我用 python 创建的一些图形。因此,我生成一个包含指定文本的图像(使用 PIL ImageDraw)并将其与图像连接起来。现在,我想在文本中包含数学符号。创建文本图像时有没有办法在乳胶数学中写入文本?这个答案建议使用 unicode 文本来解决问题,但我更喜欢直接用乳胶编写文本。

微量元素:

from PIL import ImageFont, Image, ImageDraw
from matplotlib import pyplot


def get_annotation(image_shape: tuple, title: str, font_size: int = 50):
    frame_height, frame_width = image_shape[:2]
    times_font = ImageFont.truetype('times-new-roman.ttf', font_size)
    text_image = Image.new('RGB', (frame_width, frame_height), (255, 255, 255))
    drawer = ImageDraw.Draw(text_image)
    w, h = drawer.textsize(title, font=times_font)
    drawer.text(((frame_width - w) / 2, (frame_height - h) / 2), text=title, fill=(0, 0, 0), font=times_font,
                align='center')
    annotation = numpy.array(text_image)
    return annotation

if __name__ == '__main__':
    anno = get_annotation((100, 300), 'frame $f_n$')
    pyplot.imshow(anno)
    pyplot.show()
Run Code Online (Sandbox Code Playgroud)

我尝试传递frame $f_n$title参数,但美元打印在文本图像中。

PS:times-new-roman.ttf可以在这里获取

Nag*_*S N 0

我在这里找到了 sympy 的替代方案

import sympy

sympy.preview(r'frame $f_n$', dvioptions=["-T", "tight", "-z", "0", "--truecolor", "-D 600"], viewer='file', filename='test.png', euler=False)
Run Code Online (Sandbox Code Playgroud)