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