Update app.py
Browse files
app.py
CHANGED
@@ -1,15 +1,46 @@
|
|
1 |
-
# This Gradio app allows users to add text to an image with customizable text color, size, and position.
|
2 |
import gradio as gr
|
3 |
import numpy as np
|
4 |
import matplotlib.pyplot as plt
|
5 |
-
from
|
6 |
-
import io
|
7 |
|
8 |
# Define the function to add text to the image
|
9 |
def add_text_to_image(image, text, text_color, text_size, text_position_x, text_position_y, font):
|
10 |
-
# Convert the image to a
|
11 |
-
|
12 |
-
|
13 |
|
14 |
-
#
|
15 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import gradio as gr
|
2 |
import numpy as np
|
3 |
import matplotlib.pyplot as plt
|
4 |
+
from PIL import Image, ImageDraw, ImageFont
|
|
|
5 |
|
6 |
# Define the function to add text to the image
|
7 |
def add_text_to_image(image, text, text_color, text_size, text_position_x, text_position_y, font):
|
8 |
+
# Convert the image to a PIL Image object if it's not already
|
9 |
+
if isinstance(image, np.ndarray):
|
10 |
+
image = Image.fromarray(image.astype('uint8'), 'RGB')
|
11 |
|
12 |
+
# Create a drawing context
|
13 |
+
draw = ImageDraw.Draw(image)
|
14 |
+
|
15 |
+
# Load the font (you can specify a path to a .ttf file if needed)
|
16 |
+
try:
|
17 |
+
font = ImageFont.truetype(font, text_size)
|
18 |
+
except IOError:
|
19 |
+
# Fallback to a default font if the specified font is not available
|
20 |
+
font = ImageFont.load_default()
|
21 |
+
|
22 |
+
# Add the text to the image
|
23 |
+
draw.text((text_position_x, text_position_y), text, fill=text_color, font=font)
|
24 |
+
|
25 |
+
# Convert the image back to a numpy array for Gradio compatibility
|
26 |
+
return np.array(image)
|
27 |
+
|
28 |
+
# Gradio interface
|
29 |
+
iface = gr.Interface(
|
30 |
+
fn=add_text_to_image,
|
31 |
+
inputs=[
|
32 |
+
gr.Image(label="Input Image"),
|
33 |
+
gr.Textbox(label="Text"),
|
34 |
+
gr.ColorPicker(label="Text Color", value="#FFFFFF"),
|
35 |
+
gr.Slider(minimum=10, maximum=100, value=30, label="Text Size"),
|
36 |
+
gr.Slider(minimum=0, maximum=500, value=50, label="Text Position X"),
|
37 |
+
gr.Slider(minimum=0, maximum=500, value=50, label="Text Position Y"),
|
38 |
+
gr.Textbox(label="Font (e.g., 'arial.ttf')", value="arial.ttf")
|
39 |
+
],
|
40 |
+
outputs=gr.Image(label="Output Image"),
|
41 |
+
title="Add Text to Image",
|
42 |
+
description="Upload an image and add customizable text to it."
|
43 |
+
)
|
44 |
+
|
45 |
+
# Launch the Gradio app
|
46 |
+
iface.launch()
|