Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from PIL import Image
|
3 |
+
import numpy as np
|
4 |
+
|
5 |
+
ASCII_CHARS = ["@", "#", "S", "%", "?", "*", "+", ";", ":", ",", "."]
|
6 |
+
|
7 |
+
def scale_image(image, new_width=100):
|
8 |
+
"""Resizes an image preserving the aspect ratio."""
|
9 |
+
(original_width, original_height) = image.size
|
10 |
+
aspect_ratio = original_height/float(original_width)
|
11 |
+
new_height = int(aspect_ratio * new_width)
|
12 |
+
new_image = image.resize((new_width, new_height))
|
13 |
+
return new_image
|
14 |
+
|
15 |
+
def map_pixels_to_ascii_chars(image, range_width=25):
|
16 |
+
"""Maps each pixel to an ascii char based on intensity."""
|
17 |
+
pixels_in_image = list(image.getdata())
|
18 |
+
pixels_to_chars = [ASCII_CHARS[pixel_value//range_width] for pixel_value in pixels_in_image]
|
19 |
+
return "".join(pixels_to_chars)
|
20 |
+
|
21 |
+
def convert_image_to_ascii(image, new_width=100):
|
22 |
+
image = scale_image(image)
|
23 |
+
image = image.convert("L")
|
24 |
+
|
25 |
+
pixels_to_chars = map_pixels_to_ascii_chars(image)
|
26 |
+
len_pixels_to_chars = len(pixels_to_chars)
|
27 |
+
|
28 |
+
ascii_image = [pixels_to_chars[index: index + new_width] for index in range(0, len_pixels_to_chars, new_width)]
|
29 |
+
return "\n".join(ascii_image)
|
30 |
+
|
31 |
+
def image_to_ascii(file):
|
32 |
+
image = Image.open(file.name)
|
33 |
+
ascii_str = convert_image_to_ascii(image)
|
34 |
+
return ascii_str
|
35 |
+
|
36 |
+
description = "Image to ASCII Art Converter\nUpload an image and convert it to ASCII art. Click the 'Submit' button after uploading."
|
37 |
+
interface = gr.Interface(
|
38 |
+
fn=image_to_ascii,
|
39 |
+
inputs=gr.inputs.Image(type="file", label="Upload Image"),
|
40 |
+
outputs=gr.outputs.Textbox(label="ASCII Art"),
|
41 |
+
examples=["example1.jpg", "example2.jpg"],
|
42 |
+
title="Image to ASCII Art",
|
43 |
+
description=description,
|
44 |
+
)
|
45 |
+
|
46 |
+
interface.launch()
|