view transformations/add_background_image.py @ 31:7ef8aac2cdb5

comment change and useless import removed for contrast.py
author Xavier Glorot <glorotxa@iro.umontreal.ca>
date Mon, 01 Feb 2010 14:18:47 -0500
parents 64dac4aabc04
children 4d4248f7e2fb
line wrap: on
line source

#!/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"
invert = False
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]
			elif invert:
				pix[x, y] = 255 - 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")