Skip to content

Commit bc711fa

Browse files
committed
Added imgshow.py
1 parent 4411cf9 commit bc711fa

File tree

1 file changed

+111
-0
lines changed

1 file changed

+111
-0
lines changed

src/imgshow.py

Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
#!/usr/bin/env python2
2+
#{{{ Imports
3+
from __future__ import print_function, division
4+
import sys
5+
import scipy.misc as img
6+
import numpy as np
7+
#}}}
8+
9+
10+
11+
12+
#{{{ Resize image to a specific (terminal) width
13+
def resize(image, width):
14+
iheight = image.shape[0]
15+
iwidth = image.shape[1]
16+
17+
twidth = width
18+
19+
nwidth = twidth
20+
nheight = iheight / (iwidth/twidth)
21+
nheight /= 2
22+
nwidth = int(nwidth)
23+
nheight = int(nheight)
24+
25+
return img.imresize(image, (nheight, nwidth))
26+
#}}}
27+
28+
29+
#{{{ Map each pixel based on a function
30+
def imgmap(image, fn):
31+
height = image.shape[0]
32+
width = image.shape[1]
33+
# grey = np.zeros((height, width))
34+
result = np.reshape(np.repeat(fn(image[0][0]), height*width), (height, width))
35+
for y in range(height):
36+
for x in range(width):
37+
result[y][x] = fn(image[y][x])
38+
return result
39+
#}}}
40+
41+
42+
#{{{ Print pixel matrix to the screen
43+
def render(image):
44+
height = image.shape[0]
45+
width = image.shape[1]
46+
for y in range(height):
47+
for x in range(width):
48+
print(image[y][x], end='')
49+
print('')
50+
#}}}
51+
52+
53+
54+
55+
#{{{ Run
56+
def run(data, width=80, charset=' .,-:;!*=$#@'):
57+
normalize = lambda image: imgmap(image, lambda pixel: pixel/255)
58+
charmap = lambda image: imgmap(image, lambda pixel: charset[int(pixel * (len(charset)-1))])
59+
60+
render(charmap(normalize(resize(data, width))))
61+
62+
return True
63+
#}}}
64+
65+
66+
#{{{ Main
67+
def main(argv=None):
68+
if argv is None:
69+
argv = sys.argv
70+
argc = len(argv)
71+
72+
if argc < 2:
73+
print('%s: error: insufficient arguments' % (argv[0]))
74+
return 1
75+
76+
data = None
77+
width = 80
78+
# chars = '@#$=*!;:~-,. '
79+
chars = ' .,-:;!*=$#@'
80+
81+
if argc >= 4:
82+
if len(argv[3]) < 1:
83+
print('%s: error: chars must contain at least one character' % (argv[0]))
84+
return 1
85+
chars = argv[3]
86+
87+
88+
if argc >= 3:
89+
try:
90+
width = int(argv[2])
91+
except:
92+
print('%s: error: width must be a positive, non-zero integer' % (argv[0]))
93+
return 1
94+
if width < 1:
95+
print('%s: error: width must be a positive, non-zero integer' % (argv[0]))
96+
return 1
97+
98+
if argc >= 2:
99+
try:
100+
data = img.imread(argv[1], True)
101+
except:
102+
print('%s: error: could not open %s' % (argv[0], argv[1]))
103+
return 1
104+
105+
run(data, width, chars)
106+
return 0
107+
108+
109+
if __name__ == '__main__':
110+
sys.exit(main())
111+
#}}}

0 commit comments

Comments
 (0)