Spaces:
Runtime error
Runtime error
import gradio as gr | |
from PIL import Image | |
import numpy as np | |
ASCII_CHARS = ["@", "#", "S", "%", "?", "*", "+", ";", ":", ",", "."] | |
def scale_image(image, new_width=100): | |
"""Resizes an image preserving the aspect ratio.""" | |
(original_width, original_height) = image.size | |
aspect_ratio = original_height/float(original_width) | |
new_height = int(aspect_ratio * new_width) | |
new_image = image.resize((new_width, new_height)) | |
return new_image | |
def map_pixels_to_ascii_chars(image, range_width=25): | |
"""Maps each pixel to an ascii char based on intensity.""" | |
pixels_in_image = list(image.getdata()) | |
pixels_to_chars = [ASCII_CHARS[pixel_value//range_width] for pixel_value in pixels_in_image] | |
return "".join(pixels_to_chars) | |
def convert_image_to_ascii(image, new_width=100): | |
image = scale_image(image) | |
image = image.convert("L") | |
pixels_to_chars = map_pixels_to_ascii_chars(image) | |
len_pixels_to_chars = len(pixels_to_chars) | |
ascii_image = [pixels_to_chars[index: index + new_width] for index in range(0, len_pixels_to_chars, new_width)] | |
return "\n".join(ascii_image) | |
def image_to_ascii(file): | |
image = Image.open(file.name) | |
ascii_str = convert_image_to_ascii(image) | |
return ascii_str | |
description = "Image to ASCII Art Converter\nUpload an image and convert it to ASCII art. Click the 'Submit' button after uploading." | |
interface = gr.Interface( | |
fn=image_to_ascii, | |
inputs=gr.inputs.Image(type="file", label="Upload Image"), | |
outputs=gr.outputs.Textbox(label="ASCII Art"), | |
examples=["example1.jpg", "example2.jpg"], | |
title="Image to ASCII Art", | |
description=description, | |
) | |
interface.launch() | |