0a75d7795755b8e8ae7d585fd67bd35c00a55940
1 from PIL
import Image
,ImageFilter
2 from functools
import partial
6 CLUT
= [ # color look-up table
9 # Primary 3-bit (8 colors). Unique representation!
19 # Equivalent "bright" versions of original 8 colors.
275 short2rgb_dict
= dict(CLUT
)
277 for k
, v
in short2rgb_dict
.items():
278 rgb2short_dict
[v
] = k
279 return rgb2short_dict
, short2rgb_dict
281 RGB2SHORT_DICT
, SHORT2RGB_DICT
= _create_dicts()
284 def short2rgb(short
):
285 return SHORT2RGB_DICT
[short
]
288 def pixel_print(ansicolor
):
289 sys
.stdout
.write('\033[48;5;%sm \033[0m' % (ansicolor
))
292 def hex_to_rgb(value
):
293 value
= value
.lstrip('#')
295 return tuple(int(value
[i
:i
+lv
/3], 16) for i
in range(0, lv
, lv
/3))
299 return '%02x%02x%02x' % rgb
302 def rgb2short(r
, g
, b
):
303 dist
= lambda s
,d
: (s
[0]-d
[0])**2+(s
[1]-d
[1])**2+(s
[2]-d
[2])**2
304 ary
= [hex_to_rgb(hex) for hex in RGB2SHORT_DICT
]
305 m
= min(ary
, key
=partial(dist
, (r
,g
,b
)))
306 return RGB2SHORT_DICT
[rgb_to_hex(m
)]
308 def image_to_display(path
):
310 i
= i
.convert('RGBA')
313 rows
, columns
= os
.popen('stty size', 'r').read().split()
314 width
= min(w
, int(columns
)-2*6)
315 height
= int(float(h
) * (float(width
) / float(w
)))
317 i
= i
.resize((width
, height
), Image
.BICUBIC
)
318 height
= min(height
,30)
320 for y
in xrange(height
):
322 for x
in xrange(width
):
323 p
= i
.getpixel((x
,y
))
325 pixel_print(rgb2short(r
,g
,b
))
328 if __name__
== '__main__':
329 image_to_display(sys
.argv
[1])