f4cb751cdd70a6ca70d51bf229d09be2d47475fc
2 from functools
import partial
7 CLUT
= [ # color look-up table
10 # Primary 3-bit (8 colors). Unique representation!
20 # Equivalent "bright" versions of original 8 colors.
277 short2rgb_dict
= dict(CLUT
)
279 for k
, v
in short2rgb_dict
.items():
280 rgb2short_dict
[v
] = k
281 return rgb2short_dict
, short2rgb_dict
283 RGB2SHORT_DICT
, SHORT2RGB_DICT
= _create_dicts()
286 def short2rgb(short
):
287 return SHORT2RGB_DICT
[short
]
290 def pixel_print(ansicolor
):
291 sys
.stdout
.write('\033[48;5;%sm \033[0m' % (ansicolor
))
294 def hex_to_rgb(value
):
295 value
= value
.lstrip('#')
297 return tuple(int(value
[i
:i
+ lv
/ 3], 16) for i
in range(0, lv
, lv
/ 3))
301 return '%02x%02x%02x' % rgb
304 def rgb2short(r
, g
, b
):
305 dist
= lambda s
, d
: (s
[0] - d
[0]) ** 2 + \
306 (s
[1] - d
[1]) ** 2 + (s
[2] - d
[2]) ** 2
307 ary
= [hex_to_rgb(hex) for hex in RGB2SHORT_DICT
]
308 m
= min(ary
, key
=partial(dist
, (r
, g
, b
)))
309 return RGB2SHORT_DICT
[rgb_to_hex(m
)]
312 def image_to_display(path
):
314 i
= i
.convert('RGBA')
317 rows
, columns
= os
.popen('stty size', 'r').read().split()
318 width
= min(w
, int(columns
) - 2 * 6)
319 height
= int(float(h
) * (float(width
) / float(w
)))
321 i
= i
.resize((width
, height
), Image
.BICUBIC
)
322 height
= min(height
, 30)
324 for y
in xrange(height
):
326 for x
in xrange(width
):
327 p
= i
.getpixel((x
, y
))
329 pixel_print(rgb2short(r
, g
, b
))
332 if __name__
== '__main__':
333 image_to_display(sys
.argv
[1])