2 from functools
import partial
9 This file is borrowed from following gist:
10 https://gist.github.com/MicahElliott/719710
11 It's too slow in compare with C program.
14 CLUT
= [ # color look-up table
17 # Primary 3-bit (8 colors). Unique representation!
27 # Equivalent "bright" versions of original 8 colors.
287 short2rgb_dict
= dict(CLUT
)
289 for k
, v
in short2rgb_dict
.items():
290 rgb2short_dict
[v
] = k
291 return rgb2short_dict
, short2rgb_dict
293 RGB2SHORT_DICT
, SHORT2RGB_DICT
= _create_dicts()
296 def short2rgb(short
):
300 return SHORT2RGB_DICT
[short
]
303 def pixel_print(ansicolor
):
305 Print a pixel with given Ansi color
307 sys
.stdout
.write('\033[48;5;%sm \033[0m' % (ansicolor
))
310 def hex_to_rgb(value
):
314 value
= value
.lstrip('#')
316 return tuple(int(value
[i
:i
+ lv
/ 3], 16) for i
in range(0, lv
, lv
/ 3))
323 return '%02x%02x%02x' % rgb
326 def rgb2short(r
, g
, b
):
330 dist
= lambda s
, d
: (s
[0] - d
[0]) ** 2 + \
331 (s
[1] - d
[1]) ** 2 + (s
[2] - d
[2]) ** 2
332 ary
= [hex_to_rgb(hex) for hex in RGB2SHORT_DICT
]
333 m
= min(ary
, key
=partial(dist
, (r
, g
, b
)))
334 return RGB2SHORT_DICT
[rgb_to_hex(m
)]
337 def image_to_display(path
, start
=None, length
=None):
341 rows
, columns
= os
.popen('stty size', 'r').read().split()
345 length
= int(columns
) - 2 * start
347 i
= i
.convert('RGBA')
350 width
= min(w
, length
)
351 height
= int(float(h
) * (float(width
) / float(w
)))
353 i
= i
.resize((width
, height
), Image
.BICUBIC
)
354 height
= min(height
, IMAGE_MAX_HEIGHT
)
356 for y
in xrange(height
):
357 sys
.stdout
.write(' ' * start
)
358 for x
in xrange(width
):
359 p
= i
.getpixel((x
, y
))
361 pixel_print(rgb2short(r
, g
, b
))
362 sys
.stdout
.write('\n')
366 For direct using purpose
368 if __name__
== '__main__':
369 image_to_display(sys
.argv
[1])