diff transformations/add_background_image.py @ 32:4d4248f7e2fb

Modified background adding class for compliance with testmod.py
author Guillaume Sicard <guitch21@gmail.com>
date Mon, 01 Feb 2010 19:08:32 -0500
parents 64dac4aabc04
children ab70fbca513c
line wrap: on
line diff
--- a/transformations/add_background_image.py	Mon Feb 01 14:18:47 2010 -0500
+++ b/transformations/add_background_image.py	Mon Feb 01 19:08:32 2010 -0500
@@ -1,80 +1,102 @@
 #!/usr/bin/python                                                                                 
 # -*- coding: iso-8859-1 -*-                                                                      
-# usage : add_background_image.py "image_name"
-# Chooses a random image in "image_dir" and set a random crop of it as a background to the character image "image_name" given as argument                                                   
 
-##################
-# import libraries
-##################
+'''
+    Implementation of random background adding to a specific image
+
+    Author: Guillaume Sicard
+'''
 
 import sys, os, random, fnmatch
-import Image           
-
-###########
-# variables
-###########
-# don't forget the "/" at the end of directories
+import Image, numpy           
 
-if len(sys.argv) < 2:
-	print "No argument, exiting"
-	sys.exit()
+class AddBackground():
+    def __init__(self, threshold = 128):
+        self.h = 32
+        self.w = 32
+        self.threshold = threshold;
+        self.bg_image_dir = './images/'
+        self.pattern = '*.jpg'
 
-char_image = sys.argv[1]
-image_dir = "./images/"
-pattern = "*.jpg"
-invert = False
-threshold = 100;
+    # get threshold value
+    def get_settings_names(self):
+        return [str(self.threshold)]
+
+    # no need, except for testmod.py
+    def regenerate_parameters(self, complexity):
+        value = random.gauss(0, 0.5*complexity)
+        return [value]
 
-###########
-# functions
-###########
+    # load an image
+    def load_image(self,filename):
+        image = Image.open(filename).convert('L')
+        image = numpy.asarray(image)
+        image = (image / 255.0).astype(numpy.float32)
+        return image
 
-# make a random 32x32 crop of image "image" and returns the new image_dir
-def rand_crop(image):
-	w, h = image.size
-	x, y = random.randint(1,w - 32), random.randint(1,h - 32)
+    # save an image
+    def save_image(self,array, filename):
+        image = (array * 255.0).astype('int')
+        image = Image.fromarray(image)
+        if (filename != ''):
+            image.save(filename)
+        else:
+            image.show()
 
-	return image.crop((x, y, x + 32, y + 32))
-
-# select a random image from "image_dir" and crops it
-def rand_image():
-	files = os.listdir(image_dir)
-	image_files = fnmatch.filter(files, pattern)
-	i = random.randint(0, len(image_files) - 1)
+    # make a random 32x32 crop of an image
+    def rand_crop(self,image):
+        i_w, i_h = image.shape
+        x, y = random.randint(0, i_w - self.w), random.randint(0, i_h - self.h)
+        return image[x:x + self.w, y:y + self.h]
 
-	image = Image.open(image_dir + image_files[i]).convert("L")
+    # select a random background image from "bg_image_dir" and crops it
+    def rand_bg_image(self):
+        files = os.listdir(self.bg_image_dir)
+        image_files = fnmatch.filter(files, self.pattern)
+        i = random.randint(0, len(image_files) - 1)
 
-	return rand_crop(image)
-
+        image = self.load_image(self.bg_image_dir + image_files[i])
+        self.bg_image = self.rand_crop(image)
 
-# set "bg_image" as background to "image", based on a pixels threshold
-def set_bg(image, bg_image, threshold):
-	pix = image.load()
-	bg_pix = bg_image.load()
+    # set "bg_image" as background to "image", based on a pixels threshold
+    def set_bg(self,image):
+        b = (image < self.threshold / 255.0).astype(numpy.float32)
+        return b * self.bg_image + ( 1 - b) * image
 
-	for x in range(1, 32):
-		for y in range(1, 32):
-			if pix[x, y] > threshold:
-				pix[x, y] = bg_pix[x, y]
-			elif invert:
-				pix[x, y] = 255 - pix[x, y]
+    # transform an image file and return an array
+    def transform_image_from_file(self, filename):
+        self.rand_bg_image()
+        image = self.load_image(filename)
+        image = self.set_bg(image)
+        return image
 
-	return image
+    # standard array to array transform
+    def transform_image(self, image):
+        self.rand_bg_image()
+        image = self.set_bg(image)
+        return image
 
-######
-# main
-######
+    # test method
+    def test(self,filename):
+        import time
 
-sys.stdout.write("Applying background to " + char_image + " with threshold " + str(threshold) + "... ")
-sys.stdout.flush()
+        sys.stdout.write('Starting addBackground test : loading image')
+        sys.stdout.flush()
+
+        image = self.load_image(filename)
 
-image = Image.open(char_image).convert("L")
-
-bg_image = rand_image()
+        t = 0
+        n = 500
+        for i in range(n):
+            t0 =  time.time()
+            image2 = self.transform_image(image)
+            t = ( i * t + (time.time() - t0) ) / (i + 1)
+            sys.stdout.write('.')
+            sys.stdout.flush()
+            
+        print "Done!\nAverage time : " + str(1000 * t) + " ms"
 
-image = set_bg(image, bg_image, threshold)
+if __name__ == '__main__':
 
-image.save(char_image + "-bg.jpg")
-#image.show()
-
-sys.stdout.write(" Done.\n")
+    myAddBackground = AddBackground()
+    myAddBackground.test('./images/0-LiberationSans-Italic.ttf.jpg')