import gradio as gr from transformers import pipeline import torch import numpy as np from PIL import Image import io def remove_background(input_image): try: # Initialize the pipeline with correct parameters segmentor = pipeline( task="image-segmentation", model="briaai/RMBG-1.4", trust_remote_code=True ) # Convert input to PIL Image if it's not already if not isinstance(input_image, Image.Image): input_image = Image.fromarray(input_image) # Process the image result = segmentor(input_image, return_mask=True) # Create transparent background image output_image = Image.new('RGBA', input_image.size, (0, 0, 0, 0)) output_image.paste(input_image, mask=result) return output_image except Exception as e: raise gr.Error(f"Error processing image: {str(e)}") # Create Gradio interface with gr.Blocks(theme=gr.themes.Default()) as demo: gr.HTML( """

AI Background Remover

Remove backgrounds instantly using RMBG V1.4 model

""" ) with gr.Row(): with gr.Column(): input_image = gr.Image( label="Upload Image", type="pil", sources=["upload", "clipboard"] ) with gr.Column(): output_image = gr.Image( label="Result", type="pil" ) with gr.Row(): clear_btn = gr.Button("Clear", variant="secondary") process_btn = gr.Button("Remove Background", variant="primary") # Status message status_msg = gr.Textbox( label="Status", placeholder="Ready to process your image...", interactive=False ) # Event handlers def process_and_update(image): if image is None: return None, "Please upload an image first" try: result = remove_background(image) return result, "✨ Background removed successfully!" except Exception as e: return None, f"❌ Error: {str(e)}" process_btn.click( fn=process_and_update, inputs=[input_image], outputs=[output_image, status_msg], ) clear_btn.click( fn=lambda: (None, None, "Ready to process your image..."), outputs=[input_image, output_image, status_msg], ) # Launch the app demo.launch()