Rendering a unicode/ascii character to a numpy array

ODL has text_phantom which does exactly this with some bells and whistles.

To give you a simplified implementation, you can use the PIL library. Specifically you need to decide on the image size and font size, then it is rather straightforward.

from PIL import Image, ImageDraw, ImageFont
import numpy as np

def text_phantom(text, size):
    # Availability is platform dependent
    font = 'arial'
    
    # Create font
    pil_font = ImageFont.truetype(font + ".ttf", size=size // len(text),
                                  encoding="unic")
    text_width, text_height = pil_font.getsize(text)

    # create a blank canvas with extra space between lines
    canvas = Image.new('RGB', [size, size], (255, 255, 255))

    # draw the text onto the canvas
    draw = ImageDraw.Draw(canvas)
    offset = ((size - text_width) // 2,
              (size - text_height) // 2)
    white = "#000000"
    draw.text(offset, text, font=pil_font, fill=white)

    # Convert the canvas into an array with values in [0, 1]
    return (255 - np.asarray(canvas)) / 255.0

This gives, for example:

import matplotlib.pyplot as plt
plt.imshow(text_phantom('A', 100))
plt.imshow(text_phantom('Longer text', 100))

enter image description here enter image description here