Spaces:
Sleeping
Sleeping
| """ | |
| 🎨 Background Remover | |
| Remove fundos de imagens automaticamente usando IA | |
| Otimizado para Hugging Face Spaces | |
| """ | |
| import gradio as gr | |
| from PIL import Image | |
| import numpy as np | |
| import sys | |
| import os | |
| import tempfile | |
| from datetime import datetime | |
| print("=" * 60) | |
| print("🚀 INICIANDO APP 3: BACKGROUND REMOVER") | |
| print(f"Python version: {sys.version}") | |
| print("=" * 60) | |
| # ========== CONFIGURAÇÃO ========== | |
| print("📦 Modo: rembg (CPU-friendly)") | |
| # Importa rembg (biblioteca leve para remoção de fundo) | |
| try: | |
| from rembg import remove | |
| print("✅ rembg importado com sucesso") | |
| except ImportError: | |
| print("⚠️ rembg não encontrado, usando método fallback") | |
| remove = None | |
| def remove_background(image): | |
| """Remove o fundo da imagem""" | |
| if image is None: | |
| return None, "❌ Por favor, envie uma imagem primeiro", None | |
| try: | |
| # Converte para PIL se necessário | |
| if isinstance(image, np.ndarray): | |
| image = Image.fromarray(image) | |
| # Converte para RGB se necessário | |
| if image.mode != 'RGB': | |
| image = image.convert('RGB') | |
| print(f"📸 Processando imagem: {image.size}") | |
| # Usa rembg se disponível | |
| if remove is not None: | |
| output = remove(image) | |
| print("✅ Fundo removido com rembg") | |
| else: | |
| # Fallback: cria transparência simples baseada em cor | |
| output = create_simple_transparency(image) | |
| print("⚠️ Usando método fallback") | |
| # Salva para download | |
| temp_file = save_for_download(output) | |
| return output, "✅ Fundo removido com sucesso!", temp_file | |
| except Exception as e: | |
| error_msg = f"❌ Erro ao remover fundo: {str(e)}" | |
| print(error_msg) | |
| return None, error_msg, None | |
| def create_simple_transparency(image): | |
| """Método fallback para criar transparência""" | |
| img_array = np.array(image) | |
| # Cria canal alpha | |
| alpha = np.ones((img_array.shape[0], img_array.shape[1]), dtype=np.uint8) * 255 | |
| # Detecta cor dominante nos cantos (provavelmente fundo) | |
| corners = [ | |
| img_array[0, 0], | |
| img_array[0, -1], | |
| img_array[-1, 0], | |
| img_array[-1, -1] | |
| ] | |
| bg_color = np.mean(corners, axis=0).astype(np.uint8) | |
| # Cria máscara baseada em similaridade com a cor de fundo | |
| diff = np.abs(img_array.astype(float) - bg_color.astype(float)) | |
| mask = np.mean(diff, axis=2) < 30 # threshold de similaridade | |
| alpha[mask] = 0 | |
| # Combina com a imagem original | |
| result = Image.fromarray(np.dstack([img_array, alpha])) | |
| return result | |
| def save_for_download(image): | |
| """Salva imagem temporariamente para download""" | |
| if image is None: | |
| return None | |
| # Cria arquivo temporário | |
| timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") | |
| temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=f"_bg_removed_{timestamp}.png") | |
| # Salva imagem | |
| image.save(temp_file.name, format="PNG") | |
| print(f"💾 Imagem salva: {temp_file.name}") | |
| return temp_file.name | |
| def add_solid_background(image, bg_color): | |
| """Adiciona fundo sólido colorido""" | |
| if image is None: | |
| return None, "❌ Remova o fundo primeiro", None | |
| try: | |
| # Converte hex para RGB | |
| bg_color = bg_color.lstrip('#') | |
| r, g, b = tuple(int(bg_color[i:i+2], 16) for i in (0, 2, 4)) | |
| # Cria nova imagem com fundo colorido | |
| background = Image.new('RGB', image.size, (r, g, b)) | |
| if image.mode == 'RGBA': | |
| background.paste(image, (0, 0), image) | |
| else: | |
| background.paste(image, (0, 0)) | |
| # Salva para download | |
| temp_file = save_for_download(background) | |
| return background, f"✅ Fundo {bg_color} adicionado!", temp_file | |
| except Exception as e: | |
| return None, f"❌ Erro: {str(e)}", None | |
| def add_gradient_background(image, color1, color2): | |
| """Adiciona fundo com gradiente""" | |
| if image is None: | |
| return None, "❌ Remova o fundo primeiro", None | |
| try: | |
| # Converte cores | |
| c1 = tuple(int(color1.lstrip('#')[i:i+2], 16) for i in (0, 2, 4)) | |
| c2 = tuple(int(color2.lstrip('#')[i:i+2], 16) for i in (0, 2, 4)) | |
| # Cria gradiente | |
| width, height = image.size | |
| gradient = np.zeros((height, width, 3), dtype=np.uint8) | |
| for y in range(height): | |
| ratio = y / height | |
| color = tuple(int(c1[i] * (1 - ratio) + c2[i] * ratio) for i in range(3)) | |
| gradient[y, :] = color | |
| background = Image.fromarray(gradient) | |
| if image.mode == 'RGBA': | |
| background.paste(image, (0, 0), image) | |
| else: | |
| background.paste(image, (0, 0)) | |
| # Salva para download | |
| temp_file = save_for_download(background) | |
| return background, "✅ Gradiente adicionado!", temp_file | |
| except Exception as e: | |
| return None, f"❌ Erro: {str(e)}", None | |
| def add_blur_background(image, blur_strength): | |
| """Adiciona fundo desfocado da própria imagem""" | |
| if image is None: | |
| return None, "❌ Remova o fundo primeiro", None | |
| try: | |
| from PIL import ImageFilter | |
| # Cria versão desfocada | |
| if image.mode == 'RGBA': | |
| rgb_image = image.convert('RGB') | |
| else: | |
| rgb_image = image.copy() | |
| blurred = rgb_image.filter(ImageFilter.GaussianBlur(radius=blur_strength)) | |
| if image.mode == 'RGBA': | |
| blurred.paste(image, (0, 0), image) | |
| # Salva para download | |
| temp_file = save_for_download(blurred) | |
| return blurred, "✅ Fundo desfocado adicionado!", temp_file | |
| except Exception as e: | |
| return None, f"❌ Erro: {str(e)}", None | |
| # ========== INTERFACE GRADIO ========== | |
| print("🎨 Criando interface Background Remover...") | |
| with gr.Blocks(title="🎨 Background Remover - Photoshop AI App 3", theme=gr.themes.Soft()) as demo: | |
| gr.Markdown(""" | |
| # 🎨 Background Remover | |
| ### Remove fundos de imagens automaticamente usando IA | |
| **Como usar:** | |
| 1. 📸 Faça upload de uma imagem | |
| 2. ✂️ Clique em "Remover Fundo" | |
| 3. 🎨 Adicione um novo fundo (opcional) | |
| 4. 💾 Baixe o resultado usando o botão abaixo | |
| """) | |
| with gr.Row(): | |
| with gr.Column(): | |
| input_image = gr.Image(label="📸 Imagem Original", type="pil") | |
| with gr.Row(): | |
| remove_btn = gr.Button("✂️ Remover Fundo", variant="primary", size="lg") | |
| gr.Markdown("### 🎨 Adicionar Novo Fundo (Opcional)") | |
| with gr.Tab("🎨 Cor Sólida"): | |
| bg_color = gr.ColorPicker(label="Cor do Fundo", value="#FFFFFF") | |
| solid_btn = gr.Button("Aplicar Cor Sólida") | |
| with gr.Tab("🌈 Gradiente"): | |
| with gr.Row(): | |
| grad_color1 = gr.ColorPicker(label="Cor 1", value="#667eea") | |
| grad_color2 = gr.ColorPicker(label="Cor 2", value="#764ba2") | |
| gradient_btn = gr.Button("Aplicar Gradiente") | |
| with gr.Tab("💫 Desfoque"): | |
| blur_strength = gr.Slider(5, 50, value=20, step=5, label="Intensidade") | |
| blur_btn = gr.Button("Aplicar Desfoque") | |
| with gr.Column(): | |
| output_image = gr.Image(label="✨ Resultado", type="pil") | |
| status_text = gr.Textbox(label="📊 Status", interactive=False) | |
| # Arquivo para download | |
| download_file = gr.File(label="💾 Baixar Imagem Processada", visible=True) | |
| # Exemplos | |
| gr.Markdown("### 📋 Exemplos") | |
| if os.path.exists("examples"): | |
| gr.Examples( | |
| examples=[ | |
| ["examples/person.jpg"], | |
| ["examples/product.jpg"], | |
| ], | |
| inputs=input_image, | |
| label="Clique para testar" | |
| ) | |
| # Informações | |
| gr.Markdown(""" | |
| ### ℹ️ Informações | |
| - ✅ Suporta JPG, PNG, WEBP | |
| - ✅ Processamento automático com IA | |
| - ✅ Exporta PNG com transparência | |
| - ✅ Adicione fundos personalizados | |
| - ✅ Download direto da imagem processada | |
| ### 💡 Dicas | |
| - Use imagens com boa iluminação para melhores resultados | |
| - Fundos uniformes são mais fáceis de remover | |
| - O PNG mantém a transparência | |
| - Experimente diferentes fundos para ver o que fica melhor | |
| - Clique no arquivo acima para baixar a imagem | |
| --- | |
| **🔗 Parte do Photoshop AI Ecosystem** | App 3 de 10 | |
| """) | |
| # Event handlers | |
| remove_btn.click( | |
| fn=remove_background, | |
| inputs=[input_image], | |
| outputs=[output_image, status_text, download_file] | |
| ) | |
| solid_btn.click( | |
| fn=add_solid_background, | |
| inputs=[output_image, bg_color], | |
| outputs=[output_image, status_text, download_file] | |
| ) | |
| gradient_btn.click( | |
| fn=add_gradient_background, | |
| inputs=[output_image, grad_color1, grad_color2], | |
| outputs=[output_image, status_text, download_file] | |
| ) | |
| blur_btn.click( | |
| fn=add_blur_background, | |
| inputs=[output_image, blur_strength], | |
| outputs=[output_image, status_text, download_file] | |
| ) | |
| print("=" * 60) | |
| print("✅ APP 3: BACKGROUND REMOVER PRONTO!") | |
| print("=" * 60) | |
| if __name__ == "__main__": | |
| demo.launch() |