2 from functools
import partial
8 CLUT
= [ # color look-up table
11 # Primary 3-bit (8 colors). Unique representation!
21 # Equivalent "bright" versions of original 8 colors.
278 short2rgb_dict
= dict(CLUT
)
280 for k
, v
in short2rgb_dict
.items():
281 rgb2short_dict
[v
] = k
282 return rgb2short_dict
, short2rgb_dict
284 RGB2SHORT_DICT
, SHORT2RGB_DICT
= _create_dicts()
287 def short2rgb(short
):
288 return SHORT2RGB_DICT
[short
]
291 def pixel_print(ansicolor
):
292 sys
.stdout
.write('\033[48;5;%sm \033[0m' % (ansicolor
))
295 def hex_to_rgb(value
):
296 value
= value
.lstrip('#')
298 return tuple(int(value
[i
:i
+ lv
/ 3], 16) for i
in range(0, lv
, lv
/ 3))
302 return '%02x%02x%02x' % rgb
305 def rgb2short(r
, g
, b
):
306 dist
= lambda s
, d
: (s
[0] - d
[0]) ** 2 + \
307 (s
[1] - d
[1]) ** 2 + (s
[2] - d
[2]) ** 2
308 ary
= [hex_to_rgb(hex) for hex in RGB2SHORT_DICT
]
309 m
= min(ary
, key
=partial(dist
, (r
, g
, b
)))
310 return RGB2SHORT_DICT
[rgb_to_hex(m
)]
313 def image_to_display(path
):
315 i
= i
.convert('RGBA')
318 rows
, columns
= os
.popen('stty size', 'r').read().split()
319 width
= min(w
, int(columns
) - 2 * IMAGE_SHIFT
)
320 height
= int(float(h
) * (float(width
) / float(w
)))
322 i
= i
.resize((width
, height
), Image
.BICUBIC
)
323 height
= min(height
, IMAGE_MAX_HEIGHT
)
325 for y
in xrange(height
):
326 print ' ' * IMAGE_SHIFT
,
327 for x
in xrange(width
):
328 p
= i
.getpixel((x
, y
))
330 pixel_print(rgb2short(r
, g
, b
))
333 if __name__
== '__main__':
334 image_to_display(sys
.argv
[1])