paul@0 | 1 | #!/usr/bin/env python |
paul@0 | 2 | |
paul@56 | 3 | """ |
paul@56 | 4 | Convert and optimise images for display in an Acorn Electron MODE 1 variant |
paul@56 | 5 | with four colours per line but eight colours available for selection for each |
paul@56 | 6 | line. |
paul@56 | 7 | |
paul@56 | 8 | Copyright (C) 2015 Paul Boddie <paul@boddie.org.uk> |
paul@56 | 9 | |
paul@56 | 10 | This program is free software; you can redistribute it and/or modify it under |
paul@56 | 11 | the terms of the GNU General Public License as published by the Free Software |
paul@56 | 12 | Foundation; either version 3 of the License, or (at your option) any later |
paul@56 | 13 | version. |
paul@56 | 14 | |
paul@56 | 15 | This program is distributed in the hope that it will be useful, but WITHOUT ANY |
paul@56 | 16 | WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A |
paul@56 | 17 | PARTICULAR PURPOSE. See the GNU General Public License for more details. |
paul@56 | 18 | |
paul@56 | 19 | You should have received a copy of the GNU General Public License along |
paul@56 | 20 | with this program. If not, see <http://www.gnu.org/licenses/>. |
paul@56 | 21 | """ |
paul@56 | 22 | |
paul@58 | 23 | from random import random, randrange |
paul@56 | 24 | from os.path import split, splitext |
paul@12 | 25 | import EXIF |
paul@0 | 26 | import PIL.Image |
paul@60 | 27 | import itertools |
paul@20 | 28 | import math |
paul@0 | 29 | import sys |
paul@0 | 30 | |
paul@20 | 31 | corners = [ |
paul@20 | 32 | (0, 0, 0), (255, 0, 0), (0, 255, 0), (255, 255, 0), |
paul@20 | 33 | (0, 0, 255), (255, 0, 255), (0, 255, 255), (255, 255, 255) |
paul@0 | 34 | ] |
paul@0 | 35 | |
paul@56 | 36 | # Basic colour operations. |
paul@56 | 37 | |
paul@61 | 38 | def extra(x): return x |
paul@61 | 39 | |
paul@49 | 40 | def within(v, lower, upper): |
paul@49 | 41 | return min(max(v, lower), upper) |
paul@49 | 42 | |
paul@49 | 43 | def clip(v): |
paul@49 | 44 | return within(v, 0, 255) |
paul@49 | 45 | |
paul@20 | 46 | def distance(rgb1, rgb2): |
paul@20 | 47 | r1, g1, b1 = rgb1 |
paul@20 | 48 | r2, g2, b2 = rgb2 |
paul@20 | 49 | return math.sqrt(pow(r1 - r2, 2) + pow(g1 - g2, 2) + pow(b1 - b2, 2)) |
paul@20 | 50 | |
paul@35 | 51 | def restore(srgb): |
paul@35 | 52 | return tuple(map(lambda x: int(x * 255.0), srgb)) |
paul@35 | 53 | |
paul@34 | 54 | def scale(rgb): |
paul@34 | 55 | return tuple(map(lambda x: x / 255.0, rgb)) |
paul@34 | 56 | |
paul@39 | 57 | def square(srgb): |
paul@39 | 58 | return tuple(map(lambda x: pow(x, 2), srgb)) |
paul@39 | 59 | |
paul@34 | 60 | def invert(srgb): |
paul@34 | 61 | return tuple(map(lambda x: 1.0 - x, srgb)) |
paul@34 | 62 | |
paul@56 | 63 | # Colour distribution functions. |
paul@56 | 64 | |
paul@51 | 65 | cache = {} |
paul@51 | 66 | |
paul@34 | 67 | def combination(rgb): |
paul@56 | 68 | |
paul@56 | 69 | "Return the colour distribution for 'rgb'." |
paul@56 | 70 | |
paul@51 | 71 | if not cache.has_key(rgb): |
paul@56 | 72 | |
paul@56 | 73 | # Get the colour with components scaled from 0 to 1, plus the inverted |
paul@56 | 74 | # component values. |
paul@56 | 75 | |
paul@57 | 76 | rgb = extra(scale(rgb)) |
paul@51 | 77 | rgbi = invert(rgb) |
paul@51 | 78 | pairs = zip(rgbi, rgb) |
paul@56 | 79 | |
paul@56 | 80 | # For each corner of the colour cube (primary and secondary colours plus |
paul@56 | 81 | # black and white), calculate the corner value's contribution to the |
paul@56 | 82 | # input colour. |
paul@56 | 83 | |
paul@51 | 84 | d = [] |
paul@51 | 85 | for corner in corners: |
paul@51 | 86 | rs, gs, bs = scale(corner) |
paul@56 | 87 | |
paul@56 | 88 | # Obtain inverted channel values where corner channels are low; |
paul@56 | 89 | # obtain original channel values where corner channels are high. |
paul@56 | 90 | |
paul@51 | 91 | d.append((pairs[0][int(rs)] * pairs[1][int(gs)] * pairs[2][int(bs)], corner)) |
paul@56 | 92 | |
paul@56 | 93 | # Balance the corner contributions. |
paul@56 | 94 | |
paul@51 | 95 | cache[rgb] = balance(d) |
paul@56 | 96 | |
paul@51 | 97 | return cache[rgb] |
paul@35 | 98 | |
paul@35 | 99 | def complements(rgb): |
paul@56 | 100 | |
paul@56 | 101 | "Return 'rgb' and its complement." |
paul@56 | 102 | |
paul@35 | 103 | r, g, b = rgb |
paul@35 | 104 | return rgb, restore(invert(scale(rgb))) |
paul@35 | 105 | |
paul@35 | 106 | def balance(d): |
paul@56 | 107 | |
paul@56 | 108 | """ |
paul@56 | 109 | Balance distribution 'd', cancelling opposing values and their complements |
paul@56 | 110 | and replacing their common contributions with black and white contributions. |
paul@56 | 111 | """ |
paul@56 | 112 | |
paul@35 | 113 | d = dict([(value, f) for f, value in d]) |
paul@59 | 114 | for primary, secondary in map(complements, [(0, 0, 0), (255, 0, 0), (0, 255, 0), (0, 0, 255)]): |
paul@35 | 115 | common = min(d[primary], d[secondary]) |
paul@35 | 116 | d[primary] -= common |
paul@35 | 117 | d[secondary] -= common |
paul@35 | 118 | return [(f, value) for value, f in d.items()] |
paul@20 | 119 | |
paul@34 | 120 | def combine(d): |
paul@56 | 121 | |
paul@56 | 122 | "Combine distribution 'd' to get a colour value." |
paul@56 | 123 | |
paul@34 | 124 | out = [0, 0, 0] |
paul@34 | 125 | for v, rgb in d: |
paul@34 | 126 | out[0] += v * rgb[0] |
paul@34 | 127 | out[1] += v * rgb[1] |
paul@34 | 128 | out[2] += v * rgb[2] |
paul@34 | 129 | return out |
paul@34 | 130 | |
paul@48 | 131 | def pattern(rgb, chosen=None): |
paul@56 | 132 | |
paul@56 | 133 | """ |
paul@56 | 134 | Obtain a sorted colour distribution for 'rgb', optionally limited to any |
paul@56 | 135 | specified 'chosen' colours. |
paul@56 | 136 | """ |
paul@56 | 137 | |
paul@60 | 138 | l = [(f, value) for f, value in combination(rgb) if not chosen or value in chosen] |
paul@32 | 139 | l.sort(reverse=True) |
paul@20 | 140 | return l |
paul@19 | 141 | |
paul@60 | 142 | def get_value(rgb, chosen=None, fail=False): |
paul@56 | 143 | |
paul@56 | 144 | """ |
paul@56 | 145 | Get an output colour for 'rgb', optionally limited to any specified 'chosen' |
paul@60 | 146 | colours. If 'fail' is set to a true value, return None if the colour cannot |
paul@60 | 147 | be expressed using any of the chosen colours. |
paul@56 | 148 | """ |
paul@56 | 149 | |
paul@48 | 150 | l = pattern(rgb, chosen) |
paul@48 | 151 | limit = sum([f for f, c in l]) |
paul@58 | 152 | if not limit: |
paul@60 | 153 | if fail: |
paul@60 | 154 | return None |
paul@60 | 155 | else: |
paul@60 | 156 | return l[randrange(0, len(l))][1] |
paul@58 | 157 | |
paul@48 | 158 | choose = random() * limit |
paul@32 | 159 | threshold = 0 |
paul@48 | 160 | for f, c in l: |
paul@32 | 161 | threshold += f |
paul@32 | 162 | if choose < threshold: |
paul@32 | 163 | return c |
paul@32 | 164 | return c |
paul@0 | 165 | |
paul@56 | 166 | # Colour processing operations. |
paul@56 | 167 | |
paul@21 | 168 | def sign(x): |
paul@21 | 169 | return x >= 0 and 1 or -1 |
paul@21 | 170 | |
paul@22 | 171 | def saturate_rgb(rgb, exp): |
paul@22 | 172 | return tuple([saturate_value(x, exp) for x in rgb]) |
paul@21 | 173 | |
paul@22 | 174 | def saturate_value(x, exp): |
paul@24 | 175 | return int(127.5 + sign(x - 127.5) * 127.5 * pow(abs(x - 127.5) / 127.5, exp)) |
paul@21 | 176 | |
paul@49 | 177 | def amplify_rgb(rgb, exp): |
paul@49 | 178 | return tuple([amplify_value(x, exp) for x in rgb]) |
paul@49 | 179 | |
paul@49 | 180 | def amplify_value(x, exp): |
paul@49 | 181 | return int(pow(x / 255.0, exp) * 255.0) |
paul@49 | 182 | |
paul@56 | 183 | # Image operations. |
paul@56 | 184 | |
paul@50 | 185 | def get_colours(im, y): |
paul@56 | 186 | |
paul@56 | 187 | "Get a colour distribution from image 'im' for the row 'y'." |
paul@56 | 188 | |
paul@50 | 189 | width, height = im.size |
paul@49 | 190 | c = {} |
paul@49 | 191 | for x in range(0, width): |
paul@49 | 192 | rgb = im.getpixel((x, y)) |
paul@49 | 193 | |
paul@49 | 194 | # Sum the colour probabilities. |
paul@49 | 195 | |
paul@49 | 196 | for f, value in combination(rgb): |
paul@49 | 197 | if not c.has_key(value): |
paul@49 | 198 | c[value] = f |
paul@49 | 199 | else: |
paul@49 | 200 | c[value] += f |
paul@49 | 201 | |
paul@49 | 202 | c = [(n/width, value) for value, n in c.items()] |
paul@49 | 203 | c.sort(reverse=True) |
paul@49 | 204 | return c |
paul@33 | 205 | |
paul@60 | 206 | def get_combinations(c, n): |
paul@60 | 207 | |
paul@60 | 208 | """ |
paul@60 | 209 | Get combinations of colours from 'c' of size 'n' in decreasing order of |
paul@60 | 210 | probability. |
paul@60 | 211 | """ |
paul@60 | 212 | |
paul@60 | 213 | all = [] |
paul@60 | 214 | for l in itertools.combinations(c, n): |
paul@60 | 215 | total = 0 |
paul@60 | 216 | for f, value in l: |
paul@60 | 217 | total += f |
paul@60 | 218 | all.append((total, l)) |
paul@60 | 219 | all.sort(reverse=True) |
paul@60 | 220 | return [l for total, l in all] |
paul@60 | 221 | |
paul@20 | 222 | def test(): |
paul@56 | 223 | |
paul@56 | 224 | "Generate slices of the colour cube." |
paul@56 | 225 | |
paul@20 | 226 | size = 512 |
paul@20 | 227 | for r in (0, 63, 127, 191, 255): |
paul@20 | 228 | im = PIL.Image.new("RGB", (size, size)) |
paul@20 | 229 | for g in range(0, size): |
paul@20 | 230 | for b in range(0, size): |
paul@28 | 231 | value = get_value((r, (g * 256) / size, (b * 256 / size))) |
paul@20 | 232 | im.putpixel((g, b), value) |
paul@20 | 233 | im.save("rgb%d.png" % r) |
paul@20 | 234 | |
paul@20 | 235 | def test_flat(rgb): |
paul@56 | 236 | |
paul@56 | 237 | "Generate a flat image for the colour 'rgb'." |
paul@56 | 238 | |
paul@20 | 239 | size = 64 |
paul@20 | 240 | im = PIL.Image.new("RGB", (size, size)) |
paul@20 | 241 | for y in range(0, size): |
paul@20 | 242 | for x in range(0, size): |
paul@28 | 243 | im.putpixel((x, y), get_value(rgb)) |
paul@20 | 244 | im.save("rgb%02d%02d%02d.png" % rgb) |
paul@20 | 245 | |
paul@50 | 246 | def rotate_and_scale(exif, im, width, height, rotate): |
paul@56 | 247 | |
paul@56 | 248 | """ |
paul@56 | 249 | Using the given 'exif' information, rotate and scale image 'im' given the |
paul@56 | 250 | indicated 'width' and 'height' constraints and any explicit 'rotate' |
paul@56 | 251 | indication. The returned image will be within the given 'width' and |
paul@56 | 252 | 'height', filling either or both, and preserve its original aspect ratio. |
paul@56 | 253 | """ |
paul@56 | 254 | |
paul@50 | 255 | if rotate or exif and exif["Image Orientation"].values == [6L]: |
paul@11 | 256 | im = im.rotate(270) |
paul@19 | 257 | |
paul@4 | 258 | w, h = im.size |
paul@19 | 259 | if w > h: |
paul@19 | 260 | height = (width * h) / w |
paul@19 | 261 | else: |
paul@19 | 262 | width = (height * w) / h |
paul@19 | 263 | |
paul@20 | 264 | return im.resize((width, height)) |
paul@1 | 265 | |
paul@50 | 266 | def count_colours(im, colours): |
paul@56 | 267 | |
paul@56 | 268 | """ |
paul@56 | 269 | Count colours on each row of image 'im', returning a tuple indicating the |
paul@56 | 270 | first row with more than the given number of 'colours' together with the |
paul@56 | 271 | found colours; otherwise returning None. |
paul@56 | 272 | """ |
paul@56 | 273 | |
paul@50 | 274 | width, height = im.size |
paul@50 | 275 | for y in range(0, height): |
paul@50 | 276 | l = set() |
paul@50 | 277 | for x in range(0, width): |
paul@50 | 278 | l.add(im.getpixel((x, y))) |
paul@50 | 279 | if len(l) > colours: |
paul@50 | 280 | return (y, l) |
paul@50 | 281 | return None |
paul@50 | 282 | |
paul@56 | 283 | # Main program. |
paul@56 | 284 | |
paul@20 | 285 | if __name__ == "__main__": |
paul@56 | 286 | |
paul@56 | 287 | # Test options. |
paul@56 | 288 | |
paul@20 | 289 | if "--test" in sys.argv: |
paul@20 | 290 | test() |
paul@20 | 291 | sys.exit(0) |
paul@20 | 292 | elif "--test-flat" in sys.argv: |
paul@20 | 293 | test_flat((120, 40, 60)) |
paul@20 | 294 | sys.exit(0) |
paul@56 | 295 | elif "--help" in sys.argv: |
paul@56 | 296 | print >>sys.stderr, """\ |
paul@56 | 297 | Usage: %s <input filename> <output filename> [ <options> ] |
paul@56 | 298 | |
paul@56 | 299 | Options are... |
paul@56 | 300 | |
paul@56 | 301 | -s - Saturate the input image (can be repeated) |
paul@56 | 302 | -d - Desaturate the input image (can be repeated) |
paul@56 | 303 | -D - Darken the input image (can be repeated) |
paul@56 | 304 | -B - Brighten the input image (can be repeated) |
paul@56 | 305 | -2 - Square/diminish the bright corner colour contributions (experimental) |
paul@56 | 306 | |
paul@56 | 307 | -r - Rotate the input image clockwise |
paul@56 | 308 | -p - Generate a separate preview image |
paul@56 | 309 | -h - Make the preview image with half horizontal resolution (MODE 2) |
paul@56 | 310 | -v - Verify the output image (loaded if -n is given) |
paul@56 | 311 | -n - Generate no output image |
paul@56 | 312 | """ % split(sys.argv[0])[1] |
paul@56 | 313 | sys.exit(1) |
paul@0 | 314 | |
paul@20 | 315 | width = 320 |
paul@20 | 316 | height = 256 |
paul@20 | 317 | |
paul@20 | 318 | input_filename, output_filename = sys.argv[1:3] |
paul@26 | 319 | basename, ext = splitext(output_filename) |
paul@35 | 320 | preview_filename = "".join([basename + "_preview", ext]) |
paul@26 | 321 | |
paul@50 | 322 | options = sys.argv[3:] |
paul@1 | 323 | |
paul@56 | 324 | # Preprocessing options that can be repeated for extra effect. |
paul@56 | 325 | |
paul@50 | 326 | saturate = options.count("-s") |
paul@50 | 327 | desaturate = options.count("-d") |
paul@50 | 328 | darken = options.count("-D") |
paul@50 | 329 | brighten = options.count("-B") |
paul@56 | 330 | |
paul@56 | 331 | # Experimental colour distribution modification. |
paul@56 | 332 | |
paul@57 | 333 | use_square = "-2" in options |
paul@57 | 334 | if use_square: |
paul@57 | 335 | extra = square |
paul@56 | 336 | |
paul@56 | 337 | # General output options. |
paul@56 | 338 | |
paul@56 | 339 | rotate = "-r" in options |
paul@50 | 340 | preview = "-p" in options |
paul@50 | 341 | half_resolution_preview = "-h" in options |
paul@50 | 342 | verify = "-v" in options |
paul@50 | 343 | no_normal_output = "-n" in options |
paul@50 | 344 | make_image = not no_normal_output |
paul@1 | 345 | |
paul@56 | 346 | # Load the input image if requested. |
paul@56 | 347 | |
paul@50 | 348 | if make_image or preview: |
paul@50 | 349 | exif = EXIF.process_file(open(input_filename)) |
paul@50 | 350 | im = PIL.Image.open(input_filename).convert("RGB") |
paul@50 | 351 | im = rotate_and_scale(exif, im, width, height, rotate) |
paul@50 | 352 | |
paul@50 | 353 | width, height = im.size |
paul@20 | 354 | |
paul@50 | 355 | if saturate or desaturate or darken or brighten: |
paul@50 | 356 | for y in range(0, height): |
paul@50 | 357 | for x in range(0, width): |
paul@51 | 358 | rgb = im.getpixel((x, y)) |
paul@50 | 359 | if saturate or desaturate: |
paul@50 | 360 | rgb = saturate_rgb(rgb, saturate and math.pow(0.5, saturate) or math.pow(2, desaturate)) |
paul@50 | 361 | if darken or brighten: |
paul@50 | 362 | rgb = amplify_rgb(rgb, brighten and math.pow(0.5, brighten) or math.pow(2, darken)) |
paul@51 | 363 | im.putpixel((x, y), rgb) |
paul@10 | 364 | |
paul@56 | 365 | # Generate a preview if requested. |
paul@56 | 366 | |
paul@35 | 367 | if preview: |
paul@35 | 368 | imp = im.copy() |
paul@50 | 369 | step = half_resolution_preview and 2 or 1 |
paul@35 | 370 | for y in range(0, height): |
paul@50 | 371 | for x in range(0, width, step): |
paul@35 | 372 | rgb = imp.getpixel((x, y)) |
paul@35 | 373 | value = get_value(rgb) |
paul@35 | 374 | imp.putpixel((x, y), value) |
paul@50 | 375 | if half_resolution_preview: |
paul@50 | 376 | imp.putpixel((x+1, y), value) |
paul@50 | 377 | |
paul@35 | 378 | imp.save(preview_filename) |
paul@35 | 379 | |
paul@56 | 380 | # Generate an output image if requested. |
paul@56 | 381 | |
paul@50 | 382 | if make_image: |
paul@50 | 383 | for y in range(0, height): |
paul@50 | 384 | c = get_colours(im, y) |
paul@60 | 385 | |
paul@60 | 386 | for l in get_combinations(c, 4): |
paul@60 | 387 | most = [value for f, value in l] |
paul@60 | 388 | for x in range(0, width): |
paul@60 | 389 | rgb = im.getpixel((x, y)) |
paul@60 | 390 | value = get_value(rgb, most, True) |
paul@60 | 391 | if value is None: |
paul@60 | 392 | break # try next combination |
paul@60 | 393 | else: |
paul@60 | 394 | break # use this combination |
paul@60 | 395 | else: |
paul@60 | 396 | most = [value for f, value in c[:4]] # use the first four |
paul@50 | 397 | |
paul@50 | 398 | for x in range(0, width): |
paul@50 | 399 | rgb = im.getpixel((x, y)) |
paul@50 | 400 | value = get_value(rgb, most) |
paul@50 | 401 | im.putpixel((x, y), value) |
paul@1 | 402 | |
paul@50 | 403 | if y < height - 1: |
paul@50 | 404 | rgbn = im.getpixel((x, y+1)) |
paul@50 | 405 | rgbn = tuple(map(lambda i: clip(i[0] + i[1] - i[2]), zip(rgbn, rgb, value))) |
paul@50 | 406 | im.putpixel((x, y+1), rgbn) |
paul@50 | 407 | |
paul@50 | 408 | im.save(output_filename) |
paul@1 | 409 | |
paul@56 | 410 | # Verify the output image (which may be loaded) if requested. |
paul@56 | 411 | |
paul@50 | 412 | if verify: |
paul@50 | 413 | if no_normal_output: |
paul@50 | 414 | im = PIL.Image.open(output_filename).convert("RGB") |
paul@49 | 415 | |
paul@50 | 416 | result = count_colours(im, 4) |
paul@50 | 417 | if result is not None: |
paul@50 | 418 | y, colours = result |
paul@56 | 419 | print "Image %s: row %d has the following colours: %s" % (output_filename, y, "; ".join([repr(c) for c in colours])) |
paul@0 | 420 | |
paul@0 | 421 | # vim: tabstop=4 expandtab shiftwidth=4 |