在PIL ImageDraw的text()函数中如何使用Latex数学公式文本

5
我正在尝试为我在Python中创建的一些图像添加注释。因此,我使用PIL ImageDraw生成包含指定文本的图像,并将其与图像连接起来。现在,我希望在文本中包含数学符号。在创建文本图像时,是否有一种方法可以编写LaTeX数学公式文本?这个答案提供了一个通过使用Unicode文本的解决方法,但我更喜欢直接编写LaTeX文本。
MWE:
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()

我尝试将frame $f_n$ 传递到title参数,但是美元符号在文本图像中被打印出来了。

附注:可以在这里获取times-new-roman.ttf字体文件。


你能让你的代码可复现吗? - Sadra
1个回答

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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接