Spaces:
Sleeping
Sleeping
import gradio as gr | |
from rembg import remove | |
from PIL import Image | |
import logging | |
# ๋ก๊น ์ค์ | |
logging.basicConfig(level=logging.INFO) | |
def remove_background(input_image): | |
""" | |
์ ๋ ฅ๋ ์ด๋ฏธ์ง์์ ๋ฐฐ๊ฒฝ์ ์ ๊ฑฐํ๋ ํจ์ | |
Parameters: | |
input_image (PIL.Image ๋๋ str): ์ ๋ก๋๋ ์ด๋ฏธ์ง ํ์ผ์ ๊ฐ์ฒด ๋๋ ํ์ผ ๊ฒฝ๋ก | |
Returns: | |
PIL.Image ๋๋ str: ๋ฐฐ๊ฒฝ์ด ์ ๊ฑฐ๋ ์ด๋ฏธ์ง ๋๋ ์๋ฌ ๋ฉ์์ง | |
""" | |
try: | |
logging.info("Processing image.") | |
if isinstance(input_image, str): | |
input_img = Image.open(input_image) | |
else: | |
input_img = input_image | |
# ๋ฐฐ๊ฒฝ ์ ๊ฑฐ | |
output_img = remove(input_img) | |
logging.info("Background removed successfully.") | |
# ํฌ๋ช ๋๋ฅผ ์ ์งํ๊ธฐ ์ํด PNG ํ์์ผ๋ก ๋ณํ | |
return output_img.convert("RGBA") | |
except Exception as e: | |
logging.error(f"Error removing background: {e}") | |
return f"์๋ฌ๊ฐ ๋ฐ์ํ์ต๋๋ค: {str(e)}" | |
def clear_images(): | |
"""์ ๋ ฅ ์ด๋ฏธ์ง์ ์ถ๋ ฅ ์ด๋ฏธ์ง๋ฅผ ๋ชจ๋ ์ด๊ธฐํํ๋ ํจ์""" | |
return None, None | |
# Gradio ์ธํฐํ์ด์ค ๊ตฌ์ฑ | |
with gr.Blocks(css=""" | |
#btn-remove { | |
background-color: #4CAF50; /* ์ด๋ก์ */ | |
color: white; | |
} | |
#btn-reset { | |
background-color: #f44336; /* ๋นจ๊ฐ์ */ | |
color: white; | |
} | |
""") as demo: | |
gr.Markdown("# ์ด๋ฏธ์ง ๋ฐฐ๊ฒฝ ์ ๊ฑฐ๊ธฐ") | |
gr.Markdown("์ด๋ฏธ์ง๋ฅผ ์ ๋ก๋ํ๋ฉด ๋ฐฐ๊ฒฝ์ด ์๋์ผ๋ก ์ ๊ฑฐ๋ฉ๋๋ค.") | |
with gr.Row(): | |
input_image = gr.Image( | |
type="pil", | |
label="์ ๋ ฅ ์ด๋ฏธ์ง", | |
interactive=True # ์ฌ์ฉ์๊ฐ ์ด๋ฏธ์ง๋ฅผ ์ ๋ก๋ํ ์ ์๋๋ก ์ค์ | |
) | |
output_image = gr.Image( | |
type="pil", | |
label="๋ฐฐ๊ฒฝ ์ ๊ฑฐ๋ ์ด๋ฏธ์ง", | |
interactive=False # ์ถ๋ ฅ ์ด๋ฏธ์ง๋ ์ํธ์์ฉ ๋ถ๊ฐ๋ฅ | |
) | |
# ๋ฐฐ๊ฒฝ ์ ๊ฑฐ ๋ฒํผ | |
with gr.Row(): | |
btn_remove = gr.Button("๋ฐฐ๊ฒฝ ์ ๊ฑฐ", elem_id="btn-remove") # elem_id๋ก ๋ฒํผ ์คํ์ผ ์ง์ | |
btn_remove.click(fn=remove_background, inputs=input_image, outputs=output_image) | |
# ์ด๊ธฐํ ๋ฒํผ ์ถ๊ฐ | |
btn_reset = gr.Button("์ด๊ธฐํ", elem_id="btn-reset") # elem_id๋ก ๋ฒํผ ์คํ์ผ ์ง์ | |
btn_reset.click(fn=clear_images, inputs=None, outputs=[input_image, output_image]) | |
# ์์ ์ด๋ฏธ์ง | |
gr.Examples( | |
examples=[ | |
["./example1.jpg"], | |
["./example2.jpg"] | |
], | |
inputs=input_image, | |
label="์์ ์ด๋ฏธ์ง" | |
) | |
if __name__ == "__main__": | |
demo.launch() | |