habulaj commited on
Commit
d77e4f1
·
verified ·
1 Parent(s): b5cd0d9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +21 -16
app.py CHANGED
@@ -1,27 +1,32 @@
1
  from fastapi import FastAPI, HTTPException
2
- import httpx
3
- from rembg import remove
4
- from io import BytesIO
5
  from fastapi.responses import StreamingResponse
 
 
 
 
6
 
7
  app = FastAPI()
8
 
9
- @app.get("/remove-background/")
10
  async def remove_background(image_url: str):
11
  try:
12
  # Baixa a imagem da URL fornecida
13
- async with httpx.AsyncClient() as client:
14
- response = await client.get(image_url)
15
- response.raise_for_status() # Verifica se a URL foi bem-sucedida
16
- image_data = response.content
17
 
18
- # Remover o fundo da imagem usando o rembg
19
- output_image = remove(image_data)
20
-
21
- # Retorna a imagem com o fundo removido como resposta
22
- return StreamingResponse(BytesIO(output_image), media_type="image/png")
 
 
 
 
 
 
 
 
23
 
24
- except httpx.RequestError as e:
25
- raise HTTPException(status_code=400, detail="Erro ao baixar a imagem: " + str(e))
26
  except Exception as e:
27
- raise HTTPException(status_code=500, detail="Erro ao processar a imagem: " + str(e))
 
1
  from fastapi import FastAPI, HTTPException
 
 
 
2
  from fastapi.responses import StreamingResponse
3
+ import requests
4
+ from io import BytesIO
5
+ from PIL import Image
6
+ import rembg
7
 
8
  app = FastAPI()
9
 
10
+ @app.get("/remove-background")
11
  async def remove_background(image_url: str):
12
  try:
13
  # Baixa a imagem da URL fornecida
14
+ response = requests.get(image_url)
15
+ response.raise_for_status()
 
 
16
 
17
+ # Abre a imagem usando Pillow
18
+ image = Image.open(BytesIO(response.content))
19
+
20
+ # Remove o fundo da imagem usando rembg
21
+ output = rembg.remove(image)
22
+
23
+ # Converte a imagem de volta para bytes
24
+ img_byte_arr = BytesIO()
25
+ output.save(img_byte_arr, format='PNG')
26
+ img_byte_arr.seek(0)
27
+
28
+ # Retorna a imagem processada diretamente no navegador
29
+ return StreamingResponse(img_byte_arr, media_type="image/png")
30
 
 
 
31
  except Exception as e:
32
+ raise HTTPException(status_code=400, detail=str(e))