Using PIL, this might be a solution. One difficulty, however, is that
you do not get to directly control the width and height of the array. Instead
you control the font and fontsize. If your intended usage is for a particular
LED matrix, then this might be alright -- just find the right font and fontsize
for your LED matrix.
Below I've modified jsheperd's answer
so char_to_pixels
returns a binary NumPy array. The display
function converts the binary array to a character array just to make the result easier to see.
from __future__ import print_function
import string
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
import numpy as np
def char_to_pixels(text, path='arialbd.ttf', fontsize=14):
"""
Based on https://stackoverflow.com/a/27753869/190597 (jsheperd)
"""
font = ImageFont.truetype(path, fontsize)
w, h = font.getsize(text)
h *= 2
image = Image.new('L', (w, h), 1)
draw = ImageDraw.Draw(image)
draw.text((0, 0), text, font=font)
arr = np.asarray(image)
arr = np.where(arr, 0, 1)
arr = arr[(arr != 0).any(axis=1)]
return arr
def display(arr):
result = np.where(arr, '#', ' ')
print('\n'.join([''.join(row) for row in result]))
for c in string.uppercase:
arr = char_to_pixels(
c,
path='/usr/share/fonts/truetype/liberation/LiberationSerif-Bold.ttf',
fontsize=9)
print(arr.shape)
display(arr)
print()
yields
(7, 7)
##
##
# ##
# ##
####
# ##
## ####
(7, 7)
#####
## ##
## ##
####
## ##
## ##
#####
(7, 7)
####
## #
##
##
##
## #
####
(7, 7)
#####
## ##
## ##
## ##
## ##
## ##
#####
(7, 6)
#####
## #
##
###
##
## #
#####
(7, 5)
#####
## #
##
###
##
##
####
(7, 8)
####
## #
##
##
## ####
# ##
####
(7, 7)
### ###
## ##
## ##
#####
## ##
## ##
### ###
(7, 4)
####
##
##
##
##
##
####
(7, 5)
####
##
##
##
##
# ##
###
(7, 7)
#### ##
##
## #
####
## ##
## ##
#### ##
(7, 6)
####
##
##
##
##
## #
#####
(7, 8)
## ####
## ###
### ##
# ## ##
# ## ##
# ## ##
# # ####
(7, 7)
### ###
### #
### #
# ###
# ###
# ##
### #
(7, 7)
###
## ##
## ##
## ##
## ##
## ##
###
(7, 5)
####
## #
## #
###
##
##
####
(9, 8)
####
## ##
## ##
## ##
## ##
## ##
####
##
##
(7, 7)
#####
## ##
## ##
####
## #
## ##
#### ##
(7, 5)
###
## #
###
##
##
# ##
###
(7, 6)
######
# ## #
##
##
##
##
####
(7, 7)
#######
## #
## #
## #
## #
## #
###
(7, 6)
### ##
## #
## #
##
###
##
##
(7, 9)
### ##
## ## #
## ## #
## ##
## ##
## ##
## ##
(7, 6)
######
## #
###
##
###
# ##
######
(7, 6)
######
## #
####
##
##
##
####
(7, 5)
#####
# ###
##
##
##
## #
#####
I've included the shape of the arrays above the characters so you can see if
they would fit on the LED matrix.