imagetoascii/ascii.py

46 lines
2.1 KiB
Python
Raw Permalink Normal View History

2022-10-28 01:42:48 +02:00
from PIL import Image
import sys
if not sys.argv[1:]:
print("ERROR: No input given")
sys.exit(1)
# list of characters sorted from bright to dark
characters = ['$','@','B','%','8','&','W','M','#','*','o','a','h','k','b','d','p','q','w','m','Z','O','0','Q','L','C','J','U','Y','X','z','c','v','u','n','x','r','j','f','t','/','\\','|','(',')','1','{','}','[',']','?','-','_','+','~','<','>','i','!','l','I',';',':',',','"','^','`','.',' ']
def map(in_min, in_max,out_min,out_max,x):
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min
def brightness(r,b,g):
avg= (r+b+g)/3
return avg
# print("Please enter Image Name if it if in the same Folder as the Python File, otherwise specify the path to the file!")
# imgpath=input()
image = Image.open(sys.argv[1:][0])
imagewith, imageheight = image.size #get size of image
print("Please type the desired resolution on the x(width) Axis!(e.g. 150)")
resolution = int(input())
# values to scale down the image
divisor = (int(imagewith/resolution))+1
outwith = int(imagewith/divisor)
outheight = int(imageheight/divisor)
# create an empty 2D Matrix to store the ASCII characters im
matrix = [[' ' for x in range(outheight)] for x in range(outwith)]
#write the right characters in the matrix
for i in range(0,outheight*divisor,divisor): #do steps as big as the divisor, to skip as much pixels as needed for scaling
for j in range(0,outwith*divisor,divisor): #only until outsize*devisor, because that we mapped devisor input pixels to one output pixel and because of rounding we cannot map i.e. 38 when divisor is 5 and can only go up to outsize*divisor
xy= j, i
colors = image.getpixel(xy)
charnum = int(map(0,255,len(characters)-1,0,brightness(colors[0],colors[1],colors[2])))
matrix[int(j/divisor)][int(i/divisor)]=characters[charnum]
#print the matrix
for i in range(0,outheight,2):
for j in range(outwith):
print(matrix[j][i], end = "") #print without a new line at the end
print() #new line