diff transformations/add_background_image.py @ 8:bdaa5bd26dcf

Added : script to merge a character image with a random background image
author guitch
date Tue, 26 Jan 2010 18:58:10 -0500
parents
children 64dac4aabc04
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/transformations/add_background_image.py	Tue Jan 26 18:58:10 2010 -0500
@@ -0,0 +1,79 @@
+#!/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
+##################
+
+import sys, os, random, fnmatch
+import Image           
+
+###########
+# variables
+###########
+# don't forget the "/" at the end of directories
+
+if len(sys.argv) < 2:
+	print "No argument, exiting"
+	sys.exit()
+
+char_image = sys.argv[1]
+image_dir = "./images/"                               
+pattern = "*.jpg"                                     
+threshold = 100;
+
+###########
+# functions
+###########
+
+# 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)
+
+	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)
+
+	image = Image.open(image_dir + image_files[i]).convert("L")
+
+	return 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()
+
+	for x in range(1, 32):
+		for y in range(1, 32):
+			if pix[x, y] > threshold:
+				pix[x, y] = bg_pix[x, y]
+
+	return image
+
+######
+# main
+######
+
+sys.stdout.write("Applying background to " + char_image + " with threshold " + str(threshold) + "... ")
+sys.stdout.flush()
+
+image = Image.open(char_image).convert("L")
+
+bg_image = rand_image()
+
+image = set_bg(image, bg_image, threshold)
+
+image.save(char_image + "-bg.jpg")
+#image.show()
+
+sys.stdout.write(" Done.\n")
+
+         
\ No newline at end of file