I'm trying to annotate a few figures I created in python. So, I'm generating an image containing the specified text (using PIL ImageDraw) and concatenating it with the image. Now, I want to include a math notation into the text. Is there a way to write text in latex math when creating the image of text? This answer suggests a work-around by using unicode text, but I would prefer writing the text in latex directly.
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()
I tried passing frame $f_n$
to title
parameter, but dollars got printed in the text image.
PS: times-new-roman.ttf can be obtained here
I found an alternative with sympy here
import sympy
sympy.preview(r'frame $f_n$', dvioptions=["-T", "tight", "-z", "0", "--truecolor", "-D 600"], viewer='file', filename='test.png', euler=False)