sushann222's picture
Update app.py
05509cb verified
Raw History Blame Contribute Delete
2.12 kB
from PIL import Image
import gradio as gr
import numpy as np
from rembg import remove
import openai
import requests
from io import BytesIO
# OpenAI API key setup
openai.api_key = 'your_openai_api_key'
def generate_background(prompt):
try:
response = openai.Image.create(
prompt=prompt,
n=1,
size="512x512",
response_format="url"
)
image_url = response['data'][0]['url']
background = Image.open(requests.get(image_url, stream=True).raw)
background = background.convert("RGBA")
return background
except Exception as e:
print(f"Error generating background: {e}")
return None
def overlay_images(image1, prompt):
try:
img1_no_bg = remove(image1)
img1 = Image.fromarray(img1_no_bg).convert("RGBA")
# Generate background from prompt
img2 = generate_background(prompt)
if img2 is None:
return np.array(Image.new('RGB', (512, 512), color = 'red'))
# Resize the foreground image to match the background size
img1 = img1.resize(img2.size, Image.ANTIALIAS)
combined = Image.new("RGBA", img2.size)
combined = Image.alpha_composite(combined, img2)
combined = Image.alpha_composite(combined, img1)
# Convert to supported format (e.g., PNG) and ensure proper display
combined = combined.convert("RGB")
return np.array(combined)
except Exception as e:
print(f"Error processing images: {e}")
return np.array(Image.new('RGB', (512, 512), color = 'red'))
img2img = gr.Interface(
fn=overlay_images,
inputs=[
gr.Image(type="numpy", label="Upload Image 1 (Foreground)"),
gr.Textbox(lines=1, placeholder="Enter a prompt for the background", label="Background Prompt")
],
outputs="image",
title="Overlay Images with AI Generated Background",
description="Upload an image and enter a prompt to generate a background. The first image will have its background removed and will be placed onto the generated background."
)
img2img.launch()