comparison 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
comparison
equal deleted inserted replaced
7:f2d46bb3f2d5 8:bdaa5bd26dcf
1 #!/usr/bin/python
2 # -*- coding: iso-8859-1 -*-
3 # usage : add_background_image.py "image_name"
4 # 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
5
6 ##################
7 # import libraries
8 ##################
9
10 import sys, os, random, fnmatch
11 import Image
12
13 ###########
14 # variables
15 ###########
16 # don't forget the "/" at the end of directories
17
18 if len(sys.argv) < 2:
19 print "No argument, exiting"
20 sys.exit()
21
22 char_image = sys.argv[1]
23 image_dir = "./images/"
24 pattern = "*.jpg"
25 threshold = 100;
26
27 ###########
28 # functions
29 ###########
30
31 # make a random 32x32 crop of image "image" and returns the new image_dir
32 def rand_crop(image):
33 w, h = image.size
34 x, y = random.randint(1,w - 32), random.randint(1,h - 32)
35
36 return image.crop((x, y, x + 32, y + 32))
37
38 # select a random image from "image_dir" and crops it
39 def rand_image():
40 files = os.listdir(image_dir)
41 image_files = fnmatch.filter(files, pattern)
42 i = random.randint(0, len(image_files) - 1)
43
44 image = Image.open(image_dir + image_files[i]).convert("L")
45
46 return rand_crop(image)
47
48
49 # set "bg_image" as background to "image", based on a pixels threshold
50 def set_bg(image, bg_image, threshold):
51 pix = image.load()
52 bg_pix = bg_image.load()
53
54 for x in range(1, 32):
55 for y in range(1, 32):
56 if pix[x, y] > threshold:
57 pix[x, y] = bg_pix[x, y]
58
59 return image
60
61 ######
62 # main
63 ######
64
65 sys.stdout.write("Applying background to " + char_image + " with threshold " + str(threshold) + "... ")
66 sys.stdout.flush()
67
68 image = Image.open(char_image).convert("L")
69
70 bg_image = rand_image()
71
72 image = set_bg(image, bg_image, threshold)
73
74 image.save(char_image + "-bg.jpg")
75 #image.show()
76
77 sys.stdout.write(" Done.\n")
78
79