File size: 1,153 Bytes
0a1bfaf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import gradio as gr
from rembg import remove
from PIL import Image

def replace_bg(input_img, bg_img):
    # Convert input image to RGBA
    input_img = input_img.convert("RGBA")
    
    # Remove background
    no_bg_image = remove(input_img)
    
    # If no background image provided, return transparent background
    if bg_img is None:
        return no_bg_image
    
    # Resize background to match foreground size
    bg_img = bg_img.convert("RGBA").resize(no_bg_image.size)
    
    # Combine foreground and background
    result_image = Image.alpha_composite(bg_img, no_bg_image)
    return result_image

# Create the Gradio interface
demo = gr.Interface(
    fn=replace_bg,
    inputs=[
        gr.Image(type="pil", label="📷 Upload Your Image"),
        gr.Image(type="pil", label="🎨 Upload Background Image (Optional)")
    ],
    outputs=gr.Image(type="pil", label="✨ Final Result"),
    title="🎨 Professional Background Replacer",
    description="Upload any image and replace its background with a new one. Leave background empty for transparent result."
)

# Launch the application
if __name__ == "__main__":
    demo.launch()