Uploaded by 9u1992

code

advertisement
"""PIL is standard image library for python"""
import sys
from PIL import Image
def resize_image(image, new_width=250, new_height=250):
"""Resize image to (250xsth) or (sthx250) or (250x250)"""
width, height = image.size
aspect_ratio = width / height
if width > height:
new_height = int(new_width / aspect_ratio)
else:
new_width = int(new_height * aspect_ratio)
return image.resize((new_width, new_height))
if len(sys.argv) == 2:
im = Image.open(f'{sys.argv[1]}')
else:
im = Image.open("./fedora_128.png")
def convert_to_ascii(im):
"""This function converts image to ascii chracters"""
ascii_ = """$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\\|()1{}[]?-_+~<>i!lI;:\
,"^`'."""[::-1]
while True:
size = input(
"Enter size of image. Must be between 80 and 1000(Default: 100): ")
if size == "":
size = 100
size = int(size)
break
if(not size.isnumeric()):
continue
if(int(size) < 80 or int(size) > 1000):
print("Invalid size. Try again.")
continue
size = int(size)
break
im = resize_image(im, size, size)
rgb_im = im.convert('RGB')
print(rgb_im.width)
print(rgb_im.height)
temp = []
rgb_avg = []
for row in range(0, im.height):
temp = []
for col in range(0, im.width):
rgb_arr = rgb_im.getpixel((col, row))
rgb_avg_val = (rgb_arr[0] + rgb_arr[1] + rgb_arr[2]) // 3
temp.append(rgb_avg_val)
rgb_avg.append(temp)
for row in rgb_avg:
for pixel in row:
index = (pixel * len(ascii_)) // 256
print(ascii_[index], end="")
print("")
convert_to_ascii(im)
Download