Spaces:
Runtime error
Runtime error
import gradio as gr | |
from PIL import Image | |
import numpy as np | |
# Define ASCII characters according to the intensity scale | |
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") # convert image to monochrome | |
pixels_to_chars = map_pixels_to_ascii_chars(image) | |
len_pixels_to_chars = len(pixels_to_chars) | |
# Convert the string of characters into a list of strings | |
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(image): | |
# Convert the NumPy array to a PIL Image and then to ASCII | |
image = Image.fromarray(image.astype('uint8'), 'RGB') | |
ascii_str = convert_image_to_ascii(image) | |
return ascii_str | |
description = """ | |
Image to ASCII Art Converter\n | |
Upload an image and convert it to ASCII art. Simply upload the image and | |
click the 'Submit' button to see the ASCII art. | |
""" | |
examples = ["example1.jpg"] # Make sure this example image exists in the same directory as this script | |
# Define the Gradio interface | |
interface = gr.Interface( | |
fn=image_to_ascii, | |
inputs=gr.Image(label="Upload Image"), | |
outputs=gr.Textbox(label="ASCII Art"), | |
examples=examples, | |
title="Image to ASCII Art", | |
description=description, | |
allow_flagging="never", | |
) | |
interface.launch() | |