computer_vision_project/rasterizer.py

15 lines
561 B
Python

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")
canvas = Image.new('RGB', [size + 20, size + 20], (255, 255, 255))
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