File size: 1,948 Bytes
a505bd1
 
 
 
 
 
543442b
a505bd1
4e96c9f
a505bd1
 
 
4e96c9f
a505bd1
 
 
 
 
 
 
 
 
 
 
 
 
 
33a92a7
543442b
 
 
 
4e96c9f
a505bd1
 
4e96c9f
a505bd1
 
 
 
 
 
 
 
 
543442b
 
a505bd1
 
 
33a92a7
543442b
33a92a7
 
 
543442b
a505bd1
543442b
 
 
 
 
 
 
a505bd1
 
543442b
 
 
a505bd1
 
 
 
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
65
66
67
68
69
70
71
72
73
74
import gradio as gr
from gradio_imageslider import ImageSlider
from loadimg import load_img
from transformers import AutoModelForImageSegmentation
import torch
from torchvision import transforms
from io import BytesIO

# GPU 설정을 CPU로 변경
birefnet = AutoModelForImageSegmentation.from_pretrained(
    "ZhengPeng7/BiRefNet", trust_remote_code=True
)
birefnet.to("cpu")  # GPU -> CPU로 변경

transform_image = transforms.Compose(
    [
        transforms.Resize((1024, 1024)),
        transforms.ToTensor(),
        transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
    ]
)

def fn(image):
    im = load_img(image, output_type="pil")
    im = im.convert("RGB")
    origin = im.copy()
    processed_image = process(im)
    # Convert processed image to JPEG for download
    buffered = BytesIO()
    processed_image.convert("RGB").save(buffered, format="JPEG")
    buffered.seek(0)
    return processed_image, buffered

def process(image):
    image_size = image.size
    input_images = transform_image(image).unsqueeze(0).to("cpu")  # GPU -> CPU로 변경
    # Prediction
    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)
    image.putalpha(mask)
    return image

slider = ImageSlider(label="Processed Image", type="pil")
download_output = gr.File(label="Download JPG File")

image_upload = gr.Image(label="Upload an image")

# 새로운 샘플 이미지 (예: 동일 디렉토리에 위치)
sample_images = [
    ["1.png"],
    ["2.jpg"],
    ["3.png"]
]

tab = gr.Interface(
    fn=fn, 
    inputs=image_upload, 
    outputs=[slider, download_output], 
    examples=sample_images, 
    api_name="image"
)

demo = gr.TabbedInterface(
    [tab], 
    ["Image Upload"], 
    title="Background Removal Tool"
)

if __name__ == "__main__":
    demo.launch(show_error=True)