changeset 33:6d432a5010a2

Modified font generator script : module creation. Not fully compliant with testmod.py though (transformation != generation)
author Guillaume Sicard <guitch21@gmail.com>
date Mon, 01 Feb 2010 22:55:19 -0500
parents 4d4248f7e2fb
children e61a46996db6
files transformations/ttf2jpg.py
diffstat 1 files changed, 92 insertions(+), 61 deletions(-) [+]
line wrap: on
line diff
--- a/transformations/ttf2jpg.py	Mon Feb 01 19:08:32 2010 -0500
+++ b/transformations/ttf2jpg.py	Mon Feb 01 22:55:19 2010 -0500
@@ -1,78 +1,109 @@
-#!/usr/bin/python
-# -*- coding: iso-8859-1 -*-
-# ttf2jpg.py converts font files to jpg images
-# download fonts from http://www.dafont.com
+#!/usr/bin/python                                                                                 
+# -*- coding: iso-8859-1 -*-                                                                      
 
-##################
-# import libraries
-##################
+'''
+    Implementation of font image generator
+    download fonts from http://www.dafont.com for exemple
+
+    Author: Guillaume Sicard
+'''
 
 import sys, os, fnmatch
-import Image
-import ImageFont, ImageDraw
-
-###########
-# variables
-###########
-# don't forget the "/" at the end of directories
+import Image, ImageFont, ImageDraw, numpy
 
-font_dir = "/usr/share/fonts/truetype/ttf-liberation/"
-image_dir = "./images/"
-pattern = "*.ttf"
+class ttf2jpg():
+    def __init__(self, font_file = ''):
+        self.w = 32
+        self.h = 32
+        self.font_dir = '/usr/share/fonts/truetype/ttf-liberation/'
+        self.font_file = font_file
+        self.image_dir = './images/'
+        self.pattern = '*.ttf'
 
-###########
-# functions
-###########
+    # get font name
+    def get_settings_names(self):
+        return [self.font_file]
 
-# save a picture of "text" with font "font_file"
-def write_image(text, font_file):
-#	print "Writing \"" + text + "\" with " + font_file + "..."
-	sys.stdout.write(".")
-	sys.stdout.flush()
+    # save an image
+    def save_image(self,array, filename = ''):
+        image = (array * 255.0).astype('int')
+        image = Image.fromarray(image).convert('L')
+        if (filename != ''):
+            image.save(filename)
+        else:
+            image.show()
 
-	# create a 32x32 white picture, and a drawing space
-	image = Image.new("L", (32, 32), "White")
-	draw = ImageDraw.Draw(image)
+    # return a picture array of "text" with font "font_file"
+    def create_image(self, text):
+         # create a w x h black picture, and a drawing space
+        image = Image.new('L', (self.w, self.h), 'Black')
+        draw = ImageDraw.Draw(image)
 
-	# load the font with the right size
-	font = ImageFont.truetype(font_dir + font_file, 28)
-	w,h =  draw.textsize(text, font=font)
+        # load the font with the right size
+        font = ImageFont.truetype(self.font_file, 28)
+        d_w,d_h =  draw.textsize(text, font=font)
 
-	# write text and aligns it
-	draw.text(((32 - w) / 2, ((32 - h) / 2)), text, font=font)
+        # write text and aligns it
+        draw.text(((32 - d_w) / 2, ((32 - d_h) / 2)), text, font=font, fill='White')
+
+        image = numpy.asarray(image)
+        image = (image / 255.0).astype(numpy.float32)
+
+        return image
 
-	# show image, xv must be installed
-	#image.show()
-
-	# save the picture
-	image.save(image_dir + text + "-" + font_file + ".jpg")
+    # write all the letters and numbers into pictures
+    def process_font(self):
+        for i in range(0, 26):
+            image = self.create_image(chr(ord('a') + i))
+            self.save_image(image, self.image_dir + chr(ord('a') + i) + '-' + os.path.basename(self.font_file) + '.jpg')
+            sys.stdout.write('.')
+            sys.stdout.flush()
+        for i in range(0, 26):
+            image = self.create_image(chr(ord('A') + i))
+            self.save_image(image, self.image_dir + chr(ord('A') + i) + '-' + os.path.basename(self.font_file) + '.jpg')
+            sys.stdout.write('.')
+            sys.stdout.flush()
+        for i in range(0, 10):
+            image = self.create_image(chr(ord('0') + i))
+            self.save_image(image, self.image_dir + chr(ord('0') + i) + '-' + os.path.basename(self.font_file) + '.jpg')
+            sys.stdout.write('.')
+            sys.stdout.flush()
+        return (26 + 26 + 10)
 
-# write all the letters and numbers into pictures
-def process_font(font_file):
-	for i in range(0, 26):
-		write_image(chr(ord('a') + i), font_file)
-	for i in range(0, 26):
-		write_image(chr(ord('A') + i), font_file)
-	for i in range(0, 10):
-		write_image(chr(ord('0') + i), font_file)
+    # generate the character from the font_file and returns a numpy array
+    def generate_image(self, character, font_file = ''):
+        if (font_file != ''):
+            self.font_file = font_file
+
+        return self.create_image(character)
 
-######
-# main
-######
+    # test method, create character images for all fonts in "font_dir"
+    def test(self):
+        import time
 
-# look for ttf files
-files = os.listdir(font_dir)
-font_files = fnmatch.filter(files, pattern)
+        # look for ttf files
+        files = os.listdir(self.font_dir)
+        font_files = fnmatch.filter(files, self.pattern)
+
+        # create "image_dir" if it doesn't exist
+        if not os.path.isdir(self.image_dir):
+            os.mkdir(self.image_dir)
+
+        sys.stdout.write( str(len(font_files)) + ' fonts found, generating jpg images in folder ' + self.image_dir )
+        sys.stdout.flush()
 
-# create "image_dir" if it doesn't exist
-if not os.path.isdir(image_dir):
-	os.mkdir(image_dir)
+        # main loop
+        t =  time.time()
+        n = 0
 
-sys.stdout.write( str(len(font_files)) + " fonts found, generating jpg images in folder " + image_dir )
-sys.stdout.flush()
+        for font_file in font_files:
+            self.font_file = self.font_dir + font_file
+            n += self.process_font()
+        t = time.time() - t
 
-# main loop
-for font_file in font_files:
-	process_font(font_file)
+        sys.stdout.write('\nall done!\n' + str(n) + ' images generated in ' + str(t) + 's (average : ' + str(1000 * t / n) + ' ms/im)\n')
 
-sys.stdout.write("\nall done!\n")
\ No newline at end of file
+if __name__ == '__main__':
+
+    myttf2jpg = ttf2jpg()
+    myttf2jpg.test()