File size: 1,881 Bytes
536eec3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3367c3f
 
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
import gradio as gr
from PIL import Image

def change_background_to_white(image):
    try:
        # ์ด๋ฏธ์ง€๋ฅผ RGBA๋กœ ๋ณ€ํ™˜ํ•˜์—ฌ ์•ŒํŒŒ ์ฑ„๋„์„ ํ™•๋ณด
        rgba_image = image.convert('RGBA')
    except Exception as e:
        return None, f"์ด๋ฏธ์ง€ ์ฒ˜๋ฆฌ ์ค‘ ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค: {str(e)}"

    # ๊ณ ํ•ด์ƒ๋„ ์ด๋ฏธ์ง€์— ๋Œ€ํ•œ ๊ฒฝ๊ณ 
    if rgba_image.width > 3000 or rgba_image.height > 3000:
        return None, "๋งค์šฐ ํฐ ์ด๋ฏธ์ง€๋Š” ์ฒ˜๋ฆฌ ์‹œ๊ฐ„์ด ๊ธธ์–ด์งˆ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ๊ฐ€๋Šฅํ•˜๋‹ค๋ฉด ์ด๋ฏธ์ง€ ํฌ๊ธฐ๋ฅผ ์ค„์—ฌ์ฃผ์„ธ์š”."

    # ์ƒˆ๋กœ์šด ํฐ์ƒ‰ ๋ฐฐ๊ฒฝ ์ด๋ฏธ์ง€ ์ƒ์„ฑ
    white_bg = Image.new('RGBA', rgba_image.size, (255, 255, 255, 255))
    
    # ์›๋ณธ ์ด๋ฏธ์ง€์˜ ํ”ฝ์…€ ๋ฐ์ดํ„ฐ๋ฅผ ๊ฐ€์ ธ์˜ด
    pixels = rgba_image.getdata()
    
    # ์ƒˆ๋กœ์šด ํ”ฝ์…€ ๋ฐ์ดํ„ฐ ๋ฆฌ์ŠคํŠธ ์ƒ์„ฑ
    new_pixels = []
    
    # ๋ชจ๋“  ํ”ฝ์…€์„ ์ˆœํšŒํ•˜๋ฉฐ ํˆฌ๋ช…ํ•œ ๋ถ€๋ถ„์„ ํฐ์ƒ‰์œผ๋กœ ๋ณ€๊ฒฝ
    for pixel in pixels:
        if pixel[3] < 255:
            new_pixels.append((255, 255, 255, 255))  # ํˆฌ๋ช…ํ•œ ๋ถ€๋ถ„์„ ํฐ์ƒ‰์œผ๋กœ ๋ณ€๊ฒฝ
        else:
            new_pixels.append(pixel)
    
    # ๋ณ€๊ฒฝ๋œ ํ”ฝ์…€ ๋ฐ์ดํ„ฐ๋กœ ์ด๋ฏธ์ง€๋ฅผ ์—…๋ฐ์ดํŠธ
    white_bg.putdata(new_pixels)
    
    # ์ตœ์ข… ์ด๋ฏธ์ง€๋ฅผ RGB๋กœ ๋ณ€ํ™˜ํ•˜์—ฌ ๋ฐ˜ํ™˜
    final_image = white_bg.convert('RGB')
    
    return final_image, "์ด๋ฏธ์ง€ ์ฒ˜๋ฆฌ๊ฐ€ ์™„๋ฃŒ๋˜์—ˆ์Šต๋‹ˆ๋‹ค."

with gr.Blocks() as app:
    gr.Markdown("## ์ด๋ฏธ์ง€์˜ ๋ฐฐ๊ฒฝ์ƒ‰์„ ํฐ์ƒ‰์œผ๋กœ ๋ณ€๊ฒฝํ•˜๊ธฐ")
    with gr.Row():
        input_image = gr.Image(type="pil", label="์ด๋ฏธ์ง€ ์—…๋กœ๋“œ")
        output_image = gr.Image(label="๋ฐฐ๊ฒฝ์ƒ‰ ๋ณ€๊ฒฝ๋œ ์ด๋ฏธ์ง€")
        output_text = gr.Textbox(label="์ฒ˜๋ฆฌ ๊ฒฐ๊ณผ")
    input_image.change(fn=change_background_to_white, inputs=input_image, outputs=[output_image, output_text])

if __name__ == "__main__":
    app.launch()