1 #!/usr/bin/env python 2 3 from random import random, randrange 4 from os.path import splitext 5 import EXIF 6 import PIL.Image 7 import itertools 8 import math 9 import sys 10 11 corners = [ 12 (0, 0, 0), (255, 0, 0), (0, 255, 0), (255, 255, 0), 13 (0, 0, 255), (255, 0, 255), (0, 255, 255), (255, 255, 255) 14 ] 15 16 def distance(rgb1, rgb2): 17 r1, g1, b1 = rgb1 18 r2, g2, b2 = rgb2 19 return math.sqrt(pow(r1 - r2, 2) + pow(g1 - g2, 2) + pow(b1 - b2, 2)) 20 21 def nearest(rgb, values): 22 l = [(distance(rgb, value), value) for value in values] 23 l.sort() 24 return l[0][1] 25 26 def restore(srgb): 27 return tuple(map(lambda x: int(x * 255.0), srgb)) 28 29 def scale(rgb): 30 return tuple(map(lambda x: x / 255.0, rgb)) 31 32 def square(srgb): 33 return tuple(map(lambda x: pow(x, 2), srgb)) 34 35 def invert(srgb): 36 return tuple(map(lambda x: 1.0 - x, srgb)) 37 38 def combination(rgb): 39 rgb = square(scale(rgb)) 40 rgbi = invert(rgb) 41 pairs = zip(rgbi, rgb) 42 d = [] 43 for corner in corners: 44 rs, gs, bs = scale(corner) 45 d.append((pairs[0][int(rs)] * pairs[1][int(gs)] * pairs[2][int(bs)], corner)) 46 return balance(d) 47 48 def complements(rgb): 49 r, g, b = rgb 50 return rgb, restore(invert(scale(rgb))) 51 52 def balance(d): 53 d = dict([(value, f) for f, value in d]) 54 for primary, secondary in map(complements, [(255, 0, 0), (0, 255, 0), (0, 0, 255)]): 55 common = min(d[primary], d[secondary]) 56 d[primary] -= common 57 d[secondary] -= common 58 d[(0, 0, 0)] += common 59 d[(255, 255, 255)] += common 60 return [(f, value) for value, f in d.items()] 61 62 def combine(d): 63 out = [0, 0, 0] 64 for v, rgb in d: 65 out[0] += v * rgb[0] 66 out[1] += v * rgb[1] 67 out[2] += v * rgb[2] 68 return out 69 70 def pattern(rgb): 71 l = combination(rgb) 72 l.sort(reverse=True) 73 return l 74 75 def get_value(rgb): 76 choose = random() 77 threshold = 0 78 for f, c in pattern(rgb): 79 threshold += f 80 if choose < threshold: 81 return c 82 return c 83 84 def sign(x): 85 return x >= 0 and 1 or -1 86 87 def saturate_rgb(rgb, exp): 88 return tuple([saturate_value(x, exp) for x in rgb]) 89 90 def saturate_value(x, exp): 91 return int(127.5 + sign(x - 127.5) * 127.5 * pow(abs(x - 127.5) / 127.5, exp)) 92 93 def replace(value, values): 94 if value not in values: 95 for i, v in list(enumerate(values))[::-1]: 96 if v != value: 97 values[i] = value 98 return 99 100 def test(): 101 size = 512 102 for r in (0, 63, 127, 191, 255): 103 im = PIL.Image.new("RGB", (size, size)) 104 for g in range(0, size): 105 for b in range(0, size): 106 value = get_value((r, (g * 256) / size, (b * 256 / size))) 107 im.putpixel((g, b), value) 108 im.save("rgb%d.png" % r) 109 110 def test_flat(rgb): 111 size = 64 112 im = PIL.Image.new("RGB", (size, size)) 113 for y in range(0, size): 114 for x in range(0, size): 115 im.putpixel((x, y), get_value(rgb)) 116 im.save("rgb%02d%02d%02d.png" % rgb) 117 118 def rotate_and_scale(im, width, height, rotate): 119 if rotate or x and x["Image Orientation"].values == [6L]: 120 im = im.rotate(270) 121 122 w, h = im.size 123 if w > h: 124 height = (width * h) / w 125 else: 126 width = (height * w) / h 127 128 return im.resize((width, height)) 129 130 if __name__ == "__main__": 131 if "--test" in sys.argv: 132 test() 133 sys.exit(0) 134 elif "--test-flat" in sys.argv: 135 test_flat((120, 40, 60)) 136 sys.exit(0) 137 138 width = 320 139 height = 256 140 141 input_filename, output_filename = sys.argv[1:3] 142 basename, ext = splitext(output_filename) 143 preview_filename = "".join([basename + "_preview", ext]) 144 145 rotate = "-r" in sys.argv[3:] 146 saturate = sys.argv[3:].count("-s") 147 desaturate = sys.argv[3:].count("-d") 148 preview = "-p" in sys.argv[3:] 149 150 x = EXIF.process_file(open(input_filename)) 151 im = PIL.Image.open(input_filename).convert("RGB") 152 im = rotate_and_scale(im, width, height, rotate) 153 154 width, height = im.size 155 156 colours = [] 157 158 for y in range(0, height): 159 c = {} 160 for x in range(0, width): 161 rgb = im.getpixel((x, y)) 162 163 # Saturate if requested. 164 165 if saturate or desaturate: 166 rgb = saturate_rgb(rgb, saturate and math.pow(0.5, saturate) or math.pow(2, desaturate)) 167 im.putpixel((x, y), rgb) 168 169 # Sum the colour probabilities. 170 171 for f, value in combination(rgb): 172 if not c.has_key(value): 173 c[value] = f 174 else: 175 c[value] += f 176 177 c = [(n/width, value) for value, n in c.items()] 178 c.sort(reverse=True) 179 colours.append(c) 180 181 if preview: 182 imp = im.copy() 183 for y in range(0, height): 184 for x in range(0, width): 185 rgb = imp.getpixel((x, y)) 186 value = get_value(rgb) 187 imp.putpixel((x, y), value) 188 imp.save(preview_filename) 189 190 for y, c in enumerate(colours): 191 most = [value for n, value in c[:4]] 192 least = [value for n, value in c[4:]] 193 194 if least: 195 switched = [] 196 for j in 1, 2: 197 i = randrange(0, 4) 198 n, value = c[i] 199 if n < 0.1: 200 switched.append(c[i]) 201 del c[i] 202 c += switched 203 most = [value for n, value in c[:4]] 204 least = [value for n, value in c[4:]] 205 206 for x in range(0, width): 207 rgb = im.getpixel((x, y)) 208 209 # Get the requested colours and choose the closest alternative for 210 # less common colours. 211 212 value = get_value(rgb) 213 if value in least: 214 value = nearest(value, most) 215 216 im.putpixel((x, y), value) 217 218 im.save(output_filename) 219 220 # vim: tabstop=4 expandtab shiftwidth=4