make a script that turns images into ascii characters with color in python

main.py
from PIL import Image
import sys

# Define ASCII characters to represent pixel intensity
ASCII_CHARS = ('#', '?', '%', '.', 'S', '+', '.', '*', ':', ',', '@')

# Convert RGB to grayscale
def rgb_to_gray(rgb):
    return int(rgb[0]*0.299 + rgb[1]*0.587 + rgb[2]*0.114)

# Resize image to maintain aspect ratio
def resize_image(image, new_width=100):
    (old_width, old_height) = image.size
    aspect_ratio = old_height/old_width
    new_height = int(aspect_ratio * new_width)
    new_image = image.resize((new_width, new_height))
    return new_image

# Convert image to ASCII
def image_to_ascii(image_path):
    try:
        image = Image.open(image_path)
    except Exception as e:
        print(e)
        return

    image = resize_image(image)
    grayscale_image = image.convert('L')
    pixels = grayscale_image.getdata()
    characters = [ASCII_CHARS[pixel//25] for pixel in pixels]
    ascii_image = ''.join(characters)

    color_image = image.convert('P', palette=Image.ADAPTIVE, colors=16).convert('RGB')
    
    return ascii_image, color_image

# Display ASCII image with color
def display_image(ascii_image, color_image):
    for i in range(0, len(ascii_image), new_width):
        print(ascii_image[i:i+new_width])

    color_image.show()

if __name__ == '__main__':
    image_file = 'image.jpg'  # Replace 'image.jpg' with the path to your image file
    new_width = 100  # Change to adjust width of ASCII image
    ascii_image, color_image = image_to_ascii(image_file)
    display_image(ascii_image, color_image)
1532 chars
49 lines

gistlibby LogSnag