Code for converting images to ascii:
import sys
from PIL import Image
import numpy as np
import os
ASCII_CHARS = "@%#*+=-:. "
def resize_image(image, new_width=100): width, height = image.size aspect_ratio = height / width new_height = int(aspect_ratio * new_width * 0.55) return image.resize((new_width, new_height))
def image_to_grayscale(image): return image.convert("L")
def enhance_dark_subject(image, threshold=150): img_array = np.array(image) img_array = np.where(img_array < threshold, img_array, 255) return Image.fromarray(img_array)
def pixels_to_ascii(image): pixels = np.array(image) ascii_str = ""
for row in pixels:
for pixel in row:
index = int(pixel) * (len(ASCII_CHARS) - 1) // 255
ascii_str += ASCII_CHARS[index]
ascii_str += "\n"
return ascii_str
def image_to_ascii(path, width=100): image = Image.open(path) image = resize_image(image, width) image = image_to_grayscale(image) image = enhance_dark_subject(image) return pixels_to_ascii(image)
if name == "main":
if len(sys.argv) < 2:
print("Usage: python ascii.py
image_path = sys.argv[1]
width = int(sys.argv[2]) if len(sys.argv) > 2 else 120
output_file = sys.argv[3] if len(sys.argv) > 3 else "output.txt"
ascii_art = image_to_ascii(image_path, width)
with open(output_file, "w", encoding="utf-8") as f:
f.write(ascii_art)
print(f"ASCII art saved to: {os.path.abspath(output_file)}")