-
Notifications
You must be signed in to change notification settings - Fork 0
/
image_to_ascii.py
56 lines (45 loc) · 1.46 KB
/
image_to_ascii.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
import sys
from PIL import Image, ImageDraw, ImageFont
import math
# chars = "#Wo- "[::-1]
if int(sys.argv[2]) == 0: # Type-0
chars = " \":;Il!i+?][}{1)(|\\/tfjrxnuvczXYUJCLQ0OZmwqpdbkhao#MW&8%B@$"
else: # Type-1
chars = " ░▒▓█"
charArray = list(chars)
charLength = len(charArray)
interval = charLength / 256
scaleFactor = 1
oneCharWidth = 5
oneCharHeight = 8
fileName = sys.argv[1]
# gets character based on luminosity of pixels
def getChar(inputInt):
return charArray[math.floor(inputInt * interval)]
# text_file = open("Output.txt", "w")
# input image
im = Image.open(fileName)
# importing font
fnt = ImageFont.truetype('lucon.ttf', 7)
width, height = im.size
# resize image
im = im.resize((320, int(scaleFactor * height * (320 / width) * (oneCharWidth / oneCharHeight))),
Image.Resampling.NEAREST)
width, height = im.size
pix = im.load()
outputImage = Image.new('RGB', (oneCharWidth * width, oneCharHeight * height), color=(0, 0, 0))
d = ImageDraw.Draw(outputImage)
cf = 10
# iterating over each pixel
for i in range(height):
for j in range(width):
r, g, b = pix[j, i]
r = min(r + cf, 255)
g = min(g + cf + 5, 255)
b = min(b + cf + 5, 255)
h = int(0.2126 * r + 0.7152 * g + 0.0722 * b)
# replace pixel with text of similar color
d.text((j * oneCharWidth, i * oneCharHeight), getChar(h), font=fnt, fill=(r, g, b))
# text_file.write('\n')
# save image
outputImage.save('output.png')