File size: 2,405 Bytes
89928bd
7b78269
27309aa
7b78269
d9dd398
27309aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b78269
27309aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86b6923
 
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import gradio as gr
from rembg import remove
from PIL import Image
import io

# Preserve original resolution & optimize for high-res images
def process_image(image, background_type, bg_color, bg_image):
    try:
        input_image = Image.open(image).convert("RGBA")
        # Use rembg with bytes instead of loading into RAM completely
        buffered = io.BytesIO()
        input_image.save(buffered, format="PNG")
        result = remove(buffered.getvalue())
        output = Image.open(io.BytesIO(result)).convert("RGBA")

        if background_type == "Solid Color":
            bg = Image.new("RGBA", output.size, bg_color)
            bg.paste(output, (0, 0), output)
            return bg

        elif background_type == "Custom Image" and bg_image:
            custom_bg = Image.open(bg_image).convert("RGBA").resize(output.size)
            custom_bg.paste(output, (0, 0), output)
            return custom_bg

        else:
            return output
    except Exception as e:
        return f"โŒ Error: {str(e)}"

# For multiple images
def batch_process(images, background_type, bg_color, bg_image):
    return [process_image(img, background_type, bg_color, bg_image) for img in images]

# Gradio UI
with gr.Blocks() as demo:
    gr.Markdown("## ๐ŸŽฏ High-Resolution AI Background Remover with Custom Background")

    with gr.Row():
        images_input = gr.File(label="๐Ÿ“ค Upload High-Res Image(s)", file_types=["image"], file_count="multiple")

    with gr.Row():
        background_type = gr.Radio(
            ["Transparent", "Solid Color", "Custom Image"],
            label="Choose Background Type",
            value="Transparent"
        )
        bg_color = gr.ColorPicker(label="Solid Color", value="#ffffff", visible=False)
        bg_image = gr.File(label="Custom Background Image", file_types=["image"], visible=False)

    output_gallery = gr.Gallery(label="๐Ÿ–ผ๏ธ Output Images", columns=2, height=600)

    def toggle_visibility(bg_type):
        return (
            gr.update(visible=(bg_type == "Solid Color")),
            gr.update(visible=(bg_type == "Custom Image"))
        )

    background_type.change(toggle_visibility, inputs=background_type, outputs=[bg_color, bg_image])

    run_btn = gr.Button("๐Ÿš€ Start Processing")
    run_btn.click(fn=batch_process, inputs=[images_input, background_type, bg_color, bg_image], outputs=output_gallery)

demo.launch()