Lalawinnie commited on
Commit
696afb1
·
verified ·
1 Parent(s): fe6d403

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +29 -10
app.py CHANGED
@@ -1,18 +1,37 @@
1
  import gradio as gr
2
  from rembg import remove
 
3
 
4
- def process_image(input_img):
5
- """Processes an image by removing its background and resizing it."""
6
- img = remove(input_img)
7
- return img
 
 
 
 
 
 
8
 
9
  with gr.Blocks() as demo:
10
- gr.Interface(
11
- fn=process_image,
12
- inputs = [gr.Image(label="Input Image", interactive=True)],
13
- outputs = gr.Image(label="Processed Image"),
14
- examples=[["images/sample1.png"]],
15
- title="📸 Image Background Remover")
 
 
 
 
 
 
 
 
 
 
 
16
 
17
  if __name__ == "__main__":
18
  demo.launch()
 
 
1
  import gradio as gr
2
  from rembg import remove
3
+ from PIL import Image
4
 
5
+ def replace_background(foreground_img, background_img):
6
+ # 去背處理
7
+ fg = remove(foreground_img).convert("RGBA")
8
+
9
+ # 調整背景尺寸符合前景圖
10
+ bg = background_img.convert("RGBA").resize(fg.size)
11
+
12
+ # 合成圖片
13
+ combined = Image.alpha_composite(bg, fg)
14
+ return combined.convert("RGB")
15
 
16
  with gr.Blocks() as demo:
17
+ gr.Markdown("# 🖼️ 去背 + 替換風景背景")
18
+
19
+ with gr.Row():
20
+ input_img = gr.Image(label="上傳人物圖片", type="pil")
21
+ bg_img = gr.Image(label="上傳或選擇背景圖片", type="pil")
22
+
23
+ output_img = gr.Image(label="輸出圖片")
24
+
25
+ examples = [
26
+ ["images/person1.png", "images/beach.jpg"],
27
+ ["images/person2.png", "images/mountain.jpg"]
28
+ ]
29
+
30
+ btn = gr.Button("去背並替換背景")
31
+ btn.click(fn=replace_background, inputs=[input_img, bg_img], outputs=output_img)
32
+
33
+ gr.Examples(examples=examples, inputs=[input_img, bg_img])
34
 
35
  if __name__ == "__main__":
36
  demo.launch()
37
+