2024-01-12 12:39:30 +00:00
|
|
|
from PIL import Image, ImageDraw, ImageFont
|
|
|
|
import numpy as np
|
|
|
|
|
|
|
|
def text_to_matrix(text, size, font):
|
|
|
|
pil_font = ImageFont.truetype(font, size=size // len(text), encoding="unic")
|
2024-01-26 13:27:10 +00:00
|
|
|
canvas = Image.new('RGB', [size * 2, size * 2], (255, 255, 255))
|
2024-01-12 12:39:30 +00:00
|
|
|
draw = ImageDraw.Draw(canvas)
|
|
|
|
black = "#000000"
|
|
|
|
draw.text((10, 10), text, font=pil_font, fill=black)
|
|
|
|
m = (255 - np.asarray(canvas)) / 255.0
|
|
|
|
xs, ys, _ = np.where(m > 0.1) # Never trust float comparison
|
|
|
|
m_trim = m[min(xs):max(xs) + 1, min(ys): max(ys) + 1]
|
|
|
|
|
|
|
|
return m_trim
|
|
|
|
|