python image to terminal ascii

Solutions on MaxInterview for python image to terminal ascii by the best coders in the world

showing results for - "python image to terminal ascii"
Alessio
09 Sep 2016
1import sys
2from PIL import Image
3
4# pass the image as command line argument
5image_path = sys.argv[1]
6img = Image.open(image_path)
7
8# resize the image
9width, height = img.size
10aspect_ratio = height/width
11new_width = 120
12new_height = aspect_ratio * new_width * 0.55
13img = img.resize((new_width, int(new_height)))
14# new size of image
15# print(img.size)
16
17# convert image to greyscale format
18img = img.convert('L')
19
20pixels = img.getdata()
21
22# replace each pixel with a character from array
23chars = ["B","S","#","&","@","$","%","*","!",":","."]
24new_pixels = [chars[pixel//25] for pixel in pixels]
25new_pixels = ''.join(new_pixels)
26
27# split string of chars into multiple strings of length equal to new width and create a list
28new_pixels_count = len(new_pixels)
29ascii_image = [new_pixels[index:index + new_width] for index in range(0, new_pixels_count, new_width)]
30ascii_image = "\n".join(ascii_image)
31print(ascii_image)
32
33# write to a text file.
34with open("ascii_image.txt", "w") as f:
35 f.write(ascii_image)
36