File size: 985 Bytes
4b2ecc5
 
d77e4f1
 
 
 
4b2ecc5
 
 
d77e4f1
4b2ecc5
 
 
d77e4f1
 
4b2ecc5
d77e4f1
 
 
 
 
 
 
 
 
 
 
 
 
4b2ecc5
 
d77e4f1
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
from fastapi import FastAPI, HTTPException
from fastapi.responses import StreamingResponse
import requests
from io import BytesIO
from PIL import Image
import rembg

app = FastAPI()

@app.get("/remove-background")
async def remove_background(image_url: str):
    try:
        # Baixa a imagem da URL fornecida
        response = requests.get(image_url)
        response.raise_for_status()
        
        # Abre a imagem usando Pillow
        image = Image.open(BytesIO(response.content))
        
        # Remove o fundo da imagem usando rembg
        output = rembg.remove(image)
        
        # Converte a imagem de volta para bytes
        img_byte_arr = BytesIO()
        output.save(img_byte_arr, format='PNG')
        img_byte_arr.seek(0)
        
        # Retorna a imagem processada diretamente no navegador
        return StreamingResponse(img_byte_arr, media_type="image/png")
    
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))