I would like to ask if there an easy an efficient way to render a given character to a numpy array. What I would like is a function that accepts a character as input, and returns a numpy array which then I can use as an argument of plt.imshow()
function. Cant really find that on the internet, apart from a couple of solutions that require a lot of dependancies, when it seems like an easy task.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With