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@79 | 61 | scaled_corners = map(scale, corners) |
paul@79 | 62 | zipped_corners = zip(corners, scaled_corners) |
paul@79 | 63 | |
paul@56 | 64 | # Colour distribution functions. |
paul@56 | 65 | |
paul@34 | 66 | def combination(rgb): |
paul@56 | 67 | |
paul@56 | 68 | "Return the colour distribution for 'rgb'." |
paul@56 | 69 | |
paul@63 | 70 | # Get the colour with components scaled from 0 to 1, plus the inverted |
paul@63 | 71 | # component values. |
paul@56 | 72 | |
paul@67 | 73 | rgb = scale(rgb) |
paul@63 | 74 | rgbi = invert(rgb) |
paul@63 | 75 | pairs = zip(rgbi, rgb) |
paul@56 | 76 | |
paul@63 | 77 | # For each corner of the colour cube (primary and secondary colours plus |
paul@63 | 78 | # black and white), calculate the corner value's contribution to the |
paul@63 | 79 | # input colour. |
paul@56 | 80 | |
paul@63 | 81 | d = [] |
paul@79 | 82 | for corner, scaled in zipped_corners: |
paul@79 | 83 | rs, gs, bs = scaled |
paul@56 | 84 | |
paul@63 | 85 | # Obtain inverted channel values where corner channels are low; |
paul@63 | 86 | # obtain original channel values where corner channels are high. |
paul@56 | 87 | |
paul@63 | 88 | d.append((pairs[0][int(rs)] * pairs[1][int(gs)] * pairs[2][int(bs)], corner)) |
paul@56 | 89 | |
paul@63 | 90 | # Balance the corner contributions. |
paul@63 | 91 | |
paul@63 | 92 | return balance(d) |
paul@35 | 93 | |
paul@35 | 94 | def complements(rgb): |
paul@56 | 95 | |
paul@56 | 96 | "Return 'rgb' and its complement." |
paul@56 | 97 | |
paul@35 | 98 | r, g, b = rgb |
paul@35 | 99 | return rgb, restore(invert(scale(rgb))) |
paul@35 | 100 | |
paul@79 | 101 | bases = [(0, 0, 0), (255, 0, 0), (0, 255, 0), (0, 0, 255)] |
paul@79 | 102 | base_complements = map(complements, bases) |
paul@79 | 103 | |
paul@35 | 104 | def balance(d): |
paul@56 | 105 | |
paul@56 | 106 | """ |
paul@56 | 107 | Balance distribution 'd', cancelling opposing values and their complements |
paul@56 | 108 | and replacing their common contributions with black and white contributions. |
paul@56 | 109 | """ |
paul@56 | 110 | |
paul@35 | 111 | d = dict([(value, f) for f, value in d]) |
paul@79 | 112 | for primary, secondary in base_complements: |
paul@35 | 113 | common = min(d[primary], d[secondary]) |
paul@35 | 114 | d[primary] -= common |
paul@35 | 115 | d[secondary] -= common |
paul@35 | 116 | return [(f, value) for value, f in d.items()] |
paul@20 | 117 | |
paul@34 | 118 | def combine(d): |
paul@56 | 119 | |
paul@56 | 120 | "Combine distribution 'd' to get a colour value." |
paul@56 | 121 | |
paul@34 | 122 | out = [0, 0, 0] |
paul@34 | 123 | for v, rgb in d: |
paul@34 | 124 | out[0] += v * rgb[0] |
paul@34 | 125 | out[1] += v * rgb[1] |
paul@34 | 126 | out[2] += v * rgb[2] |
paul@34 | 127 | return out |
paul@34 | 128 | |
paul@48 | 129 | def pattern(rgb, chosen=None): |
paul@56 | 130 | |
paul@56 | 131 | """ |
paul@56 | 132 | Obtain a sorted colour distribution for 'rgb', optionally limited to any |
paul@56 | 133 | specified 'chosen' colours. |
paul@56 | 134 | """ |
paul@56 | 135 | |
paul@60 | 136 | l = [(f, value) for f, value in combination(rgb) if not chosen or value in chosen] |
paul@32 | 137 | l.sort(reverse=True) |
paul@20 | 138 | return l |
paul@19 | 139 | |
paul@60 | 140 | def get_value(rgb, chosen=None, fail=False): |
paul@56 | 141 | |
paul@56 | 142 | """ |
paul@56 | 143 | Get an output colour for 'rgb', optionally limited to any specified 'chosen' |
paul@60 | 144 | colours. If 'fail' is set to a true value, return None if the colour cannot |
paul@60 | 145 | be expressed using any of the chosen colours. |
paul@56 | 146 | """ |
paul@56 | 147 | |
paul@48 | 148 | l = pattern(rgb, chosen) |
paul@48 | 149 | limit = sum([f for f, c in l]) |
paul@58 | 150 | if not limit: |
paul@60 | 151 | if fail: |
paul@60 | 152 | return None |
paul@60 | 153 | else: |
paul@60 | 154 | return l[randrange(0, len(l))][1] |
paul@58 | 155 | |
paul@48 | 156 | choose = random() * limit |
paul@32 | 157 | threshold = 0 |
paul@48 | 158 | for f, c in l: |
paul@32 | 159 | threshold += f |
paul@32 | 160 | if choose < threshold: |
paul@32 | 161 | return c |
paul@32 | 162 | return c |
paul@0 | 163 | |
paul@56 | 164 | # Colour processing operations. |
paul@56 | 165 | |
paul@21 | 166 | def sign(x): |
paul@21 | 167 | return x >= 0 and 1 or -1 |
paul@21 | 168 | |
paul@22 | 169 | def saturate_rgb(rgb, exp): |
paul@77 | 170 | r, g, b = rgb |
paul@77 | 171 | return saturate_value(r, exp), saturate_value(g, exp), saturate_value(b, exp) |
paul@21 | 172 | |
paul@22 | 173 | def saturate_value(x, exp): |
paul@24 | 174 | return int(127.5 + sign(x - 127.5) * 127.5 * pow(abs(x - 127.5) / 127.5, exp)) |
paul@21 | 175 | |
paul@49 | 176 | def amplify_rgb(rgb, exp): |
paul@77 | 177 | r, g, b = rgb |
paul@77 | 178 | return amplify_value(r, exp), amplify_value(g, exp), amplify_value(b, exp) |
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@70 | 275 | |
paul@50 | 276 | for y in range(0, height): |
paul@50 | 277 | l = set() |
paul@50 | 278 | for x in range(0, width): |
paul@50 | 279 | l.add(im.getpixel((x, y))) |
paul@50 | 280 | if len(l) > colours: |
paul@50 | 281 | return (y, l) |
paul@50 | 282 | return None |
paul@50 | 283 | |
paul@70 | 284 | def process_image(im, saturate, desaturate, darken, brighten): |
paul@70 | 285 | |
paul@70 | 286 | """ |
paul@70 | 287 | Process image 'im' using the given options: 'saturate', 'desaturate', |
paul@70 | 288 | 'darken', 'brighten'. |
paul@70 | 289 | """ |
paul@70 | 290 | |
paul@70 | 291 | width, height = im.size |
paul@70 | 292 | |
paul@70 | 293 | if saturate or desaturate or darken or brighten: |
paul@70 | 294 | for y in range(0, height): |
paul@70 | 295 | for x in range(0, width): |
paul@70 | 296 | rgb = im.getpixel((x, y)) |
paul@70 | 297 | if saturate or desaturate: |
paul@70 | 298 | rgb = saturate_rgb(rgb, saturate and 0.5 / saturate or 2 * desaturate) |
paul@70 | 299 | if darken or brighten: |
paul@70 | 300 | rgb = amplify_rgb(rgb, brighten and 0.5 / brighten or 2 * darken) |
paul@70 | 301 | im.putpixel((x, y), rgb) |
paul@70 | 302 | |
paul@70 | 303 | def preview_image(im, half_resolution_preview=False): |
paul@70 | 304 | |
paul@70 | 305 | "Return a preview copy of image 'im'." |
paul@70 | 306 | |
paul@70 | 307 | width, height = im.size |
paul@70 | 308 | |
paul@70 | 309 | imp = im.copy() |
paul@70 | 310 | step = half_resolution_preview and 2 or 1 |
paul@70 | 311 | |
paul@70 | 312 | for y in range(0, height): |
paul@70 | 313 | for x in range(0, width, step): |
paul@70 | 314 | rgb = imp.getpixel((x, y)) |
paul@70 | 315 | value = get_value(rgb) |
paul@70 | 316 | imp.putpixel((x, y), value) |
paul@70 | 317 | if half_resolution_preview: |
paul@70 | 318 | imp.putpixel((x+1, y), value) |
paul@70 | 319 | |
paul@70 | 320 | return imp |
paul@70 | 321 | |
paul@70 | 322 | def convert_image(im): |
paul@70 | 323 | |
paul@70 | 324 | "Convert image 'im' to an appropriate output representation." |
paul@70 | 325 | |
paul@70 | 326 | width, height = im.size |
paul@70 | 327 | |
paul@70 | 328 | for y in range(0, height): |
paul@70 | 329 | c = get_colours(im, y) |
paul@70 | 330 | |
paul@70 | 331 | for l in get_combinations(c, 4): |
paul@70 | 332 | most = [value for f, value in l] |
paul@70 | 333 | for x in range(0, width): |
paul@70 | 334 | rgb = im.getpixel((x, y)) |
paul@70 | 335 | value = get_value(rgb, most, True) |
paul@70 | 336 | if value is None: |
paul@70 | 337 | break # try next combination |
paul@70 | 338 | else: |
paul@70 | 339 | break # use this combination |
paul@70 | 340 | else: |
paul@70 | 341 | most = [value for f, value in c[:4]] # use the first four |
paul@70 | 342 | |
paul@70 | 343 | for x in range(0, width): |
paul@70 | 344 | rgb = im.getpixel((x, y)) |
paul@70 | 345 | value = get_value(rgb, most) |
paul@70 | 346 | im.putpixel((x, y), value) |
paul@70 | 347 | |
paul@70 | 348 | if x < width - 1: |
paul@70 | 349 | rgbn = im.getpixel((x+1, y)) |
paul@77 | 350 | rgbn = ( |
paul@77 | 351 | clip(rgbn[0] + (rgb[0] - value[0]) / 4.0), |
paul@77 | 352 | clip(rgbn[1] + (rgb[1] - value[1]) / 4.0), |
paul@77 | 353 | clip(rgbn[2] + (rgb[2] - value[2]) / 4.0) |
paul@77 | 354 | ) |
paul@70 | 355 | im.putpixel((x+1, y), rgbn) |
paul@70 | 356 | |
paul@70 | 357 | if y < height - 1: |
paul@70 | 358 | rgbn = im.getpixel((x, y+1)) |
paul@77 | 359 | rgbn = ( |
paul@77 | 360 | clip(rgbn[0] + (rgb[0] - value[0]) / 2.0), |
paul@77 | 361 | clip(rgbn[1] + (rgb[1] - value[1]) / 2.0), |
paul@77 | 362 | clip(rgbn[2] + (rgb[2] - value[2]) / 2.0) |
paul@77 | 363 | ) |
paul@70 | 364 | im.putpixel((x, y+1), rgbn) |
paul@70 | 365 | |
paul@65 | 366 | def get_float(options, flag): |
paul@65 | 367 | try: |
paul@65 | 368 | i = options.index(flag) |
paul@66 | 369 | if i+1 < len(options) and options[i+1].isdigit(): |
paul@65 | 370 | return float(options[i+1]) |
paul@65 | 371 | else: |
paul@65 | 372 | return 1.0 |
paul@65 | 373 | except ValueError: |
paul@65 | 374 | return 0.0 |
paul@65 | 375 | |
paul@56 | 376 | # Main program. |
paul@56 | 377 | |
paul@20 | 378 | if __name__ == "__main__": |
paul@56 | 379 | |
paul@56 | 380 | # Test options. |
paul@56 | 381 | |
paul@20 | 382 | if "--test" in sys.argv: |
paul@20 | 383 | test() |
paul@20 | 384 | sys.exit(0) |
paul@20 | 385 | elif "--test-flat" in sys.argv: |
paul@20 | 386 | test_flat((120, 40, 60)) |
paul@20 | 387 | sys.exit(0) |
paul@56 | 388 | elif "--help" in sys.argv: |
paul@56 | 389 | print >>sys.stderr, """\ |
paul@56 | 390 | Usage: %s <input filename> <output filename> [ <options> ] |
paul@56 | 391 | |
paul@56 | 392 | Options are... |
paul@56 | 393 | |
paul@67 | 394 | -s - Saturate the input image (can be followed by a float, default 1.0) |
paul@67 | 395 | -d - Desaturate the input image (can be followed by a float, default 1.0) |
paul@65 | 396 | -D - Darken the input image (can be followed by a float, default 1.0) |
paul@65 | 397 | -B - Brighten the input image (can be followed by a float, default 1.0) |
paul@56 | 398 | |
paul@56 | 399 | -r - Rotate the input image clockwise |
paul@56 | 400 | -p - Generate a separate preview image |
paul@56 | 401 | -h - Make the preview image with half horizontal resolution (MODE 2) |
paul@56 | 402 | -v - Verify the output image (loaded if -n is given) |
paul@56 | 403 | -n - Generate no output image |
paul@56 | 404 | """ % split(sys.argv[0])[1] |
paul@56 | 405 | sys.exit(1) |
paul@0 | 406 | |
paul@20 | 407 | width = 320 |
paul@20 | 408 | height = 256 |
paul@20 | 409 | |
paul@20 | 410 | input_filename, output_filename = sys.argv[1:3] |
paul@26 | 411 | basename, ext = splitext(output_filename) |
paul@35 | 412 | preview_filename = "".join([basename + "_preview", ext]) |
paul@26 | 413 | |
paul@50 | 414 | options = sys.argv[3:] |
paul@1 | 415 | |
paul@56 | 416 | # Preprocessing options that can be repeated for extra effect. |
paul@56 | 417 | |
paul@67 | 418 | saturate = get_float(options, "-s") |
paul@67 | 419 | desaturate = get_float(options, "-d") |
paul@65 | 420 | darken = get_float(options, "-D") |
paul@65 | 421 | brighten = get_float(options, "-B") |
paul@64 | 422 | |
paul@56 | 423 | # General output options. |
paul@56 | 424 | |
paul@56 | 425 | rotate = "-r" in options |
paul@50 | 426 | preview = "-p" in options |
paul@50 | 427 | half_resolution_preview = "-h" in options |
paul@50 | 428 | verify = "-v" in options |
paul@50 | 429 | no_normal_output = "-n" in options |
paul@50 | 430 | make_image = not no_normal_output |
paul@1 | 431 | |
paul@56 | 432 | # Load the input image if requested. |
paul@56 | 433 | |
paul@50 | 434 | if make_image or preview: |
paul@50 | 435 | exif = EXIF.process_file(open(input_filename)) |
paul@50 | 436 | im = PIL.Image.open(input_filename).convert("RGB") |
paul@50 | 437 | im = rotate_and_scale(exif, im, width, height, rotate) |
paul@50 | 438 | |
paul@70 | 439 | process_image(im, saturate, desaturate, darken, brighten) |
paul@10 | 440 | |
paul@56 | 441 | # Generate a preview if requested. |
paul@56 | 442 | |
paul@35 | 443 | if preview: |
paul@70 | 444 | preview_image(im, half_resolution_preview).save(preview_filename) |
paul@35 | 445 | |
paul@56 | 446 | # Generate an output image if requested. |
paul@56 | 447 | |
paul@50 | 448 | if make_image: |
paul@70 | 449 | convert_image(im) |
paul@50 | 450 | im.save(output_filename) |
paul@1 | 451 | |
paul@56 | 452 | # Verify the output image (which may be loaded) if requested. |
paul@56 | 453 | |
paul@50 | 454 | if verify: |
paul@50 | 455 | if no_normal_output: |
paul@50 | 456 | im = PIL.Image.open(output_filename).convert("RGB") |
paul@49 | 457 | |
paul@50 | 458 | result = count_colours(im, 4) |
paul@50 | 459 | if result is not None: |
paul@50 | 460 | y, colours = result |
paul@56 | 461 | print "Image %s: row %d has the following colours: %s" % (output_filename, y, "; ".join([repr(c) for c in colours])) |
paul@0 | 462 | |
paul@0 | 463 | # vim: tabstop=4 expandtab shiftwidth=4 |