-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimg2ascii.py
115 lines (83 loc) · 2.5 KB
/
img2ascii.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# Python code to convert an image to ASCII image.
import sys, random, argparse
import numpy as np
import math
from PIL import Image
# gray scale level values from:
# http://paulbourke.net/dataformats/asciiart/
# 70 levels of gray
gscale1 = "$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. "
# 10 levels of gray
gscale2 = '@%#*+=-:. '
def getAverageL(image):
"""
Given PIL Image, return average value of grayscale value
"""
# get image as numpy array
im = np.array(image)
# get shape
w, h = im.shape
# get average
return np.average(im.reshape(w * h))
def covertImageToAscii(fileName, cols, scale, moreLevels):
"""
Given Image and dims (rows, cols) returns an m*n list of Images
"""
# declare globals
global gscale1, gscale2
# open image and convert to grayscale
image = Image.open(fileName).convert('L')
# store dimensions
W, H = image.size[0], image.size[1]
# compute width of tile
w = W / cols
# compute tile height based on aspect ratio and scale
h = w / scale
# compute number of rows
rows = int(H / h)
# check if image size is too small
if cols > W or rows > H:
exit(0)
# ascii image is a list of character strings
aimg = []
# generate list of dimensions
for j in range(rows):
y1 = int(j * h)
y2 = int((j + 1) * h)
# correct last tile
if j == rows - 1:
y2 = H
# append an empty string
aimg.append("")
for i in range(cols):
# crop image to tile
x1 = int(i * w)
x2 = int((i + 1) * w)
# correct last tile
if i == cols - 1:
x2 = W
# crop image to extract tile
img = image.crop((x1, y1, x2, y2))
# get average luminance
avg = int(getAverageL(img))
# look up ascii char
if moreLevels:
gsval = gscale1[int((avg * 69) / 255)]
else:
gsval = gscale2[int((avg * 9) / 255)]
# append ascii char to string
aimg[j] += gsval
# return txt image
return aimg
def IMG2ASCII(outFile, imgFile):
scale = 0.5
cols = 300
moreLevels = 0
aimg = covertImageToAscii(imgFile, cols, scale, moreLevels)
f = open(outFile, 'a+')
# write to file
for row in aimg:
f.write(row + '\n')
f.close()
# Code taken from:
# https://www.geeksforgeeks.org/converting-image-ascii-image-python/