python pil

Create Image files with Letters in them

I need some test data (as always), so I created a little function to help me generate some test data

from PIL import Image, ImageDraw, ImageFont

def char_img(filename,letter,font='/Users/tim/Dev/font2/Helvetica.ttf',fsize=24):
    # make a blank image for the text, initialized to transparent text color
    #White Background
    txt = Image.new('RGB',(28,28), (255,255,255))
    #TT Font
    fnt=ImageFont.truetype(font,fsize)
    # get a drawing context
    d = ImageDraw.Draw(txt)
    # draw text, full opacity
    d.text((5,5), letter, font=fnt, fill=(0,0,0))
    #Font fill color is black
    txt.save(filename)

char_img('a_1.bmp','a')
char_img('b_1.bmp','b')
char_img('a_2.bmp','a','/Users/tim/Dev/font2/HelveticaBoldOblique.ttf',24)
char_img('b_2.bmp','b','/Users/tim/Dev/font2/HelveticaBoldOblique.ttf',24)

Generate lots of letters

I need quite a number of items, but I need them tagged so I can feed them into a ML process.

from itertools import combinations


FontL=['/Users/tim/Dev/font2/Helvetica.ttf',
        '/Users/tim/Dev/font2/HelveticaBoldOblique.ttf',
        '/Users/tim/Dev/font2/HelveticaLight.ttf',
        '/Users/tim/Dev/font2/HelveticaLightOblique.ttf']

for f in range(len(FontL)):
    for ltr in combinations ([chr(a) for a in range(97,123)],1):
        for fs in range(20,25):
            filename='{}_{}_{}.bmp'.format(ltr[0],f,fs)
            print('{} {} {} {}'.format(filename,ltr[0],FontL[f],fs))
            char_img(filename,ltr[0],FontL[f],fs)

Note, I used combinations so if I can find a "joined-up" font ... I can test this in English before trying Arabic.