Spaces:
Runtime error
Runtime error
File size: 2,077 Bytes
5779c39 914234b 5779c39 914234b 5779c39 914234b 5779c39 914234b 5779c39 914234b 5779c39 914234b 5779c39 914234b 4900a23 735eb41 914234b 5779c39 914234b 5779c39 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
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 = ["example.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()
|