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