Sure! Let's enhance your Gradio application to function as an image editor that allows users to remove the background of an image and add customized text overlays. We'll incorporate user options for selecting text content, font, size, color, and more. Additionally, we'll preload a set of fonts and provide a dropdown for easy selection.
Below is the complete code with detailed explanations:
import gradio as gr
from transformers import AutoModelForImageSegmentation
import torch
from torchvision import transforms
from PIL import Image, ImageDraw, ImageFont
import os
# Set the precision for float32 matrix multiplications
torch.set_float32_matmul_precision("highest")
# Load the pre-trained BiRefNet model for image segmentation (background removal)
birefnet = AutoModelForImageSegmentation.from_pretrained(
"ZhengPeng7/BiRefNet", trust_remote_code=True
)
birefnet.to("cuda")
# Define image transformations
transform_image = transforms.Compose(
[
transforms.Resize((1024, 1024)),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
]
)
# Path to the fonts directory
FONTS_DIR = "fonts"
# Ensure the fonts directory exists
os.makedirs(FONTS_DIR, exist_ok=True)
# Pre-download some fonts and save them in the fonts directory
# For demonstration, we'll assume you have these font files in your working directory
# Alternatively, you can download fonts from online sources and save them accordingly
PRE_DOWNLOADED_FONTS = {
"Arial": "arial.ttf",
"Helvetica": "helvetica.ttf",
"Times New Roman": "times.ttf",
"Courier New": "courier.ttf",
"Verdana": "verdana.ttf",
}
# Load the font paths
font_paths = {}
for font_name, font_file in PRE_DOWNLOADED_FONTS.items():
font_path = os.path.join(FONTS_DIR, font_file)
if not os.path.exists(font_path):
# If the font file does not exist, you need to ensure it's available.
# You can download free fonts from Google Fonts or other repositories.
# Here, we'll skip missing fonts for safety.
print(f"Font file {font_file} not found in {FONTS_DIR}. Skipping {font_name}.")
continue
font_paths[font_name] = font_path
# Define the processing function with GPU support
@gr.checkpoint
def process(image, text, font_name, font_size, text_color, position):
"""
Processes the image by removing its background and adding customized text.
Parameters:
- image (PIL.Image): Input image.
- text (str): Text to add.
- font_name (str): Selected font name.
- font_size (int): Size of the text.
- text_color (str): Color of the text (e.g., "#FFFFFF").
- position (str): Position of the text on the image.
Returns:
- PIL.Image: The final image with background removed and text added.
"""
# Store original image size
image_size = image.size
# Apply background removal
input_images = transform_image(image).unsqueeze(0).to("cuda")
with torch.no_grad():
preds = birefnet(input_images)[-1].sigmoid().cpu()
pred = preds[0].squeeze()
pred_pil = transforms.ToPILImage()(pred)
mask = pred_pil.resize(image_size).convert("L") # Grayscale mask
# Apply mask to remove background
image = image.convert("RGBA")
image.putalpha(mask)
# Create an image for the text
text_img = Image.new("RGBA", image_size, (255, 255, 255, 0))
draw = ImageDraw.Draw(text_img)
# Load the selected font
if font_name in font_paths:
font_path = font_paths[font_name]
try:
font = ImageFont.truetype(font_path, font_size)
except IOError:
font = ImageFont.load_default()
print(f"Failed to load {font_name}. Using default font.")
else:
font = ImageFont.load_default()
print(f"{font_name} not found. Using default font.")
# Calculate text size
text_width, text_height = draw.textsize(text, font=font)
# Determine text position
if position == "Top-Left":
pos = (10, 10)
elif position == "Top-Center":
pos = ((image_size[0] - text_width) // 2, 10)
elif position == "Top-Right":
pos = (image_size[0] - text_width - 10, 10)
elif position == "Center":
pos = ((image_size[0] - text_width) // 2, (image_size[1] - text_height) // 2)
elif position == "Bottom-Left":
pos = (10, image_size[1] - text_height - 10)
elif position == "Bottom-Center":
pos = ((image_size[0] - text_width) // 2, image_size[1] - text_height - 10)
elif position == "Bottom-Right":
pos = (image_size[0] - text_width - 10, image_size[1] - text_height - 10)
else:
pos = (10, 10) # Default position
# Add text to the text image
draw.text(pos, text, font=font, fill=text_color)
# Combine the original image with the text
combined = Image.alpha_composite(image, text_img)
return combined
# Define Gradio interface components
with gr.Blocks() as demo:
gr.Markdown("# Image Editor: Background Remover & Text Adder")
gr.Markdown("Upload an image, remove its background, and add customized text overlays.")
with gr.Row():
with gr.Column():
input_image = gr.Image(label="Upload Image", type="pil")
text_input = gr.Textbox(label="Text to Add", placeholder="Enter your text here...")
font_dropdown = gr.Dropdown(
label="Select Font",
choices=list(font_paths.keys()),
value=list(font_paths.keys())[0] if font_paths else "Arial",
)
font_size_slider = gr.Slider(
label="Font Size",
minimum=10,
maximum=100,
step=1,
value=40,
)
color_picker = gr.ColorPicker(
label="Text Color",
value="#FFFFFF", # Default to white
)
position_dropdown = gr.Dropdown(
label="Text Position",
choices=[
"Top-Left",
"Top-Center",
"Top-Right",
"Center",
"Bottom-Left",
"Bottom-Center",
"Bottom-Right",
],
value="Bottom-Center",
)
submit_button = gr.Button("Generate Image")
with gr.Column():
output_image = gr.Image(label="Output Image")
# Add example image (ensure 'butterfly.jpg' is available in your working directory)
demo.load(
lambda: None,
None,
None,
)
demo.launchable = True
# Define the action when the button is clicked
submit_button.click(
fn=process,
inputs=[
input_image,
text_input,
font_dropdown,
font_size_slider,
color_picker,
position_dropdown,
],
outputs=output_image,
)
if __name__ == "__main__":
demo.launch(show_error=True)
Explanation of the Enhancements
-
Font Management:
- Pre-Downloaded Fonts: The code assumes that you have five font files (
arial.ttf, helvetica.ttf, times.ttf, courier.ttf, verdana.ttf) placed inside a fonts directory. Ensure these files are present. If not, you can download free fonts from sources like Google Fonts and place them in the fonts folder.
- Dropdown for Fonts: Users can select their desired font from a dropdown menu populated with the available fonts.
-
Text Customization Options:
- Text Input: Users can input the text they want to add to the image.
- Font Size Slider: A slider allows users to choose the size of the text.
- Color Picker: Users can pick the color of the text using a color picker.
- Position Dropdown: Users can select where the text will appear on the image (e.g., Top-Left, Center, Bottom-Right).
-
Image Processing Function (process):
- Background Removal: Utilizes the pre-trained BiRefNet model to remove the image background.
- Text Overlay:
- Creates a transparent layer for the text.
- Calculates the position based on user selection.
- Draws the text with the chosen font, size, and color.
- Combines the text layer with the background-removed image.
-
Gradio Interface Layout:
- Organized using
gr.Blocks for a clean and responsive layout.
- Inputs are placed in one column, and the output image is displayed in another for better user experience.
- An example image (
butterfly.jpg) is referenced; ensure this image is available or replace it with your own examples.
-
Error Handling:
- If a selected font fails to load, the code defaults to the system's default font and prints a warning message.
- Ensure all font files are correctly placed to prevent fallback scenarios.
-
Additional Features (Creativity):
- Multiple positions allow users to place text creatively on various parts of the image.
Setup Instructions
-
Install Required Libraries:
Ensure you have all necessary Python libraries installed. You can install them using pip:
pip install gradio transformers torch torchvision pillow
-
Prepare Font Files:
- Create a directory named
fonts in your working directory.
- Download the desired
.ttf font files and place them inside the fonts folder.
- Update the
PRE_DOWNLOADED_FONTS dictionary in the code with the correct font file names.
-
Place an Example Image:
- Ensure you have an example image named
butterfly.jpg in your working directory or update the examples parameter with your image paths.
-
Run the Application:
Execute the script. A Gradio interface will launch, allowing you to upload images, customize text, and generate the edited images.
python your_script_name.py
Potential Enhancements
- Position Sliders: Instead of predefined positions, allow users to drag and drop text to any location on the image.
- Font Styles: Offer options like bold, italic, or underline.
- Multiple Text Layers: Permit adding multiple text entries with different styles.
- Image Filters: Provide additional image editing features like brightness, contrast adjustments, or filters.
- Download Options: Allow users to download the edited image in different formats.
Feel free to customize and expand upon this foundation to create a more feature-rich image editor tailored to your needs!