|
import gradio as gr |
|
import numpy as np |
|
from PIL import Image, ImageDraw, ImageFont |
|
|
|
|
|
COLOR_MAP = { |
|
"white": (255, 255, 255), |
|
"black": (0, 0, 0), |
|
"red": (255, 0, 0), |
|
"green": (0, 255, 0), |
|
"blue": (0, 0, 255), |
|
"yellow": (255, 255, 0), |
|
"cyan": (0, 255, 255), |
|
"magenta": (255, 0, 255), |
|
} |
|
|
|
|
|
def add_text_to_image(image, text, text_color, text_size, text_position_x, text_position_y, font): |
|
|
|
if isinstance(image, np.ndarray): |
|
image = Image.fromarray(image.astype('uint8'), 'RGB') |
|
|
|
|
|
draw = ImageDraw.Draw(image) |
|
|
|
|
|
try: |
|
font = ImageFont.truetype(font, text_size) |
|
except IOError: |
|
|
|
font = ImageFont.load_default() |
|
|
|
|
|
color_rgb = COLOR_MAP.get(text_color, (255, 255, 255)) |
|
|
|
|
|
draw.text((text_position_x, text_position_y), text, fill=color_rgb, font=font) |
|
|
|
|
|
return np.array(image) |
|
|
|
|
|
iface = gr.Interface( |
|
fn=add_text_to_image, |
|
inputs=[ |
|
gr.Image(label="Input Image"), |
|
gr.Textbox(label="Text"), |
|
gr.Dropdown(label="Text Color", choices=list(COLOR_MAP.keys()), value="white"), |
|
gr.Slider(minimum=10, maximum=100, value=30, label="Text Size"), |
|
gr.Slider(minimum=0, maximum=500, value=50, label="Text Position X"), |
|
gr.Slider(minimum=0, maximum=500, value=50, label="Text Position Y"), |
|
gr.Textbox(label="Font (e.g., 'arial.ttf')", value="arial.ttf") |
|
], |
|
outputs=gr.Image(label="Output Image"), |
|
title="Add Text to Image", |
|
description="Upload an image and add customizable text to it." |
|
) |
|
|
|
|
|
iface.launch() |